@nx/web 24.1.0 → 24.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,6 @@ const net_1 = require("net");
11
11
  const path_1 = require("path");
12
12
  const internal_2 = require("@nx/js/internal");
13
13
  const detect_port_1 = tslib_1.__importDefault(require("detect-port"));
14
- const wait_for_port_open_1 = require("../../utils/wait-for-port-open");
15
14
  function getHttpServerArgs(options) {
16
15
  const { buildTarget, parallel, host, proxyUrl, ssl, sslCert, sslKey, proxyOptions, watch, spa, cacheSeconds, ...rest } = options;
17
16
  const args = [`-c${options.cacheSeconds}`];
@@ -94,26 +93,22 @@ function getBuildTargetOutputPath(options, context) {
94
93
  }
95
94
  return outputPath;
96
95
  }
97
- /** Whether the server accepts connections before `exited` settles. */
98
- async function waitUntilListening(port, host, exited) {
99
- let alive = true;
100
- exited.then(() => (alive = false));
101
- // A wildcard address accepts connections on the loopback of its family. `::`
102
- // also accepts IPv4 ones, and a host may have no ::1, so it gets both probes.
103
- const probeHosts = host === '0.0.0.0'
104
- ? ['127.0.0.1']
105
- : host === '::'
106
- ? ['::1', '127.0.0.1']
107
- : [host];
108
- while (alive) {
109
- const connected = await Promise.any(probeHosts.map((probeHost) => (0, wait_for_port_open_1.waitForPortOpen)(port, { host: probeHost, retries: 0 }))).then(() => true, () => false);
110
- if (connected) {
111
- // A child that failed to bind the port leaves it to whoever holds it
112
- return alive;
113
- }
114
- await new Promise((r) => setTimeout(r, 100));
115
- }
116
- return false;
96
+ // http-server-child.js exits with this when its port turned out to be taken
97
+ const ADDRESS_IN_USE_EXIT_CODE = 75;
98
+ // N servers starting on the same port at once can cost one of them N - 1 retries
99
+ const MAX_PORT_RETRIES = 50;
100
+ function waitForListening(serve) {
101
+ return new Promise((resolve) => {
102
+ let exited = false;
103
+ serve.on('exit', () => (exited = true));
104
+ serve.on('message', (message) => {
105
+ if (message?.type === 'listening' && !exited) {
106
+ resolve({ listening: true });
107
+ }
108
+ });
109
+ // 'exit' can arrive before the child's last messages, 'close' after them
110
+ serve.on('close', (exitCode) => resolve({ exitCode }));
111
+ });
117
112
  }
118
113
  function createFileWatcher(project, changeHandler) {
119
114
  return internal_1.daemonClient.registerFileWatcher({
@@ -190,41 +185,38 @@ async function* fileServerExecutor(options, context) {
190
185
  // perform initial run
191
186
  run();
192
187
  }
193
- const port = await (0, detect_port_1.default)(options.port || 8080);
188
+ // detect port as close to when used to prevent port being used by another process
189
+ // when running in parallel
190
+ const findFreePort = async (from) => {
191
+ const freePort = await (0, detect_port_1.default)(from);
192
+ if (freePort !== from) {
193
+ devkit_1.logger.info(`Port ${from} is in use, trying another one...`);
194
+ }
195
+ return freePort;
196
+ };
197
+ const requestedPort = options.port || 8080;
198
+ let port = await findFreePort(requestedPort);
194
199
  const outputPath = getBuildTargetOutputPath(options, context);
195
200
  if (options.spa) {
196
201
  const src = (0, path_1.join)(outputPath, 'index.html');
197
202
  const dst = (0, path_1.join)(outputPath, '404.html');
198
203
  // See: https://github.com/http-party/http-server#magic-files
199
204
  (0, fs_1.copyFileSync)(src, dst);
200
- // We also need to ensure the proxyUrl is set, otherwise the browser will continue to throw a 404 error
201
- // This can cause unexpected behaviors and failures especially in automated test suites
202
- options.proxyUrl ??= `http${options.ssl ? 's' : ''}://localhost:${port}?`;
203
205
  }
204
- const args = getHttpServerArgs(options);
205
206
  const { path: pathToHttpServerPkgJson, packageJson } = (0, internal_1.readModulePackageJson)('http-server', module.paths);
206
207
  const pathToHttpServerBin = packageJson.bin['http-server'];
207
208
  const pathToHttpServer = (0, path_1.resolve)(pathToHttpServerPkgJson.replace('package.json', ''), pathToHttpServerBin);
208
- // detect port as close to when used to prevent port being used by another process
209
- // when running in parallel
210
- args.push(`-p=${port}`);
211
- const serve = (0, child_process_1.fork)(pathToHttpServer, [outputPath, ...args], {
212
- stdio: 'pipe',
213
- cwd: context.root,
214
- env: {
215
- FORCE_COLOR: 'true',
216
- ...process.env,
217
- },
218
- });
219
- const exited = new Promise((res) => {
220
- serve.on('exit', (code, signal) => {
221
- if (code === null)
222
- code = (0, internal_1.signalToCode)(signal);
223
- res({ success: code == 0 });
224
- });
225
- });
209
+ // http-server's own default when no `-a` is passed
210
+ const host = options.host || '0.0.0.0';
211
+ const getUrl = (port) => (0, internal_1.getListeningUrl)({ address: host, family: (0, net_1.isIPv6)(host) ? 'IPv6' : 'IPv4', port }, !!options.ssl);
212
+ let serve;
213
+ let stopping = false;
226
214
  const processExitListener = () => {
227
- serve.kill();
215
+ if (stopping) {
216
+ return;
217
+ }
218
+ stopping = true;
219
+ serve?.kill();
228
220
  if (disposeWatch) {
229
221
  disposeWatch();
230
222
  }
@@ -234,20 +226,65 @@ async function* fileServerExecutor(options, context) {
234
226
  };
235
227
  process.on('exit', processExitListener);
236
228
  process.on('SIGTERM', processExitListener);
237
- serve.stdout.on('data', (chunk) => {
238
- if (chunk.toString().indexOf('GET') === -1) {
239
- process.stdout.write(chunk);
229
+ const loopbacks = /^https?:\/\/localhost:/i.test(getUrl(port))
230
+ ? 'both'
231
+ : 'one';
232
+ for (let retries = 0;; retries++) {
233
+ if (stopping) {
234
+ return { success: false };
240
235
  }
241
- });
242
- serve.stderr.on('data', (chunk) => {
243
- process.stderr.write(chunk);
244
- });
245
- // http-server's own default when no `-a` is passed
246
- const host = options.host || '0.0.0.0';
247
- if (!(await waitUntilListening(port, host, exited))) {
248
- return exited;
236
+ const args = getHttpServerArgs({
237
+ ...options,
238
+ // We also need to ensure the proxyUrl is set, otherwise the browser will continue to throw a 404 error
239
+ // This can cause unexpected behaviors and failures especially in automated test suites
240
+ proxyUrl: options.proxyUrl ??
241
+ (options.spa
242
+ ? `http${options.ssl ? 's' : ''}://localhost:${port}?`
243
+ : undefined),
244
+ });
245
+ args.push(`-p=${port}`);
246
+ const child = (0, child_process_1.fork)((0, path_1.join)(__dirname, 'http-server-child.js'), [pathToHttpServer, loopbacks, outputPath, ...args], {
247
+ stdio: 'pipe',
248
+ cwd: context.root,
249
+ env: {
250
+ FORCE_COLOR: 'true',
251
+ ...process.env,
252
+ },
253
+ });
254
+ serve = child;
255
+ child.on('error', (e) => devkit_1.logger.error(e.message));
256
+ // A process that fails to spawn emits 'close' but never 'exit'
257
+ const exited = new Promise((res) => {
258
+ child.on('close', (code, signal) => {
259
+ if (code === null)
260
+ code = (0, internal_1.signalToCode)(signal);
261
+ res({ success: code == 0 });
262
+ });
263
+ });
264
+ // A fork that fails on EMFILE has no stdio
265
+ child.stdout?.on('data', (chunk) => {
266
+ if (chunk.toString().indexOf('GET') === -1) {
267
+ process.stdout.write(chunk);
268
+ }
269
+ });
270
+ child.stderr?.on('data', (chunk) => {
271
+ process.stderr.write(chunk);
272
+ });
273
+ const started = await waitForListening(child);
274
+ if (stopping) {
275
+ return exited;
276
+ }
277
+ if ('listening' in started) {
278
+ yield { success: true, baseUrl: getUrl(port) };
279
+ return exited;
280
+ }
281
+ if (started.exitCode !== ADDRESS_IN_USE_EXIT_CODE) {
282
+ return exited;
283
+ }
284
+ if (retries === MAX_PORT_RETRIES) {
285
+ throw new Error(`No available port found after ${MAX_PORT_RETRIES} retries, starting from port ${requestedPort}.`);
286
+ }
287
+ devkit_1.logger.info(`Port ${port} is in use, trying another one...`);
288
+ port = await findFreePort(port + 1);
249
289
  }
250
- const baseUrl = (0, internal_1.getListeningUrl)({ address: host, family: (0, net_1.isIPv6)(host) ? 'IPv6' : 'IPv4', port }, !!options.ssl);
251
- yield { success: true, baseUrl };
252
- return exited;
253
290
  }
@@ -0,0 +1,67 @@
1
+ // Runs http-server's bin unchanged and tells the file-server executor once its
2
+ // server listens. A probe from outside can't tell whose server answers.
3
+ const { errorMonitor } = require('events');
4
+ const { createServer } = require('net');
5
+ const { dirname, join } = require('path');
6
+
7
+ // EX_TEMPFAIL: the port was taken, so the executor retries on another one
8
+ const ADDRESS_IN_USE_EXIT_CODE = 75;
9
+ const OTHER_LOOPBACK = {
10
+ '::1': '127.0.0.1',
11
+ '127.0.0.1': '::1',
12
+ '0.0.0.0': '::1',
13
+ };
14
+
15
+ const [bin, loopbacks] = process.argv.splice(2, 2);
16
+ process.argv[1] = bin;
17
+ const { HttpServer } = require(
18
+ join(dirname(bin), '..', 'lib', 'http-server.js')
19
+ );
20
+
21
+ // Windows reports EACCES when another process holds the port exclusively.
22
+ // Elsewhere EACCES is a permission error, so it keeps its own failure.
23
+ const TAKEN_CODES =
24
+ process.platform === 'win32' ? ['EADDRINUSE', 'EACCES'] : ['EADDRINUSE'];
25
+ function exitIfTaken(e) {
26
+ if (TAKEN_CODES.includes(e.code)) {
27
+ process.exit(ADDRESS_IN_USE_EXIT_CODE);
28
+ }
29
+ }
30
+
31
+ const listen = HttpServer.prototype.listen;
32
+ HttpServer.prototype.listen = function (...args) {
33
+ const server = this.server;
34
+ // The bin's callback prints the url and opens a browser, so it waits for both loopbacks
35
+ const onListening = typeof args.at(-1) === 'function' ? args.pop() : null;
36
+ const ready = () => {
37
+ onListening?.call(server);
38
+ process.send({ type: 'listening' });
39
+ };
40
+ // A monitor keeps Node's own crash for every other listen error
41
+ server.on(errorMonitor, exitIfTaken);
42
+ server.once('listening', () => {
43
+ server.off(errorMonitor, exitIfTaken);
44
+ const { address, port } = server.address();
45
+ const otherLoopback = loopbacks === 'both' && OTHER_LOOPBACK[address];
46
+ if (!otherLoopback) {
47
+ return ready();
48
+ }
49
+ // A localhost url can resolve to either loopback, so serve the port on both
50
+ const other = createServer((socket) => server.emit('connection', socket));
51
+ const onBindError = (e) => {
52
+ exitIfTaken(e);
53
+ // Best effort: without the other loopback the server still runs on this one
54
+ ready();
55
+ };
56
+ other
57
+ .once('error', onBindError)
58
+ .once('listening', () => {
59
+ other.off('error', onBindError);
60
+ ready();
61
+ })
62
+ .listen(port, otherLoopback);
63
+ });
64
+ return listen.apply(this, args);
65
+ };
66
+
67
+ require(bin);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/web",
3
- "version": "24.1.0",
3
+ "version": "24.2.0-beta.0",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "files": [
@@ -79,20 +79,20 @@
79
79
  "http-server": "^14.1.0",
80
80
  "picocolors": "^1.1.0",
81
81
  "tslib": "^2.3.0",
82
- "@nx/devkit": "24.1.0",
83
- "@nx/js": "24.1.0"
82
+ "@nx/devkit": "24.2.0-beta.0",
83
+ "@nx/js": "24.2.0-beta.0"
84
84
  },
85
85
  "devDependencies": {
86
- "nx": "24.1.0",
87
- "@nx/vitest": "24.1.0"
86
+ "nx": "24.2.0-beta.0",
87
+ "@nx/vitest": "24.2.0-beta.0"
88
88
  },
89
89
  "peerDependencies": {
90
- "@nx/cypress": "24.1.0",
91
- "@nx/eslint": "24.1.0",
92
- "@nx/jest": "24.1.0",
93
- "@nx/playwright": "24.1.0",
94
- "@nx/vite": "24.1.0",
95
- "@nx/webpack": "24.1.0"
90
+ "@nx/cypress": "24.2.0-beta.0",
91
+ "@nx/eslint": "24.2.0-beta.0",
92
+ "@nx/jest": "24.2.0-beta.0",
93
+ "@nx/playwright": "24.2.0-beta.0",
94
+ "@nx/vite": "24.2.0-beta.0",
95
+ "@nx/webpack": "24.2.0-beta.0"
96
96
  },
97
97
  "peerDependenciesMeta": {
98
98
  "@nx/cypress": {