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