@nx/rspack 24.0.0-beta.3 → 24.0.0-beta.4

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.
@@ -0,0 +1 @@
1
+ export declare function waitForDevServer(configPath: string): Promise<void>;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.waitForDevServer = waitForDevServer;
4
+ const dev_server_ready_check_1 = require("./src/utils/dev-server-ready-check");
5
+ async function waitForDevServer(configPath) {
6
+ await (0, dev_server_ready_check_1.waitForRspackDevServer)(configPath);
7
+ // A config can leave handles open that would keep the check running
8
+ process.exit(0);
9
+ }
@@ -0,0 +1 @@
1
+ export { NxReadySignalPlugin } from './src/utils/dev-server-ready-signal';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NxReadySignalPlugin = void 0;
4
+ var dev_server_ready_signal_1 = require("./src/utils/dev-server-ready-signal");
5
+ Object.defineProperty(exports, "NxReadySignalPlugin", { enumerable: true, get: function () { return dev_server_ready_signal_1.NxReadySignalPlugin; } });
@@ -48,7 +48,7 @@ async function configurationGenerator(tree, options) {
48
48
  const task = await (0, init_1.default)(tree, {
49
49
  ...options,
50
50
  });
51
- const { targets, root, projectType } = (0, devkit_1.readProjectConfiguration)(tree, options.project);
51
+ const { targets, root } = (0, devkit_1.readProjectConfiguration)(tree, options.project);
52
52
  const { target, framework } = (0, generator_utils_1.determineFrameworkAndTarget)(tree, options, root, targets);
53
53
  options.framework = framework;
54
54
  options.target = target;
@@ -61,15 +61,13 @@ async function configurationGenerator(tree, options) {
61
61
  serve: options.serveTarget,
62
62
  };
63
63
  const { validFoundTargetName, projectContainsUnsupportedExecutor, userProvidedTargetIsUnsupported, alreadyHasNxRspackTargets, } = (0, generator_utils_1.findExistingTargetsInProject)(targets, userProvidedTargetName);
64
- if (alreadyHasNxRspackTargets.build &&
65
- (alreadyHasNxRspackTargets.serve ||
66
- (0, internal_1.getProjectType)(tree, options.project, projectType) === 'library' ||
67
- options.framework === 'nest')) {
64
+ if (alreadyHasNxRspackTargets.build || alreadyHasNxRspackTargets.serve) {
68
65
  throw new Error(`The project ${options.project} has targets using the removed @nx/rspack executors.
69
66
  Please try a different project, or remove the existing targets
70
67
  and re-run this generator to reset the existing Rspack Configuration.
71
68
  `);
72
69
  }
70
+ (0, generator_utils_1.assertNoRemovedExecutorTargets)(options.project, targets);
73
71
  if (!validFoundTargetName.build && projectContainsUnsupportedExecutor) {
74
72
  throw new Error(`The project ${options.project} cannot be converted to use Rspack.`);
75
73
  }
@@ -58,11 +58,11 @@
58
58
  },
59
59
  "buildTarget": {
60
60
  "type": "string",
61
- "description": "The build target of the project to be transformed to use the @nx/vite:build executor."
61
+ "description": "The existing build target of the project to convert to Rspack."
62
62
  },
63
63
  "serveTarget": {
64
64
  "type": "string",
65
- "description": "The serve target of the project to be transformed to use the @nx/vite:dev-server and @nx/vite:preview-server executors."
65
+ "description": "The existing serve target of the project, used to check that it can be converted to Rspack."
66
66
  },
67
67
  "rootProject": {
68
68
  "type": "boolean",
@@ -1,5 +1,6 @@
1
1
  import type { Compiler } from '@rspack/core';
2
2
  import type { NxAppRspackPluginOptions } from '../utils/models';
3
+ import { READY_SIGNAL_PLUGIN } from '../../utils/dev-server-ready-signal';
3
4
  /**
4
5
  * This plugin provides features to build Node and Web applications.
5
6
  * - TS Support (including tsconfig paths
@@ -11,6 +12,7 @@ import type { NxAppRspackPluginOptions } from '../utils/models';
11
12
  */
12
13
  export declare class NxAppRspackPlugin {
13
14
  private readonly options;
15
+ readonly [READY_SIGNAL_PLUGIN] = true;
14
16
  constructor(options?: NxAppRspackPluginOptions);
15
17
  apply(compiler: Compiler): void;
16
18
  }
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var _a;
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.NxAppRspackPlugin = void 0;
4
5
  const normalize_options_1 = require("../utils/plugins/normalize-options");
6
+ const dev_server_ready_signal_1 = require("../../utils/dev-server-ready-signal");
5
7
  const apply_base_config_1 = require("../utils/apply-base-config");
6
8
  const apply_web_config_1 = require("../utils/apply-web-config");
7
9
  /**
@@ -15,12 +17,15 @@ const apply_web_config_1 = require("../utils/apply-web-config");
15
17
  */
16
18
  class NxAppRspackPlugin {
17
19
  constructor(options = {}) {
20
+ this[_a] = true;
18
21
  // If we're building inferred targets, skip normalizing the build options
19
22
  if (!global.NX_GRAPH_CREATION) {
20
23
  this.options = (0, normalize_options_1.normalizeOptions)(options);
21
24
  }
22
25
  }
23
26
  apply(compiler) {
27
+ const { applyDevServerReadySignal } = require('../../utils/dev-server-ready-signal');
28
+ applyDevServerReadySignal(compiler);
24
29
  // Default's to web
25
30
  const target = this.options.target ?? compiler.options.target;
26
31
  this.options.outputPath ??= compiler.options.output?.path;
@@ -52,3 +57,4 @@ class NxAppRspackPlugin {
52
57
  }
53
58
  }
54
59
  exports.NxAppRspackPlugin = NxAppRspackPlugin;
60
+ _a = dev_server_ready_signal_1.READY_SIGNAL_PLUGIN;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createNodesV2 = exports.createNodes = void 0;
4
4
  const internal_1 = require("@nx/devkit/internal");
5
+ const dev_server_ready_signal_1 = require("../utils/dev-server-ready-signal");
5
6
  const devkit_1 = require("@nx/devkit");
6
7
  const js_1 = require("@nx/js");
7
8
  const internal_2 = require("@nx/js/internal");
@@ -124,6 +125,7 @@ async function createRspackTargets(configFilePath, projectRoot, options, context
124
125
  ],
125
126
  outputs,
126
127
  };
128
+ const devServerReadyWhen = getDevServerReadyWhen(configFilePath, rspackOptions);
127
129
  targets[options.serveTargetName] = {
128
130
  continuous: true,
129
131
  inputs: [...buildInputs],
@@ -133,6 +135,7 @@ async function createRspackTargets(configFilePath, projectRoot, options, context
133
135
  args: ['--node-env=development'],
134
136
  env,
135
137
  },
138
+ readyWhen: devServerReadyWhen,
136
139
  };
137
140
  targets[options.previewTargetName] = {
138
141
  continuous: true,
@@ -143,6 +146,7 @@ async function createRspackTargets(configFilePath, projectRoot, options, context
143
146
  args: ['--node-env=production'],
144
147
  env,
145
148
  },
149
+ readyWhen: devServerReadyWhen,
146
150
  };
147
151
  targets[options.serveStaticTargetName] = {
148
152
  dependsOn: [`${options.buildTargetName}`],
@@ -153,6 +157,7 @@ async function createRspackTargets(configFilePath, projectRoot, options, context
153
157
  buildTarget: options.buildTargetName,
154
158
  spa: true,
155
159
  },
160
+ readyWhen: { port: '{options.port}', host: '{options.host ?? localhost}' },
156
161
  };
157
162
  // for `convert-to-inferred` we need to leave the port undefined or the options will not match
158
163
  if (rspackConfig.devServer?.port && rspackConfig.devServer?.port !== 4200) {
@@ -212,3 +217,19 @@ function normalizeOutputPath(outputPath, projectRoot) {
212
217
  }
213
218
  }
214
219
  }
220
+ // A dev server whose config loads NxAppRspackPlugin or NxReadySignalPlugin reports
221
+ // when it listens. Otherwise the check reads the config when the task runs,
222
+ // with the task's env and options, and waits for the dev server's port.
223
+ function getDevServerReadyWhen(configFilePath, configs) {
224
+ // `rspack serve` starts one dev server, for the first config with devServer
225
+ const signals = (0, dev_server_ready_signal_1.sendsReadySignal)(configs.find((config) => config.devServer) ?? configs[0] ?? {});
226
+ return signals
227
+ ? { signal: true }
228
+ : {
229
+ // Unquoted: the plugin's glob fixes the file name. Quote it if it ever
230
+ // becomes user-chosen, since the shell expands $, backticks and %.
231
+ command: `node -e "require('@nx/rspack/ready-check').waitForDevServer(process.argv[1])" ${(0, path_1.basename)(configFilePath)}`,
232
+ // Each attempt loads the config
233
+ interval: 1000,
234
+ };
235
+ }
@@ -0,0 +1,48 @@
1
+ export interface ServeFlags {
2
+ port?: string;
3
+ host?: string;
4
+ nodeEnv?: string;
5
+ config?: string;
6
+ configNames: string[];
7
+ env: string[];
8
+ }
9
+ /**
10
+ * The flags `rspack serve` takes from the target's options. run-commands
11
+ * forwards named options, then `args`, then overrides, and a later source wins.
12
+ */
13
+ export declare function parseServeFlags(options: Record<string, unknown>): ServeFlags;
14
+ /**
15
+ * The `argv` @rspack/cli passes to a function config: its parsed options,
16
+ * with `env` set by the caller. Values follow its mri parser: a numeric value
17
+ * is a number, a bare flag is true, `--no-x` is false, a repeated flag is an
18
+ * array.
19
+ */
20
+ export declare function parseServeArgv(options: Record<string, unknown>, env: Record<string, unknown>): Record<string, unknown>;
21
+ export type DevServerAddress = {
22
+ port: number;
23
+ host?: string;
24
+ };
25
+ /**
26
+ * Where a dev server listens, or null when it picks its port or listens on a
27
+ * socket. Returns null for those, since nothing can be probed ahead of them.
28
+ */
29
+ export declare function getDevServerAddress(devServer: {
30
+ port?: unknown;
31
+ host?: unknown;
32
+ ipc?: unknown;
33
+ } | undefined, flags: ServeFlags, basePort: string | undefined): DevServerAddress | null;
34
+ /** Resolves once every address accepts a TCP connection. */
35
+ export declare function waitForAddresses(addresses: DevServerAddress[]): Promise<void>;
36
+ export declare function readTaskOptions(): Record<string, unknown> & {
37
+ cwd?: string;
38
+ };
39
+ export declare function enterTaskCwd(options: {
40
+ cwd?: string;
41
+ }): void;
42
+ /**
43
+ * The readyWhen of the inferred serve targets when the config doesn't load the
44
+ * signal plugin. Runs in the env and with the options of the serve task, reads
45
+ * the config the way `rspack serve` does, and waits for the dev server it
46
+ * starts.
47
+ */
48
+ export declare function waitForRspackDevServer(configPath: string): Promise<void>;
@@ -0,0 +1,339 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseServeFlags = parseServeFlags;
4
+ exports.parseServeArgv = parseServeArgv;
5
+ exports.getDevServerAddress = getDevServerAddress;
6
+ exports.waitForAddresses = waitForAddresses;
7
+ exports.readTaskOptions = readTaskOptions;
8
+ exports.enterTaskCwd = enterTaskCwd;
9
+ exports.waitForRspackDevServer = waitForRspackDevServer;
10
+ const internal_1 = require("@nx/devkit/internal");
11
+ const fs_1 = require("fs");
12
+ const net_1 = require("net");
13
+ const path_1 = require("path");
14
+ const semver_1 = require("semver");
15
+ const url_1 = require("url");
16
+ /**
17
+ * The flags `rspack serve` takes from the target's options. run-commands
18
+ * forwards named options, then `args`, then overrides, and a later source wins.
19
+ */
20
+ function parseServeFlags(options) {
21
+ const args = parseArgs(splitArgs(options.args));
22
+ // run-commands doesn't forward `--env` overrides, since `env` is its own option
23
+ const overrides = parseArgs(overrideArgs(options.__unparsed__));
24
+ const option = (...keys) => keys
25
+ .map((key) => options[key])
26
+ .find((value) => typeof value === 'string' || typeof value === 'number')
27
+ ?.toString();
28
+ // Repeated `--config-name` flags add up, and replace a named configName
29
+ const configNames = [...args.configNames, ...overrides.configNames];
30
+ const configName = option('configName', 'config-name');
31
+ return {
32
+ port: overrides.port ?? args.port ?? option('port'),
33
+ host: overrides.host ?? args.host ?? option('host'),
34
+ nodeEnv: overrides.nodeEnv ?? args.nodeEnv ?? option('nodeEnv', 'node-env'),
35
+ config: overrides.config ?? args.config ?? option('config', 'c'),
36
+ configNames: configNames.length > 0 ? configNames : configName ? [configName] : [],
37
+ env: args.env,
38
+ };
39
+ }
40
+ // run-commands leaves `args` for the shell to split, and quotes each override
41
+ // so it stays one argument
42
+ function splitArgs(value) {
43
+ return (0, internal_1.splitShellArgs)(Array.isArray(value)
44
+ ? value.join(' ')
45
+ : typeof value === 'string'
46
+ ? value
47
+ : '');
48
+ }
49
+ function overrideArgs(value) {
50
+ return Array.isArray(value) ? value.map(String) : [];
51
+ }
52
+ function parseArgs(args) {
53
+ const flags = { configNames: [], env: [] };
54
+ for (let i = 0; i < args.length; i++) {
55
+ const [, name, inline] = args[i].match(/^--([^=]+)(?:=(.*))?$/) ??
56
+ args[i].match(/^-(c)(?:=(.*))?$/) ??
57
+ [];
58
+ if (!name)
59
+ continue;
60
+ let value = inline;
61
+ if (value === undefined && args[i + 1] && !args[i + 1].startsWith('-')) {
62
+ value = args[++i];
63
+ }
64
+ if (name === 'port')
65
+ flags.port = value;
66
+ else if (name === 'host')
67
+ flags.host = value;
68
+ else if (name === 'node-env')
69
+ flags.nodeEnv = value;
70
+ else if (name === 'config' || name === 'c')
71
+ flags.config = value;
72
+ else if (name === 'config-name' && value)
73
+ flags.configNames.push(value);
74
+ else if (name === 'env' && value)
75
+ flags.env.push(value);
76
+ }
77
+ return flags;
78
+ }
79
+ const SHORT_FLAGS = {
80
+ c: 'config',
81
+ d: 'devtool',
82
+ m: 'mode',
83
+ o: 'output-path',
84
+ w: 'watch',
85
+ };
86
+ const ARRAY_FLAGS = new Set(['config-name', 'entry']);
87
+ // Named options run-commands forwards that the check reads
88
+ const NAMED_FLAGS = [
89
+ ['port', 'port'],
90
+ ['host', 'host'],
91
+ ['mode', 'mode'],
92
+ ['node-env', 'nodeEnv', 'node-env'],
93
+ ['config', 'config', 'c'],
94
+ ['config-name', 'configName', 'config-name'],
95
+ ];
96
+ /**
97
+ * The `argv` @rspack/cli passes to a function config: its parsed options,
98
+ * with `env` set by the caller. Values follow its mri parser: a numeric value
99
+ * is a number, a bare flag is true, `--no-x` is false, a repeated flag is an
100
+ * array.
101
+ */
102
+ function parseServeArgv(options, env) {
103
+ const tokens = [
104
+ ...splitArgs(options.args),
105
+ ...overrideArgs(options.__unparsed__),
106
+ ];
107
+ const given = new Set(tokens.map((token) => token.match(/^--([^=]+)/)?.[1]));
108
+ const named = NAMED_FLAGS.flatMap(([flag, ...keys]) => {
109
+ const value = keys
110
+ .map((key) => options[key])
111
+ .find((v) => typeof v === 'string' || typeof v === 'number');
112
+ return value === undefined || given.has(flag) ? [] : [`--${flag}=${value}`];
113
+ });
114
+ const argv = {};
115
+ const all = [...named, ...tokens];
116
+ for (let i = 0; i < all.length; i++) {
117
+ const [, dashes, rawName, inline] = all[i].match(/^(--?)([^=]+)(?:=(.*))?$/) ?? [];
118
+ if (!rawName)
119
+ continue;
120
+ const flag = dashes === '-' ? SHORT_FLAGS[rawName] : rawName;
121
+ if (!flag)
122
+ continue;
123
+ const negated = flag.startsWith('no-');
124
+ const base = negated ? flag.slice(3) : flag;
125
+ const name = base.replace(/([a-z])-([a-z])/g, (_, a, b) => a + b.toUpperCase());
126
+ if (negated) {
127
+ argv[name] = false;
128
+ continue;
129
+ }
130
+ const next = inline ?? (all[i + 1] && !all[i + 1].startsWith('-') ? all[++i] : '');
131
+ if (flag === 'env')
132
+ continue;
133
+ const value = next === '' ? true : Number.isFinite(Number(next)) ? Number(next) : next;
134
+ const previous = argv[name];
135
+ argv[name] =
136
+ previous === undefined
137
+ ? ARRAY_FLAGS.has(flag)
138
+ ? [value]
139
+ : value
140
+ : [previous, value].flat();
141
+ }
142
+ return { ...argv, env };
143
+ }
144
+ const UNSAFE_ENV_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
145
+ /** The env object `rspack serve` builds from its `--env` values. */
146
+ function parseEnv(values) {
147
+ const env = {};
148
+ for (const value of values) {
149
+ const [allKeys, val] = value.split(/=(.+)/, 2);
150
+ const keys = allKeys.split(/\.(?!$)/);
151
+ if (keys.some((key) => UNSAFE_ENV_KEYS.has(key.replace(/=$/, '')))) {
152
+ continue;
153
+ }
154
+ let ref = env;
155
+ for (const [index, key] of keys.entries()) {
156
+ if (key.endsWith('=')) {
157
+ ref[key.slice(0, -1)] = undefined;
158
+ continue;
159
+ }
160
+ if (!ref[key] || typeof ref[key] === 'string')
161
+ ref[key] = {};
162
+ if (index === keys.length - 1) {
163
+ ref[key] = typeof val === 'string' ? val : true;
164
+ }
165
+ ref = ref[key];
166
+ }
167
+ }
168
+ return env;
169
+ }
170
+ // `rspack serve` loads the @rspack/dev-server its own @rspack/cli resolves
171
+ function getDevServerMajorVersion() {
172
+ let cliPackageJsonPath;
173
+ try {
174
+ cliPackageJsonPath = (0, internal_1.readModulePackageJson)('@rspack/cli', [
175
+ process.cwd(),
176
+ ]).path;
177
+ }
178
+ catch {
179
+ return null;
180
+ }
181
+ const version = (0, internal_1.getInstalledPackageVersion)('@rspack/dev-server', [
182
+ (0, path_1.dirname)(cliPackageJsonPath),
183
+ ]);
184
+ return version ? (0, semver_1.major)(version) : null;
185
+ }
186
+ const CONFIG_EXTENSIONS = ['.ts', '.js', '.mts', '.mjs', '.cts', '.cjs'];
187
+ function resolveExtendedConfig(request, baseDir) {
188
+ if (request.startsWith('file://'))
189
+ return (0, url_1.fileURLToPath)(request);
190
+ if (request.startsWith('.') ||
191
+ request.startsWith('/') ||
192
+ request.includes(':\\')) {
193
+ const path = (0, path_1.resolve)(baseDir, request);
194
+ const found = (0, path_1.extname)(path)
195
+ ? path
196
+ : CONFIG_EXTENSIONS.map((ext) => path + ext).find(fs_1.existsSync);
197
+ if (!found) {
198
+ throw new Error(`Extended configuration file "${path}" not found.`);
199
+ }
200
+ return found;
201
+ }
202
+ return require.resolve(request, { paths: [baseDir, process.cwd()] });
203
+ }
204
+ /** Applies `extends` the way `rspack serve` does. */
205
+ async function applyExtends(config, configPath, load, extending = []) {
206
+ if (extending.includes(configPath)) {
207
+ throw new Error(`Recursive configuration detected. Config file "${configPath}" extends itself.`);
208
+ }
209
+ let merged = config;
210
+ for (const request of config.extends ? [config.extends].flat() : []) {
211
+ const path = resolveExtendedConfig(request, (0, path_1.dirname)(configPath));
212
+ const base = await load(path);
213
+ merged = mergeExtendedConfig(isPlainObject(base)
214
+ ? await applyExtends(base, path, load, [...extending, configPath])
215
+ : {}, merged);
216
+ }
217
+ return merged;
218
+ }
219
+ // Merges the fields read here as both @rspack/cli majors do: the extending
220
+ // config wins unless undefined, and devServer objects merge by key
221
+ function mergeExtendedConfig(base, config) {
222
+ const merged = mergeDefined(base, config);
223
+ if (isPlainObject(base.devServer) && isPlainObject(config.devServer)) {
224
+ merged.devServer = mergeDefined(base.devServer, config.devServer);
225
+ }
226
+ return merged;
227
+ }
228
+ function mergeDefined(base, value) {
229
+ const merged = { ...base };
230
+ for (const [key, entry] of Object.entries(value)) {
231
+ if (entry !== undefined)
232
+ merged[key] = entry;
233
+ }
234
+ return merged;
235
+ }
236
+ function isPlainObject(value) {
237
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
238
+ }
239
+ /**
240
+ * Where a dev server listens, or null when it picks its port or listens on a
241
+ * socket. Returns null for those, since nothing can be probed ahead of them.
242
+ */
243
+ function getDevServerAddress(devServer, flags, basePort) {
244
+ if (devServer?.ipc)
245
+ return null;
246
+ const port = flags.port ?? devServer?.port ?? basePort ?? 8080;
247
+ if (port === 'auto' || String(port) === '0')
248
+ return null;
249
+ const number = Number(port);
250
+ if (!Number.isInteger(number) || number <= 0)
251
+ return null;
252
+ const configured = flags.host ?? devServer?.host;
253
+ const host = typeof configured === 'string' ? (0, internal_1.resolveStartupHost)(configured) : undefined;
254
+ return host && !LOOPBACK_HOSTS.has(host)
255
+ ? { port: number, host }
256
+ : { port: number };
257
+ }
258
+ // The probe reaches these on loopback. `local-ip` and friends resolve to an
259
+ // interface address first, the way the dev server resolves them.
260
+ const LOOPBACK_HOSTS = new Set(['localhost', '0.0.0.0', '::']);
261
+ /** Resolves once every address accepts a TCP connection. */
262
+ async function waitForAddresses(addresses) {
263
+ await Promise.all(addresses.map(waitForAddress));
264
+ }
265
+ async function waitForAddress({ port, host }) {
266
+ const hosts = host ? [host] : ['127.0.0.1', '::1'];
267
+ while (!(await Promise.any(hosts.map((h) => connects(port, h))).catch(() => false))) {
268
+ await new Promise((r) => setTimeout(r, 250));
269
+ }
270
+ }
271
+ function connects(port, host) {
272
+ return new Promise((resolve, reject) => {
273
+ const socket = (0, net_1.createConnection)({ port, host });
274
+ socket.once('connect', () => {
275
+ socket.destroy();
276
+ resolve(true);
277
+ });
278
+ socket.once('error', (e) => {
279
+ socket.destroy();
280
+ reject(e);
281
+ });
282
+ });
283
+ }
284
+ function readTaskOptions() {
285
+ try {
286
+ return JSON.parse(process.env.NX_TASK_OPTIONS ?? '{}');
287
+ }
288
+ catch {
289
+ return {};
290
+ }
291
+ }
292
+ // The serve command runs from the target's cwd, so its config does too
293
+ function enterTaskCwd(options) {
294
+ if (options.cwd)
295
+ process.chdir((0, path_1.resolve)(options.cwd));
296
+ }
297
+ /**
298
+ * The readyWhen of the inferred serve targets when the config doesn't load the
299
+ * signal plugin. Runs in the env and with the options of the serve task, reads
300
+ * the config the way `rspack serve` does, and waits for the dev server it
301
+ * starts.
302
+ */
303
+ async function waitForRspackDevServer(configPath) {
304
+ const options = readTaskOptions();
305
+ const flags = parseServeFlags(options);
306
+ // The config's file name, in the cwd of the serve task
307
+ const absoluteConfigPath = (0, path_1.resolve)(options.cwd ?? '.', flags.config ?? configPath);
308
+ enterTaskCwd(options);
309
+ // `rspack serve` sets it before it loads the config
310
+ process.env.NODE_ENV ??= flags.nodeEnv ?? 'development';
311
+ // Dev server 1.x reads the webpack-dev-server names
312
+ const devServerEnv = getDevServerMajorVersion() === 1 ? 'WEBPACK' : 'RSPACK';
313
+ // The dev server sets it on import, which `rspack serve` does before it
314
+ // loads the config
315
+ process.env[`${devServerEnv}_SERVE`] ||= 'true';
316
+ // Skips NxAppRspackPlugin's option normalization, which nothing here uses
317
+ global.NX_GRAPH_CREATION = true;
318
+ const { getRootTsConfigPath } = require('@nx/js');
319
+ const { resolveUserDefinedRspackConfig } = require('./resolve-user-defined-rspack-config');
320
+ const { readRspackOptions } = require('./read-rspack-options');
321
+ const env = parseEnv(flags.env);
322
+ if (!('RSPACK_SERVE' in env))
323
+ env.RSPACK_SERVE = true;
324
+ const argv = parseServeArgv(options, env);
325
+ const tsConfig = getRootTsConfigPath();
326
+ const load = async (path) => {
327
+ const config = await resolveUserDefinedRspackConfig(path, tsConfig);
328
+ return typeof config === 'function' ? await config(env, argv) : config;
329
+ };
330
+ const configs = (await Promise.all((await readRspackOptions(await resolveUserDefinedRspackConfig(absoluteConfigPath, tsConfig), env, argv)).map((config) => applyExtends(config, absoluteConfigPath, load)))).filter((config) => flags.configNames.length === 0 || flags.configNames.includes(config.name));
331
+ // `rspack serve` starts one dev server, for the first config with devServer,
332
+ // and serves a `devServer: false` config with the defaults
333
+ const config = configs.find((c) => c.devServer) ?? configs[0];
334
+ if (!config)
335
+ return;
336
+ const address = getDevServerAddress((config.devServer || undefined), flags, process.env[`${devServerEnv}_DEV_SERVER_BASE_PORT`]);
337
+ if (address)
338
+ await waitForAddresses([address]);
339
+ }
@@ -0,0 +1,29 @@
1
+ import type { AddressInfo } from 'net';
2
+ import type { Compiler } from '@rspack/core';
3
+ export declare const READY_SIGNAL_PLUGIN: unique symbol;
4
+ /** Whether the dev server of this config will report its readiness. */
5
+ export declare function sendsReadySignal(config: {
6
+ devServer?: unknown;
7
+ plugins?: unknown[];
8
+ }): boolean;
9
+ /**
10
+ * Reports the dev server's address to an Nx task whose readyWhen is `signal`.
11
+ * `rspack serve` reads `devServer` from the compiler after plugins apply,
12
+ * so wrapping `onListening` here reaches the server it starts.
13
+ */
14
+ export declare function applyDevServerReadySignal(compiler: Compiler): void;
15
+ /** Reports the dev server's address to an Nx task whose readyWhen is `signal`. */
16
+ export declare class NxReadySignalPlugin {
17
+ readonly [READY_SIGNAL_PLUGIN] = true;
18
+ apply(compiler: Compiler): void;
19
+ }
20
+ export declare function getDevServerUrl(server: {
21
+ server?: {
22
+ address(): AddressInfo | string | null;
23
+ };
24
+ options?: {
25
+ server?: string | {
26
+ type?: string;
27
+ };
28
+ };
29
+ }): string | undefined;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.NxReadySignalPlugin = exports.READY_SIGNAL_PLUGIN = void 0;
5
+ exports.sendsReadySignal = sendsReadySignal;
6
+ exports.applyDevServerReadySignal = applyDevServerReadySignal;
7
+ exports.getDevServerUrl = getDevServerUrl;
8
+ // Set on the plugins that report readiness, so inference can find them in a
9
+ // config it has loaded
10
+ exports.READY_SIGNAL_PLUGIN = Symbol.for('@nx/ready-signal-plugin');
11
+ /** Whether the dev server of this config will report its readiness. */
12
+ function sendsReadySignal(config) {
13
+ return (typeof config.devServer === 'object' &&
14
+ !!config.devServer &&
15
+ !!config.plugins?.some((plugin) => plugin?.[exports.READY_SIGNAL_PLUGIN]));
16
+ }
17
+ /**
18
+ * Reports the dev server's address to an Nx task whose readyWhen is `signal`.
19
+ * `rspack serve` reads `devServer` from the compiler after plugins apply,
20
+ * so wrapping `onListening` here reaches the server it starts.
21
+ */
22
+ function applyDevServerReadySignal(compiler) {
23
+ const devServer = compiler.options.devServer;
24
+ if (!devServer || !process.env.NX_READY_SIGNAL_SOCKET) {
25
+ return;
26
+ }
27
+ const { signalTaskReady } = require('@nx/devkit');
28
+ const onListening = devServer.onListening;
29
+ devServer.onListening = (server) => {
30
+ onListening?.(server);
31
+ signalTaskReady({ url: getDevServerUrl(server) });
32
+ };
33
+ }
34
+ /** Reports the dev server's address to an Nx task whose readyWhen is `signal`. */
35
+ class NxReadySignalPlugin {
36
+ constructor() {
37
+ this[_a] = true;
38
+ }
39
+ apply(compiler) {
40
+ applyDevServerReadySignal(compiler);
41
+ }
42
+ }
43
+ exports.NxReadySignalPlugin = NxReadySignalPlugin;
44
+ _a = exports.READY_SIGNAL_PLUGIN;
45
+ function getDevServerUrl(server) {
46
+ const address = server.server?.address();
47
+ if (!address || typeof address === 'string') {
48
+ return undefined;
49
+ }
50
+ const type = typeof server.options?.server === 'string'
51
+ ? server.options.server
52
+ : server.options?.server?.type;
53
+ const protocol = type && type !== 'http' ? 'https' : 'http';
54
+ const host = address.address === '::' || address.address === '0.0.0.0'
55
+ ? 'localhost'
56
+ : address.family === 'IPv6'
57
+ ? `[${address.address}]`
58
+ : address.address;
59
+ return `${protocol}://${host}:${address.port}/`;
60
+ }
@@ -13,6 +13,7 @@ export declare function findExistingTargetsInProject(targets: {
13
13
  userProvidedTargetIsUnsupported: TargetFlags;
14
14
  alreadyHasNxRspackTargets: TargetFlags;
15
15
  };
16
+ export declare function assertNoRemovedExecutorTargets(projectName: string, targets: Record<string, TargetConfiguration> | undefined): void;
16
17
  export declare function writeRspackConfigFile(tree: Tree, options: ConfigurationSchema, stylePreprocessorOptions?: {
17
18
  includePaths?: string[];
18
19
  }): void;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.findExistingTargetsInProject = findExistingTargetsInProject;
4
+ exports.assertNoRemovedExecutorTargets = assertNoRemovedExecutorTargets;
4
5
  exports.writeRspackConfigFile = writeRspackConfigFile;
5
6
  exports.deleteWebpackConfig = deleteWebpackConfig;
6
7
  exports.moveAndEditIndexHtml = moveAndEditIndexHtml;
@@ -22,24 +23,8 @@ function findExistingTargetsInProject(targets, userProvidedTargets) {
22
23
  alreadyHasNxRspackTargets: {},
23
24
  };
24
25
  const supportedExecutors = {
25
- build: [
26
- '@nxext/vite:build',
27
- '@nrwl/webpack:webpack',
28
- '@nrwl/rollup:rollup',
29
- '@nrwl/web:rollup',
30
- '@nrwl/vite:build',
31
- '@nx/webpack:webpack',
32
- '@nx/rollup:rollup',
33
- '@nx/web:rollup',
34
- '@nx/vite:build',
35
- ],
36
- serve: [
37
- '@nxext/vite:dev',
38
- '@nrwl/webpack:dev-server',
39
- '@nrwl/vite:dev-server',
40
- '@nx/webpack:dev-server',
41
- '@nx/vite:dev-server',
42
- ],
26
+ build: ['@nxext/vite:build'],
27
+ serve: ['@nxext/vite:dev'],
43
28
  };
44
29
  const unsupportedExecutors = [
45
30
  '@nx/js:babel',
@@ -117,6 +102,28 @@ function findExistingTargetsInProject(targets, userProvidedTargets) {
117
102
  }
118
103
  return output;
119
104
  }
105
+ // A leftover target on one of these can't run, and it shadows the inferred
106
+ // target with the same name, so converting around it leaves a broken project.
107
+ const removedConvertibleExecutors = [
108
+ '@nrwl/rollup:rollup',
109
+ '@nrwl/vite:build',
110
+ '@nrwl/vite:dev-server',
111
+ '@nrwl/webpack:dev-server',
112
+ '@nrwl/webpack:webpack',
113
+ '@nx/rollup:rollup',
114
+ '@nx/vite:build',
115
+ '@nx/vite:dev-server',
116
+ '@nx/webpack:dev-server',
117
+ '@nx/webpack:webpack',
118
+ ];
119
+ function assertNoRemovedExecutorTargets(projectName, targets) {
120
+ const removedTargets = Object.entries(targets ?? {})
121
+ .filter(([, target]) => removedConvertibleExecutors.includes(target.executor))
122
+ .map(([targetName, target]) => `${targetName} (${target.executor})`);
123
+ if (removedTargets.length) {
124
+ throw new Error(`The project ${projectName} has targets using removed executors: ${removedTargets.join(', ')}. Convert them to inferred targets first, for example with "nx g @nx/workspace:infer-targets --project=${projectName}".`);
125
+ }
126
+ }
120
127
  function writeRspackConfigFile(tree, options, stylePreprocessorOptions) {
121
128
  const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
122
129
  tree.write((0, devkit_1.joinPathFragments)(project.root, 'rspack.config.js'), createConfig(tree, { ...options, stylePreprocessorOptions }));
@@ -362,8 +369,7 @@ function determineFrameworkAndTarget(tree, options, projectRoot, targets) {
362
369
  if (options.target !== 'node') {
363
370
  // Try to infer from jest config if the env is node
364
371
  let jestConfigPath;
365
- if (targets?.test?.executor !== '@nx/jest:jest' &&
366
- targets?.test?.options?.jestConfig) {
372
+ if (targets?.test?.options?.jestConfig) {
367
373
  jestConfigPath = targets?.test?.options?.jestConfig;
368
374
  }
369
375
  else {
@@ -8,4 +8,4 @@ import type { Configuration } from '@rspack/core';
8
8
  *
9
9
  * @param rspackConfig
10
10
  */
11
- export declare function readRspackOptions(rspackConfig: unknown): Promise<Configuration[]>;
11
+ export declare function readRspackOptions(rspackConfig: unknown, env?: Record<string, unknown>, argv?: Record<string, unknown>): Promise<Configuration[]>;
@@ -13,7 +13,9 @@ const internal_1 = require("@nx/devkit/internal");
13
13
  *
14
14
  * @param rspackConfig
15
15
  */
16
- async function readRspackOptions(rspackConfig) {
16
+ async function readRspackOptions(rspackConfig,
17
+ // A function config gets the production build's env unless told otherwise
18
+ env = { production: true }, argv = {}) {
17
19
  const configs = [];
18
20
  const resolveConfig = async (config) => {
19
21
  if ((0, config_1.isNxRspackComposablePlugin)(config)) {
@@ -43,9 +45,7 @@ async function readRspackOptions(rspackConfig) {
43
45
  });
44
46
  }
45
47
  else if (typeof config === 'function') {
46
- const resolved = await config({
47
- production: true, // we want the production build options
48
- }, {});
48
+ const resolved = await config(env, argv);
49
49
  // If the resolved configuration is an array, resolve each configuration
50
50
  return Array.isArray(resolved)
51
51
  ? (await Promise.all(resolved.map(resolveConfig))).flat()
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nx/rspack",
3
3
  "description": "The Nx Plugin for Rspack contains executors and generators that support building applications using Rspack.",
4
- "version": "24.0.0-beta.3",
4
+ "version": "24.0.0-beta.4",
5
5
  "type": "commonjs",
6
6
  "files": [
7
7
  "dist",
@@ -43,6 +43,18 @@
43
43
  "plugin.js": [
44
44
  "dist/plugin.d.ts"
45
45
  ],
46
+ "ready-check": [
47
+ "dist/ready-check.d.ts"
48
+ ],
49
+ "ready-check.js": [
50
+ "dist/ready-check.d.ts"
51
+ ],
52
+ "ready-signal": [
53
+ "dist/ready-signal.d.ts"
54
+ ],
55
+ "ready-signal.js": [
56
+ "dist/ready-signal.d.ts"
57
+ ],
46
58
  "react-plugin": [
47
59
  "dist/react-plugin.d.ts"
48
60
  ],
@@ -89,6 +101,26 @@
89
101
  "types": "./dist/plugin.d.ts",
90
102
  "default": "./dist/plugin.js"
91
103
  },
104
+ "./ready-check": {
105
+ "@nx/nx-source": "./ready-check.ts",
106
+ "types": "./dist/ready-check.d.ts",
107
+ "default": "./dist/ready-check.js"
108
+ },
109
+ "./ready-check.js": {
110
+ "@nx/nx-source": "./ready-check.ts",
111
+ "types": "./dist/ready-check.d.ts",
112
+ "default": "./dist/ready-check.js"
113
+ },
114
+ "./ready-signal": {
115
+ "@nx/nx-source": "./ready-signal.ts",
116
+ "types": "./dist/ready-signal.d.ts",
117
+ "default": "./dist/ready-signal.js"
118
+ },
119
+ "./ready-signal.js": {
120
+ "@nx/nx-source": "./ready-signal.ts",
121
+ "types": "./dist/ready-signal.d.ts",
122
+ "default": "./dist/ready-signal.js"
123
+ },
92
124
  "./react-plugin": {
93
125
  "@nx/nx-source": "./react-plugin.ts",
94
126
  "types": "./dist/react-plugin.d.ts",
@@ -111,9 +143,9 @@
111
143
  }
112
144
  },
113
145
  "dependencies": {
114
- "@nx/devkit": "24.0.0-beta.3",
115
- "@nx/js": "24.0.0-beta.3",
116
- "@nx/web": "24.0.0-beta.3",
146
+ "@nx/devkit": "24.0.0-beta.4",
147
+ "@nx/js": "24.0.0-beta.4",
148
+ "@nx/web": "24.0.0-beta.4",
117
149
  "@phenomnomnominal/tsquery": "~6.2.0",
118
150
  "autoprefixer": "^10.4.9",
119
151
  "browserslist": "^4.26.0",
@@ -134,12 +166,12 @@
134
166
  "style-loader": "^3.3.0",
135
167
  "ts-checker-rspack-plugin": "^1.3.0",
136
168
  "tslib": "^2.3.0",
137
- "webpack": "5.109.2",
169
+ "webpack": "5.111.0",
138
170
  "webpack-node-externals": "^3.0.0"
139
171
  },
140
172
  "devDependencies": {
141
- "nx": "24.0.0-beta.3",
142
- "@nx/nest": "24.0.0-beta.3",
173
+ "nx": "24.0.0-beta.4",
174
+ "@nx/nest": "24.0.0-beta.4",
143
175
  "@rspack/cli": "^2.0.4"
144
176
  },
145
177
  "peerDependencies": {