Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): ensure port 0 uses random port wi…
Browse files Browse the repository at this point in the history
…th Vite development server

Vite appears to consider a port value of `0` as a falsy value and use the default Vite port of
`5173` when zero is used as a value for the development server port option. To workaround this
issue, the port checker code now explicitly handles the zero value case and determines a random
port as would be done automatically by the Webpack-based development server.

(cherry picked from commit 5b8e2d5)
  • Loading branch information
clydin committed Dec 8, 2023
1 parent 1cfd710 commit d1b27e5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ describeServeBuilder(
expect(result?.success).toBeTrue();
const port = getResultPort(result);
expect(port).not.toBe('4200');
if (isViteRun) {
// Should not be default Vite port either
expect(port).not.toBe('5173');
}

expect(port).toMatch(/\d{4,6}/);
expect(await response?.text()).toContain('<title>');

Expand Down
25 changes: 18 additions & 7 deletions packages/angular_devkit/build_angular/src/utils/check-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/

import * as net from 'net';
import assert from 'node:assert';
import { AddressInfo, createServer } from 'node:net';
import { loadEsmModule } from './load-esm';
import { isTTY } from './tty';

Expand All @@ -15,12 +16,14 @@ function createInUseError(port: number): Error {
}

export async function checkPort(port: number, host: string): Promise<number> {
if (port === 0) {
return 0;
}
// Disabled due to Vite not handling port 0 and instead always using the default value (5173)
// TODO: Enable this again once Vite is fixed
// if (port === 0) {
// return 0;
// }

return new Promise<number>((resolve, reject) => {
const server = net.createServer();
const server = createServer();

server
.once('error', (err: NodeJS.ErrnoException) => {
Expand All @@ -46,13 +49,21 @@ export async function checkPort(port: number, host: string): Promise<number> {
}),
)
.then(
(answers) => (answers.useDifferent ? resolve(0) : reject(createInUseError(port))),
(answers) =>
answers.useDifferent ? resolve(checkPort(0, host)) : reject(createInUseError(port)),
() => reject(createInUseError(port)),
);
})
.once('listening', () => {
// Get the actual address from the listening server instance
const address = server.address();
assert(
address && typeof address !== 'string',
'Port check server address should always be an object.',
);

server.close();
resolve(port);
resolve(address.port);
})
.listen(port, host);
});
Expand Down

0 comments on commit d1b27e5

Please sign in to comment.