@rspack/cli 1.0.14 → 1.1.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,822 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__rspack_core__ from "@rspack/core";
2
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs__ from "node:fs";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_inspector__ from "node:inspector";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url__ from "node:url";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_node_util__ from "node:util";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_colorette__ from "colorette";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_semver__ from "semver";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_yargs__ from "yargs";
10
+ import * as __WEBPACK_EXTERNAL_MODULE_yargs_helpers__ from "yargs/helpers";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_interpret__ from "interpret";
12
+ import * as __WEBPACK_EXTERNAL_MODULE_rechoir__ from "rechoir";
13
+ var __webpack_modules__ = {
14
+ "./src/utils/crossImport.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
15
+ __webpack_require__.d(__webpack_exports__, {
16
+ Z: function() {
17
+ return __WEBPACK_DEFAULT_EXPORT__;
18
+ },
19
+ y: function() {
20
+ return dynamicImport;
21
+ }
22
+ });
23
+ /* ESM import */ var node_url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:url");
24
+ /* ESM import */ var _isEsmFile__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/utils/isEsmFile.ts");
25
+ /**
26
+ * Dynamically import files. It will make sure it's not being compiled away by TS/Rslib.
27
+ */ const dynamicImport = new Function("path", "return import(path)");
28
+ const crossImport = async (path, cwd = process.cwd())=>{
29
+ if ((0, _isEsmFile__WEBPACK_IMPORTED_MODULE_1__ /* ["default"] */ .Z)(path, cwd)) {
30
+ const url = (0, node_url__WEBPACK_IMPORTED_MODULE_0__.pathToFileURL)(path).href;
31
+ const { default: config } = await dynamicImport(url);
32
+ return config;
33
+ }
34
+ let result = require(path);
35
+ // compatible with export default config in common ts config
36
+ if (result && "object" == typeof result && "default" in result) result = result.default || {};
37
+ return result;
38
+ };
39
+ /* ESM default export */ const __WEBPACK_DEFAULT_EXPORT__ = crossImport;
40
+ },
41
+ "./src/utils/isEsmFile.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
42
+ // EXPORTS
43
+ __webpack_require__.d(__webpack_exports__, {
44
+ Z: ()=>/* binding */ isEsmFile
45
+ });
46
+ // EXTERNAL MODULE: external "node:path"
47
+ var external_node_path_ = __webpack_require__("node:path");
48
+ // EXTERNAL MODULE: external "node:fs"
49
+ var external_node_fs_ = __webpack_require__("node:fs");
50
+ const readPackageUp_readPackageUp = (cwd = process.cwd())=>{
51
+ let currentDir = external_node_path_["default"].resolve(cwd);
52
+ let packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
53
+ while(!external_node_fs_["default"].existsSync(packageJsonPath)){
54
+ const parentDir = external_node_path_["default"].dirname(currentDir);
55
+ if (parentDir === currentDir) return null;
56
+ currentDir = parentDir;
57
+ packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
58
+ }
59
+ try {
60
+ return JSON.parse(external_node_fs_["default"].readFileSync(packageJsonPath, "utf8"));
61
+ } catch (error) {
62
+ return null;
63
+ }
64
+ };
65
+ /* ESM default export */ const readPackageUp = readPackageUp_readPackageUp;
66
+ const isEsmFile_isEsmFile = (filePath, cwd = process.cwd())=>{
67
+ const ext = external_node_path_["default"].extname(filePath);
68
+ if (/\.(mjs|mts)$/.test(ext)) return true;
69
+ if (/\.(cjs|cts)/.test(ext)) return false;
70
+ const packageJson = readPackageUp(cwd);
71
+ return (null == packageJson ? void 0 : packageJson.type) === "module";
72
+ };
73
+ /* ESM default export */ const isEsmFile = isEsmFile_isEsmFile;
74
+ },
75
+ "@rspack/core": function(module) {
76
+ module.exports = __WEBPACK_EXTERNAL_MODULE__rspack_core__;
77
+ },
78
+ "node:fs": function(module) {
79
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs__;
80
+ },
81
+ "node:inspector": function(module) {
82
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_inspector__;
83
+ },
84
+ "node:path": function(module) {
85
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_path__;
86
+ },
87
+ "node:url": function(module) {
88
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_url__;
89
+ }
90
+ };
91
+ /************************************************************************/ // The module cache
92
+ var __webpack_module_cache__ = {};
93
+ // The require function
94
+ function __webpack_require__(moduleId) {
95
+ // Check if module is in cache
96
+ var cachedModule = __webpack_module_cache__[moduleId];
97
+ if (void 0 !== cachedModule) return cachedModule.exports;
98
+ // Create a new module (and put it into the cache)
99
+ var module = __webpack_module_cache__[moduleId] = {
100
+ exports: {}
101
+ };
102
+ // Execute the module function
103
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
104
+ // Return the exports of the module
105
+ return module.exports;
106
+ }
107
+ // expose the modules object (__webpack_modules__)
108
+ __webpack_require__.m = __webpack_modules__;
109
+ /************************************************************************/ // webpack/runtime/define_property_getters
110
+ (()=>{
111
+ __webpack_require__.d = function(exports, definition) {
112
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
113
+ enumerable: true,
114
+ get: definition[key]
115
+ });
116
+ };
117
+ })();
118
+ // webpack/runtime/ensure_chunk
119
+ (()=>{
120
+ __webpack_require__.f = {};
121
+ // This file contains only the entry chunk.
122
+ // The chunk loading function for additional chunks
123
+ __webpack_require__.e = function(chunkId) {
124
+ return Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {
125
+ __webpack_require__.f[key](chunkId, promises);
126
+ return promises;
127
+ }, []));
128
+ };
129
+ })();
130
+ // webpack/runtime/get javascript chunk filename
131
+ (()=>{
132
+ // This function allow to reference chunks
133
+ __webpack_require__.u = function(chunkId) {
134
+ // return url for filenames not based on template
135
+ // return url for filenames based on template
136
+ return "" + chunkId + ".mjs";
137
+ };
138
+ })();
139
+ // webpack/runtime/has_own_property
140
+ (()=>{
141
+ __webpack_require__.o = function(obj, prop) {
142
+ return Object.prototype.hasOwnProperty.call(obj, prop);
143
+ };
144
+ })();
145
+ // webpack/runtime/module_chunk_loading
146
+ (()=>{
147
+ // object to store loaded and loading chunks
148
+ // undefined = chunk not loaded, null = chunk preloaded/prefetched
149
+ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
150
+ var installedChunks = {
151
+ 980: 0
152
+ };
153
+ var installChunk = function(data) {
154
+ var ids = data.ids;
155
+ var modules = data.modules;
156
+ var runtime = data.runtime;
157
+ // add "modules" to the modules object,
158
+ // then flag all "ids" as loaded and fire callback
159
+ var moduleId, chunkId, i = 0;
160
+ for(moduleId in modules)if (__webpack_require__.o(modules, moduleId)) __webpack_require__.m[moduleId] = modules[moduleId];
161
+ if (runtime) runtime(__webpack_require__);
162
+ for(; i < ids.length; i++){
163
+ chunkId = ids[i];
164
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
165
+ installedChunks[ids[i]] = 0;
166
+ }
167
+ };
168
+ __webpack_require__.f.j = function(chunkId, promises) {
169
+ // import() chunk loading for javascript
170
+ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
171
+ if (0 !== installedChunkData) {
172
+ // a Promise means "currently loading".
173
+ if (installedChunkData) promises.push(installedChunkData[1]);
174
+ else {
175
+ // setup Promise in chunk cache
176
+ var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, function(e) {
177
+ if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
178
+ throw e;
179
+ });
180
+ var promise = Promise.race([
181
+ promise,
182
+ new Promise(function(resolve) {
183
+ installedChunkData = installedChunks[chunkId] = [
184
+ resolve
185
+ ];
186
+ })
187
+ ]);
188
+ promises.push(installedChunkData[1] = promise);
189
+ }
190
+ }
191
+ };
192
+ })();
193
+ // EXTERNAL MODULE: external "node:path"
194
+ var external_node_path_ = __webpack_require__("node:path");
195
+ // EXTERNAL MODULE: external "@rspack/core"
196
+ var core_ = __webpack_require__("@rspack/core");
197
+ // EXTERNAL MODULE: external "node:fs"
198
+ var external_node_fs_ = __webpack_require__("node:fs");
199
+ const commonOptions = (yargs)=>yargs.options({
200
+ config: {
201
+ g: true,
202
+ type: "string",
203
+ describe: "config file",
204
+ alias: "c"
205
+ },
206
+ entry: {
207
+ type: "array",
208
+ string: true,
209
+ describe: "entry file"
210
+ },
211
+ "output-path": {
212
+ type: "string",
213
+ describe: "output path dir",
214
+ alias: "o"
215
+ },
216
+ mode: {
217
+ type: "string",
218
+ describe: "mode",
219
+ alias: "m"
220
+ },
221
+ watch: {
222
+ type: "boolean",
223
+ default: false,
224
+ describe: "watch",
225
+ alias: "w"
226
+ },
227
+ env: {
228
+ type: "array",
229
+ string: true,
230
+ describe: "env passed to config function"
231
+ },
232
+ "node-env": {
233
+ string: true,
234
+ describe: "sets process.env.NODE_ENV to be specified value"
235
+ },
236
+ devtool: {
237
+ type: "boolean",
238
+ default: false,
239
+ describe: "devtool",
240
+ alias: "d"
241
+ },
242
+ configName: {
243
+ type: "array",
244
+ string: true,
245
+ describe: "Name of the configuration to use."
246
+ }
247
+ }).alias({
248
+ v: "version",
249
+ h: "help"
250
+ });
251
+ const previewOptions = (yargs)=>yargs.positional("dir", {
252
+ type: "string",
253
+ describe: "directory want to preview"
254
+ }).options({
255
+ publicPath: {
256
+ type: "string",
257
+ describe: "static resource server path"
258
+ },
259
+ config: {
260
+ g: true,
261
+ type: "string",
262
+ describe: "config file",
263
+ alias: "c"
264
+ },
265
+ port: {
266
+ type: "number",
267
+ describe: "preview server port"
268
+ },
269
+ host: {
270
+ type: "string",
271
+ describe: "preview server host"
272
+ },
273
+ open: {
274
+ type: "boolean",
275
+ describe: "open browser"
276
+ },
277
+ // same as devServer.server
278
+ server: {
279
+ type: "string",
280
+ describe: "Configuration items for the server."
281
+ },
282
+ configName: {
283
+ type: "array",
284
+ string: true,
285
+ describe: "Name of the configuration to use."
286
+ }
287
+ });
288
+ function normalizeEnv(argv) {
289
+ function parseValue(previous, value) {
290
+ const [allKeys, val] = value.split(/=(.+)/, 2);
291
+ const splitKeys = allKeys.split(/\.(?!$)/);
292
+ let prevRef = previous;
293
+ splitKeys.forEach((key, index)=>{
294
+ let someKey = key;
295
+ // https://github.com/webpack/webpack-cli/issues/3284
296
+ if (someKey.endsWith("=")) {
297
+ // remove '=' from key
298
+ someKey = someKey.slice(0, -1);
299
+ prevRef[someKey] = void 0;
300
+ return;
301
+ }
302
+ if (!prevRef[someKey] || "string" == typeof prevRef[someKey]) prevRef[someKey] = {};
303
+ if (index === splitKeys.length - 1) {
304
+ if ("string" == typeof val) prevRef[someKey] = val;
305
+ else prevRef[someKey] = true;
306
+ }
307
+ prevRef = prevRef[someKey];
308
+ });
309
+ return previous;
310
+ }
311
+ const envObj = (argv.env ?? []).reduce(parseValue, {});
312
+ argv.env = envObj;
313
+ }
314
+ /**
315
+ * set builtin env from cli - like `WEBPACK_BUNDLE=true`. also for `RSPACK_` prefixed.
316
+ * @param env the `argv.env` object
317
+ * @param envNameSuffix the added env will be `WEBPACK_${envNameSuffix}` and `RSPACK_${envNameSuffix}`
318
+ * @param value
319
+ */ function setBuiltinEnvArg(env, envNameSuffix, value) {
320
+ const envNames = [
321
+ // TODO: breaking change
322
+ // `WEBPACK_${envNameSuffix}`,
323
+ `RSPACK_${envNameSuffix}`
324
+ ];
325
+ for (const envName of envNames){
326
+ if (!(envName in env)) env[envName] = value;
327
+ }
328
+ }
329
+ /**
330
+ * infer `argv.env` as an object for it was transformed from array to object after `normalizeEnv` middleware
331
+ * @returns the reference of `argv.env` object
332
+ */ function ensureEnvObject(options) {
333
+ if (Array.isArray(options.env)) // in case that cli haven't got `normalizeEnv` middleware applied
334
+ normalizeEnv(options);
335
+ options.env = options.env || {};
336
+ return options.env;
337
+ }
338
+ class BuildCommand {
339
+ async apply(cli) {
340
+ cli.program.command([
341
+ "build",
342
+ "$0",
343
+ "bundle",
344
+ "b"
345
+ ], "run the rspack build", (yargs)=>commonOptions(yargs).options({
346
+ analyze: {
347
+ type: "boolean",
348
+ default: false,
349
+ describe: "analyze"
350
+ },
351
+ json: {
352
+ describe: "emit stats json"
353
+ },
354
+ profile: {
355
+ type: "boolean",
356
+ default: false,
357
+ describe: "capture timing information for each module"
358
+ }
359
+ }), async (options)=>{
360
+ const env = ensureEnvObject(options);
361
+ if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
362
+ else {
363
+ setBuiltinEnvArg(env, "BUNDLE", true);
364
+ setBuiltinEnvArg(env, "BUILD", true);
365
+ }
366
+ const logger = cli.getLogger();
367
+ let createJsonStringifyStream;
368
+ if (options.json) {
369
+ const jsonExt = await import("@discoveryjs/json-ext");
370
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
371
+ }
372
+ const errorHandler = (error, stats)=>{
373
+ if (error) {
374
+ logger.error(error);
375
+ process.exit(2);
376
+ }
377
+ if (null == stats ? void 0 : stats.hasErrors()) process.exitCode = 1;
378
+ if (!compiler || !stats) return;
379
+ const statsOptions = cli.isMultipleCompiler(compiler) ? {
380
+ children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
381
+ } : compiler.options ? compiler.options.stats : void 0;
382
+ if (options.json && createJsonStringifyStream) {
383
+ const handleWriteError = (error)=>{
384
+ logger.error(error);
385
+ process.exit(2);
386
+ };
387
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
388
+ else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_.createWriteStream(options.json)).on("error", handleWriteError) // Use stderr to logging
389
+ .on("close", ()=>{
390
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
391
+ });
392
+ } else {
393
+ const printedStats = stats.toString(statsOptions);
394
+ // Avoid extra empty line when `stats: 'none'`
395
+ if (printedStats) logger.raw(printedStats);
396
+ }
397
+ };
398
+ const rspackOptions = {
399
+ ...options,
400
+ argv: {
401
+ ...options
402
+ }
403
+ };
404
+ const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler);
405
+ if (!compiler || cli.isWatch(compiler)) return;
406
+ compiler.run((error, stats)=>{
407
+ // If there is a compilation error, the close method should not be called,
408
+ // Otherwise Rspack may generate invalid caches.
409
+ if (error || (null == stats ? void 0 : stats.hasErrors())) errorHandler(error, stats);
410
+ else compiler.close((closeErr)=>{
411
+ if (closeErr) logger.error(closeErr);
412
+ errorHandler(error, stats);
413
+ });
414
+ });
415
+ });
416
+ }
417
+ }
418
+ const defaultRoot = "dist";
419
+ class PreviewCommand {
420
+ async apply(cli) {
421
+ cli.program.command([
422
+ "preview [dir]",
423
+ "preview",
424
+ "p"
425
+ ], "run the rspack server for build output", previewOptions, async (options)=>{
426
+ // config、configName are necessary for loadConfig
427
+ const rspackOptions = {
428
+ config: options.config,
429
+ configName: options.configName,
430
+ argv: {
431
+ ...options
432
+ }
433
+ };
434
+ const { RspackDevServer } = await import("@rspack/dev-server");
435
+ let config = await cli.loadConfig(rspackOptions);
436
+ config = await getPreviewConfig(config, options);
437
+ if (!Array.isArray(config)) config = [
438
+ config
439
+ ];
440
+ // find the possible devServer config
441
+ config = config.find((item)=>item.devServer) || config[0];
442
+ const devServerOptions = config.devServer;
443
+ try {
444
+ const compiler = (0, core_.rspack)({
445
+ entry: {}
446
+ });
447
+ if (!compiler) return;
448
+ const server = new RspackDevServer(devServerOptions, compiler);
449
+ await server.start();
450
+ } catch (error) {
451
+ const logger = cli.getLogger();
452
+ logger.error(error);
453
+ process.exit(2);
454
+ }
455
+ });
456
+ }
457
+ }
458
+ // get the devServerOptions from the config
459
+ async function getPreviewConfig(item, options) {
460
+ const internalPreviewConfig = async (item)=>{
461
+ var _item_output, _item_devServer, _item_devServer1, _item_devServer2, _item_devServer3, _item_devServer4;
462
+ // all of the options that a preview static server needs(maybe not all)
463
+ item.devServer = {
464
+ static: {
465
+ directory: options.dir ? external_node_path_["default"].join(item.context ?? process.cwd(), options.dir) : (null === (_item_output = item.output) || void 0 === _item_output ? void 0 : _item_output.path) ?? external_node_path_["default"].join(item.context ?? process.cwd(), defaultRoot),
466
+ publicPath: options.publicPath ?? "/"
467
+ },
468
+ port: options.port ?? 8080,
469
+ proxy: null === (_item_devServer = item.devServer) || void 0 === _item_devServer ? void 0 : _item_devServer.proxy,
470
+ host: options.host ?? (null === (_item_devServer1 = item.devServer) || void 0 === _item_devServer1 ? void 0 : _item_devServer1.host),
471
+ open: options.open ?? (null === (_item_devServer2 = item.devServer) || void 0 === _item_devServer2 ? void 0 : _item_devServer2.open),
472
+ server: options.server ?? (null === (_item_devServer3 = item.devServer) || void 0 === _item_devServer3 ? void 0 : _item_devServer3.server),
473
+ historyApiFallback: null === (_item_devServer4 = item.devServer) || void 0 === _item_devServer4 ? void 0 : _item_devServer4.historyApiFallback
474
+ };
475
+ return item;
476
+ };
477
+ if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
478
+ return internalPreviewConfig(item);
479
+ }
480
+ class ServeCommand {
481
+ async apply(cli) {
482
+ cli.program.command([
483
+ "serve",
484
+ "server",
485
+ "s",
486
+ "dev"
487
+ ], "run the rspack dev server.", (yargs)=>commonOptions(yargs).options({
488
+ hot: {
489
+ coerce: (arg)=>{
490
+ if ("boolean" == typeof arg || "only" === arg) return arg;
491
+ if ("false" === arg) return false;
492
+ return true;
493
+ },
494
+ describe: "enables hot module replacement"
495
+ },
496
+ port: {
497
+ type: "number",
498
+ coerce: (arg)=>Number.isInteger(arg) ? arg : void 0,
499
+ describe: "allows to specify a port to use"
500
+ },
501
+ host: {
502
+ type: "string",
503
+ describe: "allows to specify a hostname to use"
504
+ }
505
+ }), async (options)=>{
506
+ setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true);
507
+ const rspackOptions = {
508
+ ...options,
509
+ argv: {
510
+ ...options
511
+ }
512
+ };
513
+ /**
514
+ * webpack-dev-server will set `process.env.WEBPACK_SERVE` to true
515
+ * when its module is imported, so we have to lazy load the package
516
+ * to make sure the envvar is not set on build mode.
517
+ * when run in serve mode, we have to load the package before config
518
+ * module is imported so that the envvar `process.env.WEBPACK_SERVE`
519
+ * got in config module could be `true`.
520
+ * related issue: https://github.com/web-infra-dev/rspack/issues/6359
521
+ */ const { RspackDevServer } = await import("@rspack/dev-server");
522
+ const compiler = await cli.createCompiler(rspackOptions, "serve");
523
+ if (!compiler) return;
524
+ const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [
525
+ compiler
526
+ ];
527
+ const possibleCompilers = compilers.filter((compiler)=>compiler.options.devServer);
528
+ const usedPorts = [];
529
+ const servers = [];
530
+ /**
531
+ * Webpack uses an Array of compilerForDevServer,
532
+ * however according to it's doc https://webpack.js.org/configuration/dev-server/#devserverhot
533
+ * It should use only the first one
534
+ *
535
+ * Choose the one for configure devServer
536
+ */ const compilerForDevServer = possibleCompilers.length > 0 ? possibleCompilers[0] : compilers[0];
537
+ /**
538
+ * Rspack relies on devServer.hot to enable HMR
539
+ */ for (const compiler of compilers){
540
+ const devServer = compiler.options.devServer ??= {};
541
+ devServer.hot = options.hot ?? devServer.hot ?? true;
542
+ if (false !== devServer.client) {
543
+ if (true === devServer.client || null == devServer.client) devServer.client = {};
544
+ devServer.client = {
545
+ overlay: {
546
+ errors: true,
547
+ warnings: false
548
+ },
549
+ ...devServer.client
550
+ };
551
+ }
552
+ }
553
+ const result = compilerForDevServer.options.devServer ??= {};
554
+ /**
555
+ * Enable this to tell Rspack that we need to enable React Refresh by default
556
+ */ result.hot = options.hot ?? result.hot ?? true;
557
+ result.host = options.host || result.host;
558
+ result.port = options.port || result.port;
559
+ if (false !== result.client) {
560
+ if (true === result.client || null == result.client) result.client = {};
561
+ result.client = {
562
+ overlay: {
563
+ errors: true,
564
+ warnings: false
565
+ },
566
+ ...result.client
567
+ };
568
+ }
569
+ const devServerOptions = result;
570
+ if (devServerOptions.port) {
571
+ const portNumber = Number(devServerOptions.port);
572
+ if (!Number.isNaN(portNumber)) {
573
+ if (usedPorts.find((port)=>portNumber === port)) throw new Error("Unique ports must be specified for each devServer option in your rspack configuration. Alternatively, run only 1 devServer config using the --config-name flag to specify your desired config.");
574
+ usedPorts.push(portNumber);
575
+ }
576
+ }
577
+ try {
578
+ const server = new RspackDevServer(devServerOptions, compiler);
579
+ await server.start();
580
+ servers.push(server);
581
+ } catch (error) {
582
+ const logger = cli.getLogger();
583
+ logger.error(error);
584
+ process.exit(2);
585
+ }
586
+ });
587
+ }
588
+ }
589
+ // EXTERNAL MODULE: ./src/utils/crossImport.ts
590
+ var crossImport = __webpack_require__("./src/utils/crossImport.ts");
591
+ const DEFAULT_EXTENSIONS = [
592
+ ".js",
593
+ ".ts",
594
+ ".mjs",
595
+ ".mts",
596
+ ".cjs",
597
+ ".cts"
598
+ ];
599
+ /**
600
+ * Takes a basePath like `webpack.config`, return `webpack.config.{ext}` if
601
+ * exists. returns undefined if none of them exists
602
+ */ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_["default"].existsSync);
603
+ /* ESM default export */ const utils_findConfig = findConfig;
604
+ // EXTERNAL MODULE: ./src/utils/isEsmFile.ts + 1 modules
605
+ var isEsmFile = __webpack_require__("./src/utils/isEsmFile.ts");
606
+ const isTsFile = (configPath)=>{
607
+ const ext = external_node_path_["default"].extname(configPath);
608
+ return /\.(c|m)?ts$/.test(ext);
609
+ };
610
+ /* ESM default export */ const utils_isTsFile = isTsFile;
611
+ const loadConfig_DEFAULT_CONFIG_NAME = "rspack.config";
612
+ const registerLoader = (configPath)=>{
613
+ const ext = external_node_path_["default"].extname(configPath);
614
+ // TODO implement good `.mts` support after https://github.com/gulpjs/rechoir/issues/43
615
+ // For ESM and `.mts` you need to use: 'NODE_OPTIONS="--loader ts-node/esm" rspack build --config ./rspack.config.mts'
616
+ if ((0, isEsmFile /* default */ .Z)(configPath) && utils_isTsFile(configPath)) return;
617
+ const extensions = Object.fromEntries(Object.entries(__WEBPACK_EXTERNAL_MODULE_interpret__["default"].extensions).filter(([key])=>key === ext));
618
+ if (0 === Object.keys(extensions).length) throw new Error(`config file "${configPath}" is not supported.`);
619
+ try {
620
+ __WEBPACK_EXTERNAL_MODULE_rechoir__["default"].prepare(extensions, configPath);
621
+ } catch (error) {
622
+ const failures = null == error ? void 0 : error.failures;
623
+ if (failures) {
624
+ const messages = failures.map((failure)=>failure.error.message);
625
+ throw new Error(`${messages.join("\n")}`);
626
+ }
627
+ throw error;
628
+ }
629
+ };
630
+ async function loadRspackConfig(options, cwd = process.cwd()) {
631
+ if (options.config) {
632
+ const configPath = external_node_path_["default"].resolve(cwd, options.config);
633
+ if (!external_node_fs_["default"].existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`);
634
+ utils_isTsFile(configPath) && registerLoader(configPath);
635
+ return (0, crossImport /* default */ .Z)(configPath, cwd);
636
+ }
637
+ const defaultConfig = utils_findConfig(external_node_path_["default"].resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME));
638
+ if (defaultConfig) {
639
+ utils_isTsFile(defaultConfig) && registerLoader(defaultConfig);
640
+ return (0, crossImport /* default */ .Z)(defaultConfig, cwd);
641
+ }
642
+ return {};
643
+ }
644
+ function _define_property(obj, key, value) {
645
+ if (key in obj) Object.defineProperty(obj, key, {
646
+ value: value,
647
+ enumerable: true,
648
+ configurable: true,
649
+ writable: true
650
+ });
651
+ else obj[key] = value;
652
+ return obj;
653
+ }
654
+ class RspackCLI {
655
+ async createCompiler(options, rspackCommand, callback) {
656
+ var _process_env, _process;
657
+ process.env.RSPACK_CONFIG_VALIDATE ??= "loose";
658
+ process.env.WATCHPACK_WATCHER_LIMIT = process.env.WATCHPACK_WATCHER_LIMIT || "20";
659
+ const nodeEnv = null === (_process = process) || void 0 === _process ? void 0 : null === (_process_env = _process.env) || void 0 === _process_env ? void 0 : _process_env.NODE_ENV;
660
+ const rspackCommandDefaultEnv = "build" === rspackCommand ? "production" : "development";
661
+ if ("string" == typeof options.nodeEnv) process.env.NODE_ENV = nodeEnv || options.nodeEnv;
662
+ else process.env.NODE_ENV = nodeEnv || rspackCommandDefaultEnv;
663
+ let config = await this.loadConfig(options);
664
+ config = await this.buildConfig(config, options, rspackCommand);
665
+ const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
666
+ let compiler;
667
+ try {
668
+ compiler = (0, core_.rspack)(config, isWatch ? callback : void 0);
669
+ } catch (e) {
670
+ // Aligned with webpack-cli
671
+ // See: https://github.com/webpack/webpack-cli/blob/eea6adf7d34dfbfd3b5b784ece4a4664834f5a6a/packages/webpack-cli/src/webpack-cli.ts#L2394
672
+ if (e instanceof core_.ValidationError) {
673
+ this.getLogger().error(e.message);
674
+ process.exit(2);
675
+ } else if (e instanceof Error) {
676
+ if ("function" == typeof callback) callback(e);
677
+ else this.getLogger().error(e);
678
+ return null;
679
+ }
680
+ throw e;
681
+ }
682
+ return compiler;
683
+ }
684
+ createColors(useColor) {
685
+ const shouldUseColor = useColor || __WEBPACK_EXTERNAL_MODULE_colorette__.isColorSupported;
686
+ return {
687
+ ...(0, __WEBPACK_EXTERNAL_MODULE_colorette__.createColors)({
688
+ useColor: shouldUseColor
689
+ }),
690
+ isColorSupported: shouldUseColor
691
+ };
692
+ }
693
+ getLogger() {
694
+ return {
695
+ error: (val)=>console.error(`[rspack-cli] ${this.colors.red(__WEBPACK_EXTERNAL_MODULE_node_util__["default"].format(val))}`),
696
+ warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`),
697
+ info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`),
698
+ success: (val)=>console.log(`[rspack-cli] ${this.colors.green(val)}`),
699
+ log: (val)=>console.log(`[rspack-cli] ${val}`),
700
+ raw: (val)=>console.log(val)
701
+ };
702
+ }
703
+ async run(argv) {
704
+ if (__WEBPACK_EXTERNAL_MODULE_semver__["default"].lt(__WEBPACK_EXTERNAL_MODULE_semver__["default"].clean(process.version), "14.0.0")) this.getLogger().warn(`Minimum recommended Node.js version is 14.0.0, current version is ${process.version}`);
705
+ this.program.showHelpOnFail(false);
706
+ this.program.usage("[options]");
707
+ this.program.scriptName("rspack");
708
+ this.program.strictCommands(true).strict(true);
709
+ this.program.middleware(normalizeEnv);
710
+ this.registerCommands();
711
+ await this.program.parseAsync((0, __WEBPACK_EXTERNAL_MODULE_yargs_helpers__.hideBin)(argv));
712
+ }
713
+ async registerCommands() {
714
+ const builtinCommands = [
715
+ new BuildCommand(),
716
+ new ServeCommand(),
717
+ new PreviewCommand()
718
+ ];
719
+ for (const command of builtinCommands)command.apply(this);
720
+ }
721
+ async buildConfig(item, options, command) {
722
+ const isBuild = "build" === command;
723
+ const isServe = "serve" === command;
724
+ const commandDefaultEnv = isBuild ? "production" : "development";
725
+ const internalBuildConfig = async (item)=>{
726
+ if (options.entry) item.entry = {
727
+ main: options.entry.map((x)=>external_node_path_["default"].resolve(process.cwd(), x))[0] // Fix me when entry supports array
728
+ };
729
+ // to set output.path
730
+ item.output = item.output || {};
731
+ if (options["output-path"]) item.output.path = external_node_path_["default"].resolve(process.cwd(), options["output-path"]);
732
+ if (options.analyze) {
733
+ const { BundleAnalyzerPlugin } = await import("webpack-bundle-analyzer");
734
+ (item.plugins ??= []).push({
735
+ name: "rspack-bundle-analyzer",
736
+ apply (compiler) {
737
+ new BundleAnalyzerPlugin({
738
+ generateStatsFile: true
739
+ }).apply(compiler);
740
+ }
741
+ });
742
+ }
743
+ if (options.profile) item.profile = true;
744
+ if (process.env.RSPACK_PROFILE) {
745
+ const { applyProfile } = await __webpack_require__.e(/* import() */ "629").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts"));
746
+ await applyProfile(process.env.RSPACK_PROFILE, item);
747
+ }
748
+ // cli --watch overrides the watch config
749
+ if (options.watch) item.watch = options.watch;
750
+ // auto set default mode if user config don't set it
751
+ if (!item.mode) item.mode = commandDefaultEnv ?? "none";
752
+ // user parameters always has highest priority than default mode and config mode
753
+ if (options.mode) item.mode = options.mode;
754
+ // false is also a valid value for sourcemap, so don't override it
755
+ if (void 0 === item.devtool) item.devtool = isBuild ? "source-map" : "cheap-module-source-map";
756
+ if (isServe) {
757
+ const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin);
758
+ if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin());
759
+ }
760
+ if (void 0 === item.stats) item.stats = {
761
+ preset: "errors-warnings",
762
+ timings: true
763
+ };
764
+ else if ("boolean" == typeof item.stats) item.stats = item.stats ? {
765
+ preset: "normal"
766
+ } : {
767
+ preset: "none"
768
+ };
769
+ else if ("string" == typeof item.stats) item.stats = {
770
+ preset: item.stats
771
+ };
772
+ if (this.colors.isColorSupported && void 0 === item.stats.colors) item.stats.colors = true;
773
+ return item;
774
+ };
775
+ if (Array.isArray(item)) return Promise.all(item.map(internalBuildConfig));
776
+ return internalBuildConfig(item);
777
+ }
778
+ async loadConfig(options) {
779
+ let loadedConfig = await loadRspackConfig(options);
780
+ if (options.configName) {
781
+ const notFoundConfigNames = [];
782
+ loadedConfig = options.configName.map((configName)=>{
783
+ let found;
784
+ found = Array.isArray(loadedConfig) ? loadedConfig.find((options)=>options.name === configName) : loadedConfig.name === configName ? loadedConfig : void 0;
785
+ if (!found) notFoundConfigNames.push(configName);
786
+ // WARNING: if config is not found, the program will exit
787
+ // so assert here is okay to avoid runtime filtering
788
+ return found;
789
+ });
790
+ if (notFoundConfigNames.length > 0) {
791
+ this.getLogger().error(notFoundConfigNames.map((configName)=>`Configuration with the name "${configName}" was not found.`).join(" "));
792
+ process.exit(2);
793
+ }
794
+ }
795
+ if ("function" == typeof loadedConfig) {
796
+ var _options_argv;
797
+ loadedConfig = loadedConfig(null === (_options_argv = options.argv) || void 0 === _options_argv ? void 0 : _options_argv.env, options.argv);
798
+ // if return promise we should await its result
799
+ if ("function" == typeof loadedConfig.then) loadedConfig = await loadedConfig;
800
+ }
801
+ return loadedConfig;
802
+ }
803
+ isMultipleCompiler(compiler) {
804
+ return Boolean(compiler.compilers);
805
+ }
806
+ isWatch(compiler) {
807
+ return Boolean(this.isMultipleCompiler(compiler) ? compiler.compilers.some((compiler)=>compiler.options.watch) : compiler.options.watch);
808
+ }
809
+ constructor(){
810
+ _define_property(this, "colors", void 0);
811
+ _define_property(this, "program", void 0);
812
+ this.colors = this.createColors();
813
+ this.program = (0, __WEBPACK_EXTERNAL_MODULE_yargs__["default"])();
814
+ }
815
+ }
816
+ function defineConfig(config) {
817
+ return config;
818
+ }
819
+ function definePlugin(plugin) {
820
+ return plugin;
821
+ }
822
+ export { RspackCLI, defineConfig, definePlugin };