diff --git a/packages/env/CHANGELOG.md b/packages/env/CHANGELOG.md index 711daa1573e16f..6a29673fb1aa9c 100644 --- a/packages/env/CHANGELOG.md +++ b/packages/env/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### New Features + +- The default ports `8888` (development) and `8889` (tests) now automatically fall back to the next available port when busy, so `wp-env start` works out of the box on hosts where those ports are taken; explicitly configured ports keep today's strict behavior unless `--auto-port` / `"autoPort": true` is passed, and the new `"autoPort": false` opt-out disables fallback even on the defaults. ([#49843](https://github.com/WordPress/gutenberg/issues/49843), [#74472](https://github.com/WordPress/gutenberg/pull/74472)) + ## 11.5.0 (2026-04-29) ## 11.4.0 (2026-04-15) diff --git a/packages/env/README.md b/packages/env/README.md index ed41743236e958..0f53425efd78eb 100644 --- a/packages/env/README.md +++ b/packages/env/README.md @@ -139,7 +139,7 @@ In this table, by default, you should see two entries: `wordpress` with port 888 ### 2. Check the port number -By default `wp-env` uses port 8888, meaning that the local environment will be available at http://localhost:8888. +By default `wp-env` tries port 8888, meaning that the local environment will be available at http://localhost:8888. If 8888 is busy on your host and you have not configured a port explicitly, `wp-env` automatically falls back to the next available port and prints the resolved port at start time — see [Automatic Port Selection](#automatic-port-selection) for the full contract and how to opt out. You can configure the port that `wp-env` uses so that it doesn't clash with another server by specifying the `WP_ENV_PORT` environment variable when starting `wp-env`: @@ -149,7 +149,7 @@ $ WP_ENV_PORT=3333 wp-env start Running `docker ps` and inspecting the `PORTS` column allows you to determine which port `wp-env` is currently using. -You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence. +You may also specify the port numbers in your `.wp-env.json` file, but the environment variables will take precedence. Ports you set explicitly (in `.wp-env.json`, in `.wp-env.override.json`, or via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`) are never silently moved; if you need them to also auto-fall-back when busy, see the `--auto-port` flag in [Automatic Port Selection](#automatic-port-selection). ### 3. Restart `wp-env` with updates @@ -365,8 +365,10 @@ Options: [string] --scripts Execute any configured lifecycle scripts. [boolean] [default: true] - --auto-port Automatically find available ports when configured ports are - busy. [boolean] + --auto-port Also fall back to the next available port when explicitly + configured ports are busy. By default, only the standard ports + 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" + setting. [boolean] ``` ### `wp-env stop` @@ -606,7 +608,7 @@ To enable editor autocomplete and validation, add a `$schema` key: | `"port"` | `integer` | `8888` | The port number to use for the installation. | | `"testsEnvironment"` | `boolean` | `false` | _Deprecated._ Whether to create a separate test environment with its own database and containers. Use `--config` with a separate config file instead. | | `"testsPort"` | `integer` | `8889` | The port number for the test site. | -| `"autoPort"` | `boolean` | `false` | Whether to automatically find available HTTP ports when configured ports are busy. | +| `"autoPort"` | `boolean\|null`| `null` (defaults only) | Tri-state automatic HTTP port selection. When `null` (the default), the default ports `8888`/`8889` automatically fall back to the next available port if busy, but explicitly configured ports stay strict. Set to `true` to also fall back on user-set ports. Set to `false` to opt out entirely, including on the default ports. | | `"config"` | `Object` | See below. | Mapping of wp-config.php constants to their desired values. | | `"mappings"` | `Object` | `"{}"` | Mapping of WordPress directories to local directories to be mounted in the WordPress instance. | | `"mysqlPort"` | `integer` | `null` (randomly assigned) | The MySQL port number to expose. | @@ -619,15 +621,25 @@ _Note: the port number environment variable (`WP_ENV_PORT`) takes precedence ove ### Automatic Port Selection -By default, `wp-env` uses fixed ports (`8888` for development, `8889` for tests). If a port is busy, Docker will report an error at start time. +By default, `wp-env` tries the standard ports (`8888` for development, `8889` for tests). If you have not configured a port explicitly and one of those defaults is busy on the host, `wp-env` scans upward to the next available port (for example: `8888` → `8890` → `8891`, ...) and starts the environment there. The CLI prints a one-line notice through the same spinner used for other start-time messages so you can see which port was actually bound. -To opt in to automatic port selection, pass the `--auto-port` flag: +Ports that you configured yourself — through `port` / `testsPort` in `.wp-env.json`, in `.wp-env.override.json`, via `WP_ENV_PORT` / `WP_ENV_TESTS_PORT`, or any combination — are never silently moved. If your configured port is busy, the start fails with the existing port-conflict error so your explicit choice is honored. + +If you want auto-fallback to apply to your configured ports too, pass the `--auto-port` flag (or set `"autoPort": true` in `.wp-env.json`): ```sh wp-env start --auto-port ``` -When `--auto-port` (or `"autoPort": true`) is enabled and a configured port is busy, `wp-env` scans upward from the configured port to find the next available one (for example: `8888`, `8889`, `8890`, ...). Automatic port selection is disabled when `CI` is set. +To opt out of the default-port fallback as well — for example, when you want a hard guarantee that `wp-env` only ever binds `8888`/`8889` — set `"autoPort": false` in `.wp-env.json`: + +```json +{ + "autoPort": false +} +``` + +Automatic port selection is also disabled whenever the `CI` environment variable is set, regardless of the `autoPort` value, so test runs stay deterministic. Several types of strings can be passed into the `core`, `plugins`, `themes`, and `mappings` fields. diff --git a/packages/env/lib/cli.js b/packages/env/lib/cli.js index 9452fce24707c0..e5619861c714bc 100644 --- a/packages/env/lib/cli.js +++ b/packages/env/lib/cli.js @@ -154,7 +154,7 @@ module.exports = function cli() { args.option( 'auto-port', { type: 'boolean', describe: - 'Automatically find available ports when configured ports are busy. Overrides the .wp-env.json "autoPort" setting.', + 'Also fall back to the next available port when explicitly configured ports are busy. By default, only the standard ports 8888/8889 auto-fall-back. Overrides the .wp-env.json "autoPort" setting.', } ); }, withSpinner( env.start ) diff --git a/packages/env/lib/commands/start.js b/packages/env/lib/commands/start.js index 91da7f592c7b46..be54bb70d4af90 100644 --- a/packages/env/lib/commands/start.js +++ b/packages/env/lib/commands/start.js @@ -21,16 +21,16 @@ const { getRuntime, getSavedRuntime, saveRuntime } = require( '../runtime' ); /** * Starts the development server. * - * @param {Object} options - * @param {Object} options.spinner A CLI spinner which indicates progress. - * @param {boolean} options.update If true, update sources. - * @param {string} options.xdebug The Xdebug mode to set. - * @param {string} options.spx The SPX mode to set. - * @param {boolean} options.scripts Indicates whether or not lifecycle scripts should be executed. - * @param {boolean} options.debug True if debug mode is enabled. - * @param {string} options.runtime The runtime to use ('docker' or 'playground'). - * @param {boolean} options.autoPort If true, automatically find available ports when configured ports are busy. - * @param {string|null} options.config Path to a custom .wp-env.json configuration file. + * @param {Object} options + * @param {Object} options.spinner A CLI spinner which indicates progress. + * @param {boolean} options.update If true, update sources. + * @param {string} options.xdebug The Xdebug mode to set. + * @param {string} options.spx The SPX mode to set. + * @param {boolean} options.scripts Indicates whether or not lifecycle scripts should be executed. + * @param {boolean} options.debug True if debug mode is enabled. + * @param {string} options.runtime The runtime to use ('docker' or 'playground'). + * @param {boolean|undefined} options.autoPort Tri-state: `true` enables automatic port fallback for every port (including user-set ones); `false` disables fallback even on default ports; `undefined` (the typical case — flag not supplied) defers to `.wp-env.json`'s `autoPort` field, where unset/`null` means "auto-fallback only on default ports `8888`/`8889`". + * @param {string|null} options.config Path to a custom .wp-env.json configuration file. */ module.exports = async function start( { spinner, diff --git a/packages/env/lib/config/load-config.js b/packages/env/lib/config/load-config.js index 89fb07a2595c19..72ed01dfa33ba2 100644 --- a/packages/env/lib/config/load-config.js +++ b/packages/env/lib/config/load-config.js @@ -37,12 +37,12 @@ const { createPortResolver } = require( '../resolve-available-ports' ); /** * Loads any configuration from a given directory. * - * @param {string} configDirectoryPath The directory we want to load the config from. - * @param {string|null} customConfigPath Optional custom config file path. - * @param {Object} options Options for loading the config. - * @param {boolean} options.resolvePorts Whether HTTP ports should be resolved for this command. - * @param {boolean} options.autoPort CLI override for automatic port selection. - * @param {Object} options.spinner A CLI spinner used by the port resolver. + * @param {string} configDirectoryPath The directory we want to load the config from. + * @param {string|null} customConfigPath Optional custom config file path. + * @param {Object} options Options for loading the config. + * @param {boolean} options.resolvePorts Whether HTTP ports should be resolved for this command. + * @param {boolean|undefined} options.autoPort Tri-state CLI override for automatic port selection: `true` enables fallback for all ports, `false` disables fallback even on default ports, `undefined` defers to `config.autoPort` (which itself is tri-state — `null`/`undefined` means "fallback only on default ports"). + * @param {Object} options.spinner A CLI spinner used by the port resolver. * * @return {Promise} The config object we've loaded. */ @@ -93,25 +93,44 @@ module.exports = async function loadConfig( customConfigPath ); - let portResolver; - if ( resolvePorts ) { - let shouldAutoPort = - autoPort !== undefined ? autoPort : config.autoPort; + // Compute the tri-state auto-port mode. Precedence: CLI option beats + // config.autoPort. CLI `true`/`false` are explicit; `undefined` defers + // to the parsed config value (which itself is tri-state — `null` / + // `undefined` means "unset, use the new defaults-only behavior"). + let autoPortMode; + const effectiveAutoPort = + autoPort !== undefined ? autoPort : config.autoPort; + if ( effectiveAutoPort === true ) { + autoPortMode = 'all'; + } else if ( effectiveAutoPort === false ) { + autoPortMode = 'off'; + } else { + autoPortMode = 'defaults-only'; + } - // Automatic port selection is undesirable in CI where determinism matters. - if ( process.env.CI ) { - shouldAutoPort = false; - } + // Automatic port selection is undesirable in CI where determinism matters. + if ( process.env.CI ) { + autoPortMode = 'off'; + } - if ( shouldAutoPort ) { - portResolver = createPortResolver( spinner ); - } + let portResolver; + if ( resolvePorts && autoPortMode !== 'off' ) { + portResolver = createPortResolver( spinner ); } + // Read the per-port provenance attached by `parseConfig`. Falls back to + // an empty set so callers that bypass `parseConfig` (e.g. some tests) + // keep working. + const defaultOriginPorts = config.__defaultOriginPorts ?? new Set(); + // Make sure to perform any additional post-processing that // may be needed before the config object is ready for // consumption elsewhere in the tool. - config = await postProcessConfig( config, { portResolver } ); + config = await postProcessConfig( config, { + portResolver, + autoPortMode, + defaultOriginPorts, + } ); return { name: path.basename( configDirectoryPath ), diff --git a/packages/env/lib/config/parse-config.js b/packages/env/lib/config/parse-config.js index 9ee50cdd5275f0..1de3563a4b110a 100644 --- a/packages/env/lib/config/parse-config.js +++ b/packages/env/lib/config/parse-config.js @@ -35,7 +35,7 @@ const mergeConfigs = require( './merge-configs' ); * @typedef WPRootConfigOptions * @property {number} port The port to use in the development environment. * @property {number} testsPort The port to use in the tests environment. - * @property {boolean} autoPort Whether to automatically select a nearby available HTTP port. + * @property {boolean|null} autoPort Tri-state: `null` (unset, default behavior — auto-fallback only on default ports), `true` (auto-fallback for all ports), `false` (strict for all ports). * @property {Object.} lifecycleScripts The scripts to run at certain points in the command lifecycle. * @property {Object.} lifecycleScripts.afterStart The script to run after the "start" command has completed. * @property {Object.} lifecycleScripts.afterClean The script to run after the "clean" command has completed. @@ -90,7 +90,7 @@ const DEFAULT_ENVIRONMENT_CONFIG = { themes: [], port: 8888, testsPort: 8889, - autoPort: false, + autoPort: null, mysqlPort: null, phpmyadmin: false, phpmyadminPort: null, @@ -159,12 +159,115 @@ async function parseConfig( // Merge all of our configs so that we have a complete object // containing the desired options in order of precedence. - return mergeConfigs( + const merged = mergeConfigs( defaultConfig, localConfig ?? {}, overrideConfig ?? {}, environmentVarOverrides ); + + // Track which HTTP ports came from `DEFAULT_ENVIRONMENT_CONFIG` versus + // any user-supplied source. This is consumed by the port resolver to + // decide whether to silently fall back to the next available port (for + // default-origin ports) or to surface a strict port-busy error (for + // user-set ports). Stored as a non-enumerable property so it does not + // participate in `mergeConfig` iteration, JSON serialization, or + // `toEqual` equality checks performed elsewhere. + const defaultOriginPorts = computeDefaultOriginPorts( + localConfig, + overrideConfig, + environmentVarOverrides + ); + Object.defineProperty( merged, '__defaultOriginPorts', { + value: defaultOriginPorts, + enumerable: false, + writable: false, + configurable: false, + } ); + + return merged; +} + +/** + * Computes the set of HTTP port keys whose effective value comes from + * `DEFAULT_ENVIRONMENT_CONFIG` (i.e. no user-supplied source provided them). + * + * The returned Set contains zero or more of the strings `'development.port'` + * and `'tests.port'`. Each key is included when none of the user-supplied + * sources (root `.wp-env.json`, `.wp-env.override.json`, or environment + * variables) provide a value for that port. + * + * @param {Object|null} localConfig The parsed local config, or null when absent. + * @param {Object|null} overrideConfig The parsed override config, or null when absent. + * @param {Object} environmentVarOverrides The config-shaped object derived from env vars. + * + * @return {Set} The set of default-origin port keys. + */ +function computeDefaultOriginPorts( + localConfig, + overrideConfig, + environmentVarOverrides +) { + const result = new Set(); + + const isDevelopmentPortUserSet = + layerSetsDevelopmentPort( localConfig ) || + layerSetsDevelopmentPort( overrideConfig ) || + layerSetsDevelopmentPort( environmentVarOverrides ); + + const isTestsPortUserSet = + layerSetsTestsPort( localConfig ) || + layerSetsTestsPort( overrideConfig ) || + layerSetsTestsPort( environmentVarOverrides ); + + if ( ! isDevelopmentPortUserSet ) { + result.add( 'development.port' ); + } + if ( ! isTestsPortUserSet ) { + result.add( 'tests.port' ); + } + + return result; +} + +/** + * Whether the given config layer provides a value for the development HTTP port. + * + * @param {Object|null|undefined} layer The config layer to inspect. + * + * @return {boolean} True when the layer sets the development port. + */ +function layerSetsDevelopmentPort( layer ) { + if ( ! layer ) { + return false; + } + if ( layer.port !== undefined ) { + return true; + } + if ( layer.env?.development?.port !== undefined ) { + return true; + } + return false; +} + +/** + * Whether the given config layer provides a value for the tests HTTP port. + * + * @param {Object|null|undefined} layer The config layer to inspect. + * + * @return {boolean} True when the layer sets the tests port. + */ +function layerSetsTestsPort( layer ) { + if ( ! layer ) { + return false; + } + if ( layer.testsPort !== undefined ) { + return true; + } + if ( layer.env?.tests?.port !== undefined ) { + return true; + } + return false; } /** @@ -388,7 +491,12 @@ async function parseRootConfig( configFile, rawConfig, options ) { parsedConfig.testsPort = rawConfig.testsPort; } if ( rawConfig.autoPort !== undefined ) { - if ( typeof rawConfig.autoPort !== 'boolean' ) { + // `null` is a valid tri-state value meaning "unset" (the default). + // Only user-provided autoPort values must be booleans. + if ( + rawConfig.autoPort !== null && + typeof rawConfig.autoPort !== 'boolean' + ) { throw new ValidationError( `Invalid ${ configFile }: "autoPort" must be a boolean.` ); diff --git a/packages/env/lib/config/post-process-config.js b/packages/env/lib/config/post-process-config.js index 13cd180e68c21c..d04b0d90c693fd 100644 --- a/packages/env/lib/config/post-process-config.js +++ b/packages/env/lib/config/post-process-config.js @@ -15,15 +15,17 @@ const { resolveConfigPorts } = require( '../resolve-available-ports' ); /** * Performs any additional post-processing on the config object. * - * @param {WPEnvironmentConfig} config The config to process. - * @param {Object} options Options for post-processing. - * @param {Object} options.portResolver An optional port resolver for automatic port selection. + * @param {WPEnvironmentConfig} config The config to process. + * @param {Object} options Options for post-processing. + * @param {Object} options.portResolver An optional port resolver for automatic port selection. + * @param {'off'|'all'|'defaults-only'} options.autoPortMode The auto-port routing mode. `'off'` disables fallback (strict); `'all'` enables fallback for every port (today's PR #74472 behavior); `'defaults-only'` enables fallback only on default-origin HTTP ports (the new default behavior). Defaults to `'off'` so existing call sites that do not opt in keep their current behavior. + * @param {Set} options.defaultOriginPorts The set of port keys (e.g. `'development.port'`, `'tests.port'`) whose effective value comes from the default config rather than any user-supplied source. Used by `'defaults-only'` mode to decide which ports may auto-fall-back. Defaults to an empty set. * * @return {Promise} The config after post-processing. */ module.exports = async function postProcessConfig( config, - { portResolver } = {} + { portResolver, autoPortMode = 'off', defaultOriginPorts = new Set() } = {} ) { // Make sure that we're operating on a config object that has // complete environment configs for convenience. @@ -33,7 +35,10 @@ module.exports = async function postProcessConfig( // but before appending ports to URLs. This way appendPortToWPConfigs // uses the resolved ports and we don't need to fix URLs afterward. if ( portResolver ) { - config = await resolveConfigPorts( config, portResolver ); + config = await resolveConfigPorts( config, portResolver, { + autoPortMode, + defaultOriginPorts, + } ); } config = appendPortToWPConfigs( config ); diff --git a/packages/env/lib/config/test/config-integration.js b/packages/env/lib/config/test/config-integration.js index d503a35163f5dd..2440dbf9b453b5 100644 --- a/packages/env/lib/config/test/config-integration.js +++ b/packages/env/lib/config/test/config-integration.js @@ -12,6 +12,7 @@ const { existsSync } = require( 'fs' ); const loadConfig = require( '../load-config' ); const detectDirectoryType = require( '../detect-directory-type' ); const md5 = require( '../../md5' ); +const { findAvailablePort, isPortAvailable } = require( '../../port-utils' ); jest.mock( 'fs', () => ( { promises: { @@ -23,6 +24,8 @@ jest.mock( 'fs', () => ( { existsSync: jest.fn().mockReturnValue( false ), } ) ); +jest.mock( '../../port-utils' ); + // This mocks a small response with a format matching the stable-check API. // It makes getLatestWordPressVersion resolve to "100.0.0". jest.mock( 'got', () => @@ -43,9 +46,17 @@ jest.mock( 'got', () => jest.mock( '../detect-directory-type', () => jest.fn() ); describe( 'Config Integration', () => { + // Save the inherited CI value so we can restore it after each test + // (the new tests below stomp on `process.env.CI` to assert the guard). + let originalCI; + beforeEach( () => { process.env.WP_ENV_HOME = '/cache'; detectDirectoryType.mockResolvedValue( null ); + originalCI = process.env.CI; + // Force-disable CI for tests that exercise the auto-fallback paths. + // Tests that need CI on opt back in explicitly. + delete process.env.CI; } ); afterEach( () => { @@ -55,6 +66,13 @@ describe( 'Config Integration', () => { delete process.env.WP_ENV_TESTS_PORT; delete process.env.WP_ENV_TESTS_MYSQL_PORT; delete process.env.WP_ENV_LIFECYCLE_SCRIPT_AFTER_START; + // Restore the inherited CI value, if any. + if ( originalCI === undefined ) { + delete process.env.CI; + } else { + process.env.CI = originalCI; + } + jest.clearAllMocks(); } ); it( 'should use default configuration', async () => { @@ -204,6 +222,169 @@ describe( 'Config Integration', () => { expect( config ).toMatchSnapshot(); } ); + describe( 'auto-port fallback (tri-state autoPort)', () => { + const stubSpinner = () => ( { + text: '', + info: jest.fn(), + start: jest.fn(), + fail: jest.fn(), + warn: jest.fn(), + stop: jest.fn(), + } ); + + it( 'with no user autoPort and busy default port falls back via defaults-only mode (AC1)', async () => { + readFile.mockImplementation( async () => { + throw { code: 'ENOENT' }; + } ); + + // Default port 8888 is busy; the resolver should hand back 8890. + findAvailablePort.mockImplementation( ( { preferredPort } ) => { + if ( preferredPort === 8888 ) { + return Promise.resolve( 8890 ); + } + return Promise.resolve( preferredPort ); + } ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + expect( config.env.development.port ).toEqual( 8890 ); + expect( config.env.development.config.WP_HOME ).toEqual( + 'http://localhost:8890' + ); + expect( config.env.development.config.WP_SITEURL ).toEqual( + 'http://localhost:8890' + ); + } ); + + it( 'with autoPort:false in user config skips fallback even on default ports (AC5)', async () => { + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { autoPort: false } ); + } + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockResolvedValue( 8890 ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + // autoPort:false forces 'off' mode, so the auto-fallback path + // (`findAvailablePort`) is never called. The default port stays + // as configured; any port-busy error surfaces later at the + // Docker bind layer with the existing message. + expect( findAvailablePort ).not.toHaveBeenCalled(); + expect( config.env.development.port ).toEqual( 8888 ); + } ); + + it( 'with CI=1 disables fallback regardless of autoPort:true in user config (AC6 + AC8 regression detector)', async () => { + process.env.CI = '1'; + + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { autoPort: true } ); + } + throw { code: 'ENOENT' }; + } ); + + // Mock both port-utils functions so we can detect which path + // (if any) was taken. Strict path uses isPortAvailable; + // auto-fallback path uses findAvailablePort. + findAvailablePort.mockResolvedValue( 8890 ); + isPortAvailable.mockResolvedValue( true ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + // AC8 regression detector: even with autoPort:true the CI guard + // forces 'off' mode, so the resolver is not created at all and + // the auto-fallback path (`findAvailablePort`) is never called. + // Removing the `if ( process.env.CI )` guard in load-config.js + // would call findAvailablePort and fail this expectation. + expect( findAvailablePort ).not.toHaveBeenCalled(); + // Default port stays as configured because no resolver fired. + expect( config.env.development.port ).toEqual( 8888 ); + } ); + + it( 'with CI=1 disables fallback even when autoPort is unset (AC6)', async () => { + process.env.CI = '1'; + + readFile.mockImplementation( async () => { + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockResolvedValue( 8890 ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + spinner: stubSpinner(), + } ); + + // CI guard short-circuits the new defaults-only mode. + expect( findAvailablePort ).not.toHaveBeenCalled(); + expect( config.env.development.port ).toEqual( 8888 ); + } ); + + it( 'with CLI autoPort=true and user config autoPort=false has CLI win (AC4 precedence)', async () => { + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { autoPort: false } ); + } + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockImplementation( ( { preferredPort } ) => { + if ( preferredPort === 8888 ) { + return Promise.resolve( 8890 ); + } + return Promise.resolve( preferredPort ); + } ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + autoPort: true, + spinner: stubSpinner(), + } ); + + // CLI true wins over config false → fallback fired. + expect( config.env.development.port ).toEqual( 8890 ); + } ); + + it( 'with CLI autoPort=true and explicit user port falls back when port is busy (AC4 behavior-level)', async () => { + readFile.mockImplementation( async ( fileName ) => { + if ( fileName === '/test/gutenberg/.wp-env.json' ) { + return JSON.stringify( { port: 9000 } ); + } + throw { code: 'ENOENT' }; + } ); + + findAvailablePort.mockImplementation( ( { preferredPort } ) => { + if ( preferredPort === 9000 ) { + return Promise.resolve( 9001 ); + } + return Promise.resolve( preferredPort ); + } ); + + const config = await loadConfig( '/test/gutenberg', null, { + resolvePorts: true, + autoPort: true, + spinner: stubSpinner(), + } ); + + expect( config.env.development.port ).toEqual( 9001 ); + expect( config.env.development.config.WP_HOME ).toEqual( + 'http://localhost:9001' + ); + } ); + } ); + describe( 'cache directory naming', () => { beforeEach( () => { readFile.mockImplementation( async () => { diff --git a/packages/env/lib/config/test/parse-config.js b/packages/env/lib/config/test/parse-config.js index 7d0803af3cdef3..e8e70a5340dba7 100644 --- a/packages/env/lib/config/test/parse-config.js +++ b/packages/env/lib/config/test/parse-config.js @@ -21,7 +21,7 @@ jest.mock( '../../wordpress', () => ( { const DEFAULT_CONFIG = { port: 8888, testsPort: 8889, - autoPort: false, + autoPort: null, mysqlPort: null, phpmyadmin: false, phpmyadminPort: null, @@ -193,7 +193,13 @@ describe( 'parseConfig', () => { expect( parsed ).toEqual( expected ); } ); - it( 'should accept autoPort as a boolean', async () => { + it( 'should accept autoPort as a tri-state (null default, true, false)', async () => { + // 1. With no user config, the default is `null` (the new tri-state + // "unset" sentinel — distinguishable from explicit `false`). + const defaultParsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( defaultParsed.autoPort ).toBeNull(); + + // 2. Explicit `true` survives merge. readRawConfigFile.mockImplementation( async ( configFile ) => { if ( configFile === '/test/gutenberg/.wp-env.json' ) { return { @@ -201,9 +207,21 @@ describe( 'parseConfig', () => { }; } } ); + const parsedTrue = await parseConfig( '/test/gutenberg', '/cache' ); + expect( parsedTrue.autoPort ).toEqual( true ); - const parsed = await parseConfig( '/test/gutenberg', '/cache' ); - expect( parsed.autoPort ).toEqual( true ); + // 3. Explicit `false` survives merge and is observably distinct + // from the default `null` (this is the AC11 boundary check). + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.json' ) { + return { + autoPort: false, + }; + } + } ); + const parsedFalse = await parseConfig( '/test/gutenberg', '/cache' ); + expect( parsedFalse.autoPort ).toEqual( false ); + expect( parsedFalse.autoPort ).not.toBeNull(); } ); it( 'should parse core, plugin, theme, and mapping sources', async () => { @@ -590,4 +608,120 @@ describe( 'parseConfig', () => { ) ); } ); + + describe( '__defaultOriginPorts provenance', () => { + it( 'attaches __defaultOriginPorts as a non-enumerable Set with both http ports when no user config sets them', async () => { + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + + expect( parsed.__defaultOriginPorts ).toBeInstanceOf( Set ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( true ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + expect( parsed.__defaultOriginPorts.size ).toBe( 2 ); + + expect( + Object.prototype.propertyIsEnumerable.call( + parsed, + '__defaultOriginPorts' + ) + ).toBe( false ); + } ); + + it( 'omits development.port from __defaultOriginPorts when local config sets root port', async () => { + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.json' ) { + return { port: 9000 }; + } + } ); + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( false ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + } ); + + it( 'omits tests.port from __defaultOriginPorts when local config sets env.tests.port', async () => { + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.json' ) { + return { + env: { + tests: { port: 9001 }, + }, + }; + } + } ); + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( true ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + false + ); + } ); + + it( 'omits development.port from __defaultOriginPorts when override config sets port', async () => { + readRawConfigFile.mockImplementation( async ( configFile ) => { + if ( configFile === '/test/gutenberg/.wp-env.override.json' ) { + return { port: 9000 }; + } + } ); + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( false ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + } ); + + it( 'omits development.port from __defaultOriginPorts when WP_ENV_PORT is set', async () => { + process.env.WP_ENV_PORT = '4321'; + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( false ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + true + ); + } ); + + it( 'omits tests.port from __defaultOriginPorts when WP_ENV_TESTS_PORT is set', async () => { + process.env.WP_ENV_TESTS_PORT = '5432'; + + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + expect( + parsed.__defaultOriginPorts.has( 'development.port' ) + ).toBe( true ); + expect( parsed.__defaultOriginPorts.has( 'tests.port' ) ).toBe( + false + ); + } ); + + it( '__defaultOriginPorts is invisible to mergeConfigs and toEqual (regression guard for non-enumerable contract)', async () => { + const parsed = await parseConfig( '/test/gutenberg', '/cache' ); + + // JSON round-trip must drop the non-enumerable property. + const roundTripped = JSON.parse( JSON.stringify( parsed ) ); + expect( roundTripped.__defaultOriginPorts ).toBeUndefined(); + + // `toEqual` against the publicly-known DEFAULT_CONFIG must still + // pass (i.e. Jest's deep-equal does not consider the + // non-enumerable property). + expect( parsed ).toEqual( DEFAULT_CONFIG ); + + // `Object.keys` / `for…in` / `Object.entries` must all skip it. + expect( Object.keys( parsed ) ).not.toContain( + '__defaultOriginPorts' + ); + } ); + } ); } ); diff --git a/packages/env/lib/config/test/post-process-config.js b/packages/env/lib/config/test/post-process-config.js index d66e096991dd37..67f5af21a04b6c 100644 --- a/packages/env/lib/config/test/post-process-config.js +++ b/packages/env/lib/config/test/post-process-config.js @@ -348,6 +348,246 @@ describe( 'postProcessConfig', () => { } ); } ); + describe( 'port resolver routing (autoPortMode + defaultOriginPorts)', () => { + it( 'threads autoPortMode and defaultOriginPorts to resolveConfigPorts', async () => { + // Mock the resolver to return distinct fallback ports so the + // post-processed config does not trip validatePortUniqueness. + const portResolver = { + resolve: jest + .fn() + .mockResolvedValueOnce( 8890 ) + .mockResolvedValueOnce( 8891 ), + }; + + const processed = await postProcessConfig( + { + env: { + development: { + port: 8888, + config: { + WP_HOME: 'http://localhost', + WP_SITEURL: 'http://localhost', + }, + }, + tests: { + port: 8889, + config: { + WP_HOME: 'http://localhost', + WP_SITEURL: 'http://localhost', + }, + }, + }, + }, + { + portResolver, + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ + 'development.port', + 'tests.port', + ] ), + } + ); + + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + false + ); + // Resolved port flows into the merged env config and into + // appendPortToWPConfigs's WP_HOME / WP_SITEURL outputs. + expect( processed.env.development.port ).toEqual( 8890 ); + expect( processed.env.development.config.WP_HOME ).toEqual( + 'http://localhost:8890' + ); + expect( processed.env.development.config.WP_SITEURL ).toEqual( + 'http://localhost:8890' + ); + expect( processed.env.tests.port ).toEqual( 8891 ); + expect( processed.env.tests.config.WP_HOME ).toEqual( + 'http://localhost:8891' + ); + } ); + + it( 'with autoPortMode=defaults-only routes user-set port to strict and default-origin port to non-strict', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { port: 8888 }, + tests: { port: 9001 }, + }, + }, + { + portResolver, + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ 'development.port' ] ), + } + ); + + // development.port is default-origin → non-strict (false). + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + // tests.port is user-set → strict (true). + expect( portResolver.resolve ).toHaveBeenCalledWith( + 9001, + 'env.tests.port', + true + ); + } ); + + it( 'with autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { + port: 8889, + }, + }, + }, + { + portResolver, + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ + 'development.port', + 'tests.port', + ] ), + } + ); + + // Resolver was called for HTTP ports. + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + false + ); + // Resolver was NEVER called for phpmyadminPort under + // defaults-only mode (preserving today's behavior verbatim + // where phpmyadminPort is only auto-resolved under --auto-port). + const phpmyadminCalls = portResolver.resolve.mock.calls.filter( + ( call ) => call[ 1 ].includes( 'phpmyadminPort' ) + ); + expect( phpmyadminCalls ).toHaveLength( 0 ); + } ); + + it( 'with autoPortMode=all routes both http ports AND phpmyadminPort non-strict (preserves PR #74472 behavior)', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }, + { + portResolver, + autoPortMode: 'all', + defaultOriginPorts: new Set(), + } + ); + + // All three ports get the non-strict (false) third argument. + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + false + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8080, + 'env.development.phpmyadminPort', + false + ); + } ); + + it( 'defaults to autoPortMode=off and routes ports strict (back-compat for callers that do not pass options)', async () => { + const portResolver = { + resolve: jest + .fn() + .mockImplementation( ( preferred ) => + Promise.resolve( preferred ) + ), + }; + + await postProcessConfig( + { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }, + { portResolver } + ); + + // All ports get strict=true under the default 'off' mode. + // Note that 'off' does NOT skip phpmyadminPort — only + // 'defaults-only' does (the skip rule is mode-specific). + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8888, + 'env.development.port', + true + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8889, + 'env.tests.port', + true + ); + expect( portResolver.resolve ).toHaveBeenCalledWith( + 8080, + 'env.development.phpmyadminPort', + true + ); + } ); + } ); + describe( 'testsEnvironment', () => { it( 'should ignore env overrides entirely when testsEnvironment is false', async () => { const processed = await postProcessConfig( { diff --git a/packages/env/lib/resolve-available-ports.js b/packages/env/lib/resolve-available-ports.js index 81e0584c8e62c6..a6cce60da9caa8 100644 --- a/packages/env/lib/resolve-available-ports.js +++ b/packages/env/lib/resolve-available-ports.js @@ -77,6 +77,18 @@ function createPortResolver( spinner ) { exclude: usedPorts, } ); + // Inform the user via the existing spinner channel when the + // preferred port was busy and we fell back to a different + // one. Reuses the same spinner instance the resolver already + // holds — introducing a separate logger or stream would be + // a regression detected by the test suite (AC7). + if ( spinner && resolvedPort !== preferredPort ) { + spinner.info( + `Port ${ preferredPort } (${ configPath }) was busy; using ${ resolvedPort } instead.` + ); + spinner.start(); + } + usedPorts.push( resolvedPort ); return resolvedPort; @@ -93,11 +105,18 @@ function createPortResolver( spinner ) { * Resolves available ports on a config object. Iterates over the * defined port properties and resolves each one that has a value. * - * @param {Object} config The config object (after mergeRootToEnvironments). - * @param {Object} portResolver A port resolver created by `createPortResolver`. + * @param {Object} config The config object (after mergeRootToEnvironments). + * @param {Object} portResolver A port resolver created by `createPortResolver`. + * @param {Object} [options] Routing options. + * @param {'off'|'all'|'defaults-only'} [options.autoPortMode] The auto-port routing mode. `'off'` forces strict per-port (production never reaches this branch because the resolver itself is not created in `'off'` mode). `'all'` mirrors today's `--auto-port` behavior — every port (including phpmyadminPort) auto-falls-back. `'defaults-only'` only auto-falls-back HTTP ports whose value originated from the default config; user-set HTTP ports stay strict, and `phpmyadminPort` is skipped entirely (preserving today's behavior verbatim — phpmyadminPort is only resolved when the user explicitly opts in via `--auto-port`). + * @param {Set} [options.defaultOriginPorts] The set of port keys (e.g. `'development.port'`, `'tests.port'`) whose effective value comes from the default config rather than any user-supplied source. Used by `'defaults-only'` mode. * @return {Promise} The config with resolved ports. */ -async function resolveConfigPorts( config, portResolver ) { +async function resolveConfigPorts( + config, + portResolver, + { autoPortMode = 'off', defaultOriginPorts = new Set() } = {} +) { for ( const { env, property } of PORT_DEFINITIONS ) { const currentValue = config.env[ env ][ property ]; @@ -107,6 +126,14 @@ async function resolveConfigPorts( config, portResolver ) { continue; } + // Per-port skip rule. Under `defaults-only` mode we deliberately + // do not resolve `phpmyadminPort` at all so its behavior is + // identical to today's: it is only auto-resolved when the user + // has explicitly opted in via `--auto-port` (the `'all'` mode). + if ( autoPortMode === 'defaults-only' && property !== 'port' ) { + continue; + } + // Use a well-known preferred port when one isn't explicitly set. // For explicit ports, use the configured value. const key = `${ env }.${ property }`; @@ -117,12 +144,31 @@ async function resolveConfigPorts( config, portResolver ) { continue; } - // When --auto-port is active (the only time this runs), - // always auto-fallback to an available port. + // Decide whether this port participates in auto-fallback. + // - `'off'` → strict (defensive; the resolver is normally not + // created in this mode, so this branch is reachable only when + // the function is unit-tested directly). + // - `'all'` → non-strict for every port. Preserves today's + // `--auto-port` behavior, including the phpmyadminPort path. + // - `'defaults-only'` → non-strict only for HTTP ports whose value + // came from `DEFAULT_ENVIRONMENT_CONFIG`. User-set HTTP ports + // stay strict so the existing port-busy error surfaces. + let strict; + if ( autoPortMode === 'off' ) { + strict = true; + } else if ( autoPortMode === 'all' ) { + strict = false; + } else { + // 'defaults-only' — only `property === 'port'` reaches here + // because of the skip rule above. + strict = ! defaultOriginPorts.has( key ); + } + const configPath = `env.${ key }`; config.env[ env ][ property ] = await portResolver.resolve( preferredPort, - configPath + configPath, + strict ); } diff --git a/packages/env/lib/test/resolve-available-ports.js b/packages/env/lib/test/resolve-available-ports.js index 049ab6c8e4db0b..385c22588bab7e 100644 --- a/packages/env/lib/test/resolve-available-ports.js +++ b/packages/env/lib/test/resolve-available-ports.js @@ -77,7 +77,9 @@ describe( 'resolve-available-ports', () => { }, }; - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); // Null ports should be resolved using preferred ports. expect( findAvailablePort ).toHaveBeenCalledWith( @@ -101,7 +103,9 @@ describe( 'resolve-available-ports', () => { }, }; - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); expect( config.env.development.port ).toBe( 9000 ); expect( config.env.tests.port ).toBe( 9001 ); @@ -125,7 +129,9 @@ describe( 'resolve-available-ports', () => { }, }; - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); // phpmyadminPort should use findAvailablePort (non-strict), // not isPortAvailable (strict), even with an explicit value. @@ -145,11 +151,246 @@ describe( 'resolve-available-ports', () => { }; findAvailablePort.mockResolvedValue( 8888 ); - await resolveConfigPorts( config, resolver ); + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); // phpmyadminPort is undefined so should not trigger any resolution. expect( config.env.development.phpmyadminPort ).toBeUndefined(); expect( config.env.tests.phpmyadminPort ).toBeUndefined(); } ); + + it( 'under autoPortMode=defaults-only uses strict mode for non-default-origin ports and non-strict for default-origin ports', async () => { + findAvailablePort.mockImplementation( ( { preferredPort } ) => + Promise.resolve( preferredPort ) + ); + isPortAvailable.mockResolvedValue( true ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { port: 8888 }, + tests: { port: 9001 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ 'development.port' ] ), + } ); + + // Default-origin development port → non-strict (findAvailablePort). + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8888 } ) + ); + // User-set tests port → strict (isPortAvailable). + expect( isPortAvailable ).toHaveBeenCalledWith( 9001 ); + } ); + + it( 'under autoPortMode=defaults-only skips phpmyadminPort entirely (B3 regression guard)', async () => { + findAvailablePort.mockImplementation( ( { preferredPort } ) => + Promise.resolve( preferredPort ) + ); + isPortAvailable.mockResolvedValue( true ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'defaults-only', + defaultOriginPorts: new Set( [ + 'development.port', + 'tests.port', + ] ), + } ); + + // HTTP ports were resolved. + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8888 } ) + ); + // phpmyadminPort was NOT resolved through either path. + expect( findAvailablePort ).not.toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8080 } ) + ); + expect( isPortAvailable ).not.toHaveBeenCalledWith( 8080 ); + // And its value is left untouched. + expect( config.env.development.phpmyadminPort ).toEqual( 8080 ); + } ); + + it( 'under autoPortMode=all uses non-strict mode for all ports including phpmyadminPort', async () => { + findAvailablePort.mockImplementation( ( { preferredPort } ) => + Promise.resolve( preferredPort ) + ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'all', + } ); + + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8888 } ) + ); + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8889 } ) + ); + expect( findAvailablePort ).toHaveBeenCalledWith( + expect.objectContaining( { preferredPort: 8080 } ) + ); + expect( isPortAvailable ).not.toHaveBeenCalled(); + } ); + + it( 'under autoPortMode=off uses strict mode for HTTP ports and still resolves phpmyadminPort strictly', async () => { + isPortAvailable.mockResolvedValue( true ); + + const resolver = createPortResolver(); + const config = { + env: { + development: { + port: 8888, + phpmyadminPort: 8080, + }, + tests: { port: 8889 }, + }, + }; + + await resolveConfigPorts( config, resolver, { + autoPortMode: 'off', + } ); + + expect( isPortAvailable ).toHaveBeenCalledWith( 8888 ); + expect( isPortAvailable ).toHaveBeenCalledWith( 8889 ); + expect( isPortAvailable ).toHaveBeenCalledWith( 8080 ); + expect( findAvailablePort ).not.toHaveBeenCalled(); + } ); + } ); + + describe( 'createPortResolver moved-port notice (R11 / AC7)', () => { + const stubSpinner = () => ( { + text: '', + info: jest.fn(), + start: jest.fn(), + } ); + + it( 'emits spinner.info exactly once when fallback occurs and re-arms the spinner', async () => { + findAvailablePort.mockResolvedValue( 8890 ); + const spinner = stubSpinner(); + + const resolver = createPortResolver( spinner ); + await resolver.resolve( 8888, 'env.development.port' ); + + expect( spinner.info ).toHaveBeenCalledTimes( 1 ); + expect( spinner.info.mock.calls[ 0 ][ 0 ] ).toMatch( + /8888.*busy.*8890/i + ); + // Spinner is re-armed after the info notice (matches the + // existing `spinner.warn(...); spinner.start();` precedent in + // commands/start.js). + expect( spinner.start ).toHaveBeenCalled(); + expect( spinner.info.mock.invocationCallOrder[ 0 ] ).toBeLessThan( + spinner.start.mock.invocationCallOrder[ 0 ] + ); + } ); + + it( 'does NOT emit spinner.info when the preferred port is available (no move occurred)', async () => { + // findAvailablePort returns the preferred port itself — + // signalling no fallback was needed. + findAvailablePort.mockResolvedValue( 8888 ); + const spinner = stubSpinner(); + + const resolver = createPortResolver( spinner ); + await resolver.resolve( 8888, 'env.development.port' ); + + expect( spinner.info ).not.toHaveBeenCalled(); + } ); + + it( 'does NOT emit spinner.info on the strict failure path', async () => { + isPortAvailable.mockResolvedValue( false ); + const spinner = stubSpinner(); + + const resolver = createPortResolver( spinner ); + await expect( + resolver.resolve( 9000, 'env.development.port', true ) + ).rejects.toThrow( /Port 9000.*is busy/ ); + + expect( spinner.info ).not.toHaveBeenCalled(); + } ); + + it( 'does not write to console or process.stdout when fallback occurs (regression guard)', async () => { + findAvailablePort.mockResolvedValue( 8890 ); + + const consoleLog = jest + .spyOn( console, 'log' ) + .mockImplementation( () => {} ); + const consoleInfo = jest + .spyOn( console, 'info' ) + .mockImplementation( () => {} ); + const consoleWarn = jest + .spyOn( console, 'warn' ) + .mockImplementation( () => {} ); + const stdoutWrite = jest + .spyOn( process.stdout, 'write' ) + .mockImplementation( () => true ); + + try { + const resolver = createPortResolver( stubSpinner() ); + await resolver.resolve( 8888, 'env.development.port' ); + + // AC7: introducing a separate output channel would be a + // detectable regression. None of these were called. + expect( consoleLog ).not.toHaveBeenCalled(); + expect( consoleInfo ).not.toHaveBeenCalled(); + expect( consoleWarn ).not.toHaveBeenCalled(); + expect( stdoutWrite ).not.toHaveBeenCalled(); + } finally { + consoleLog.mockRestore(); + consoleInfo.mockRestore(); + consoleWarn.mockRestore(); + stdoutWrite.mockRestore(); + } + } ); + + it( 'suppresses the notice silently when no spinner is provided (test-path safety)', async () => { + findAvailablePort.mockResolvedValue( 8890 ); + + const consoleLog = jest + .spyOn( console, 'log' ) + .mockImplementation( () => {} ); + const consoleInfo = jest + .spyOn( console, 'info' ) + .mockImplementation( () => {} ); + + try { + // No spinner argument — must not throw and must not + // silently log to console as a fallback channel. + const resolver = createPortResolver(); + await expect( + resolver.resolve( 8888, 'env.development.port' ) + ).resolves.toEqual( 8890 ); + + expect( consoleLog ).not.toHaveBeenCalled(); + expect( consoleInfo ).not.toHaveBeenCalled(); + } finally { + consoleLog.mockRestore(); + consoleInfo.mockRestore(); + } + } ); } ); } );