@rspack/cli 1.5.8 → 1.6.0-beta.1

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,30 +1,179 @@
1
- "use strict";
1
+ const __rslib_import_meta_url__ = /*#__PURE__*/ function() {
2
+ return 'undefined' == typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
3
+ }();
2
4
  var __webpack_modules__ = {
3
- "@rspack/core": function(module) {
4
- module.exports = require("@rspack/core");
5
+ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js": function(module) {
6
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
7
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || "win32" === p.platform || (p.stdout || {}).isTTY && "dumb" !== env.TERM || !!env.CI);
8
+ let formatter = (open, close, replace = open)=>(input)=>{
9
+ let string = "" + input, index = string.indexOf(close, open.length);
10
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
11
+ };
12
+ let replaceClose = (string, close, replace, index)=>{
13
+ let result = "", cursor = 0;
14
+ do {
15
+ result += string.substring(cursor, index) + replace;
16
+ cursor = index + close.length;
17
+ index = string.indexOf(close, cursor);
18
+ }while (~index);
19
+ return result + string.substring(cursor);
20
+ };
21
+ let createColors = (enabled = isColorSupported)=>{
22
+ let f = enabled ? formatter : ()=>String;
23
+ return {
24
+ isColorSupported: enabled,
25
+ reset: f("\x1b[0m", "\x1b[0m"),
26
+ bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
27
+ dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
28
+ italic: f("\x1b[3m", "\x1b[23m"),
29
+ underline: f("\x1b[4m", "\x1b[24m"),
30
+ inverse: f("\x1b[7m", "\x1b[27m"),
31
+ hidden: f("\x1b[8m", "\x1b[28m"),
32
+ strikethrough: f("\x1b[9m", "\x1b[29m"),
33
+ black: f("\x1b[30m", "\x1b[39m"),
34
+ red: f("\x1b[31m", "\x1b[39m"),
35
+ green: f("\x1b[32m", "\x1b[39m"),
36
+ yellow: f("\x1b[33m", "\x1b[39m"),
37
+ blue: f("\x1b[34m", "\x1b[39m"),
38
+ magenta: f("\x1b[35m", "\x1b[39m"),
39
+ cyan: f("\x1b[36m", "\x1b[39m"),
40
+ white: f("\x1b[37m", "\x1b[39m"),
41
+ gray: f("\x1b[90m", "\x1b[39m"),
42
+ bgBlack: f("\x1b[40m", "\x1b[49m"),
43
+ bgRed: f("\x1b[41m", "\x1b[49m"),
44
+ bgGreen: f("\x1b[42m", "\x1b[49m"),
45
+ bgYellow: f("\x1b[43m", "\x1b[49m"),
46
+ bgBlue: f("\x1b[44m", "\x1b[49m"),
47
+ bgMagenta: f("\x1b[45m", "\x1b[49m"),
48
+ bgCyan: f("\x1b[46m", "\x1b[49m"),
49
+ bgWhite: f("\x1b[47m", "\x1b[49m"),
50
+ blackBright: f("\x1b[90m", "\x1b[39m"),
51
+ redBright: f("\x1b[91m", "\x1b[39m"),
52
+ greenBright: f("\x1b[92m", "\x1b[39m"),
53
+ yellowBright: f("\x1b[93m", "\x1b[39m"),
54
+ blueBright: f("\x1b[94m", "\x1b[39m"),
55
+ magentaBright: f("\x1b[95m", "\x1b[39m"),
56
+ cyanBright: f("\x1b[96m", "\x1b[39m"),
57
+ whiteBright: f("\x1b[97m", "\x1b[39m"),
58
+ bgBlackBright: f("\x1b[100m", "\x1b[49m"),
59
+ bgRedBright: f("\x1b[101m", "\x1b[49m"),
60
+ bgGreenBright: f("\x1b[102m", "\x1b[49m"),
61
+ bgYellowBright: f("\x1b[103m", "\x1b[49m"),
62
+ bgBlueBright: f("\x1b[104m", "\x1b[49m"),
63
+ bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
64
+ bgCyanBright: f("\x1b[106m", "\x1b[49m"),
65
+ bgWhiteBright: f("\x1b[107m", "\x1b[49m")
66
+ };
67
+ };
68
+ module.exports = createColors();
69
+ module.exports.createColors = createColors;
70
+ },
71
+ "../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js": function(module, exports1, __webpack_require__) {
72
+ "use strict";
73
+ module = __webpack_require__.nmd(module);
74
+ const BuiltinModule = __webpack_require__("module");
75
+ const path = __webpack_require__("path");
76
+ const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
77
+ const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule;
78
+ const HOOK_RETURNED_NOTHING_ERROR_MESSAGE = "[Pirates] A hook returned a non-string, or nothing at all! This is a violation of intergalactic law!\n--------------------\nIf you have no idea what this means or what Pirates is, let me explain: Pirates is a module that makes it easy to implement require hooks. One of the require hooks you're using uses it. One of these require hooks didn't return anything from it's handler, so we don't know what to do. You might want to debug this.";
79
+ function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
80
+ if ('string' != typeof filename) return false;
81
+ if (-1 === exts.indexOf(path.extname(filename))) return false;
82
+ const resolvedFilename = path.resolve(filename);
83
+ if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) return false;
84
+ if (matcher && 'function' == typeof matcher) return !!matcher(resolvedFilename);
85
+ return true;
86
+ }
87
+ function addHook(hook, opts = {}) {
88
+ let reverted = false;
89
+ const loaders = [];
90
+ const oldLoaders = [];
91
+ let exts;
92
+ const originalJSLoader = Module._extensions['.js'];
93
+ const matcher = opts.matcher || null;
94
+ const ignoreNodeModules = false !== opts.ignoreNodeModules;
95
+ exts = opts.extensions || opts.exts || opts.extension || opts.ext || [
96
+ '.js'
97
+ ];
98
+ if (!Array.isArray(exts)) exts = [
99
+ exts
100
+ ];
101
+ exts.forEach((ext)=>{
102
+ if ('string' != typeof ext) throw new TypeError(`Invalid Extension: ${ext}`);
103
+ const oldLoader = Module._extensions[ext] || originalJSLoader;
104
+ oldLoaders[ext] = Module._extensions[ext];
105
+ loaders[ext] = Module._extensions[ext] = function(mod, filename) {
106
+ let compile;
107
+ if (!reverted) {
108
+ if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
109
+ compile = mod._compile;
110
+ mod._compile = function(code) {
111
+ mod._compile = compile;
112
+ const newCode = hook(code, filename);
113
+ if ('string' != typeof newCode) throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
114
+ return mod._compile(newCode, filename);
115
+ };
116
+ }
117
+ }
118
+ oldLoader(mod, filename);
119
+ };
120
+ });
121
+ return function() {
122
+ if (reverted) return;
123
+ reverted = true;
124
+ exts.forEach((ext)=>{
125
+ if (Module._extensions[ext] === loaders[ext]) if (oldLoaders[ext]) Module._extensions[ext] = oldLoaders[ext];
126
+ else delete Module._extensions[ext];
127
+ });
128
+ };
129
+ }
130
+ exports1.addHook = addHook;
131
+ },
132
+ "./src/utils/rspackCore.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
133
+ "use strict";
134
+ __webpack_require__.d(__webpack_exports__, {
135
+ Z: ()=>rspack
136
+ });
137
+ const external_node_module_namespaceObject = require("node:module");
138
+ const rspackCore_require = (0, external_node_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
139
+ const rspack = rspackCore_require("@rspack/core");
140
+ },
141
+ module: function(module) {
142
+ "use strict";
143
+ module.exports = require("module");
5
144
  },
6
145
  "node:fs": function(module) {
146
+ "use strict";
7
147
  module.exports = require("node:fs");
8
148
  },
9
149
  "node:path": function(module) {
150
+ "use strict";
10
151
  module.exports = require("node:path");
11
152
  },
153
+ path: function(module) {
154
+ "use strict";
155
+ module.exports = require("path");
156
+ },
12
157
  "@discoveryjs/json-ext": function(module) {
158
+ "use strict";
13
159
  module.exports = import("@discoveryjs/json-ext").then(function(module) {
14
160
  return module;
15
161
  });
16
162
  },
17
163
  "@rspack/dev-server": function(module) {
164
+ "use strict";
18
165
  module.exports = import("@rspack/dev-server").then(function(module) {
19
166
  return module;
20
167
  });
21
168
  },
22
169
  "exit-hook": function(module) {
170
+ "use strict";
23
171
  module.exports = import("exit-hook").then(function(module) {
24
172
  return module;
25
173
  });
26
174
  },
27
175
  "webpack-bundle-analyzer": function(module) {
176
+ "use strict";
28
177
  module.exports = import("webpack-bundle-analyzer").then(function(module) {
29
178
  return module;
30
179
  });
@@ -35,9 +184,12 @@ function __webpack_require__(moduleId) {
35
184
  var cachedModule = __webpack_module_cache__[moduleId];
36
185
  if (void 0 !== cachedModule) return cachedModule.exports;
37
186
  var module = __webpack_module_cache__[moduleId] = {
187
+ id: moduleId,
188
+ loaded: false,
38
189
  exports: {}
39
190
  };
40
191
  __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
192
+ module.loaded = true;
41
193
  return module.exports;
42
194
  }
43
195
  __webpack_require__.m = __webpack_modules__;
@@ -66,7 +218,7 @@ __webpack_require__.m = __webpack_modules__;
66
218
  }, []));
67
219
  })();
68
220
  (()=>{
69
- __webpack_require__.u = (chunkId)=>"" + chunkId + ".js";
221
+ __webpack_require__.u = (chunkId)=>"0~" + chunkId + ".js";
70
222
  })();
71
223
  (()=>{
72
224
  __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
@@ -81,6 +233,13 @@ __webpack_require__.m = __webpack_modules__;
81
233
  });
82
234
  };
83
235
  })();
236
+ (()=>{
237
+ __webpack_require__.nmd = (module)=>{
238
+ module.paths = [];
239
+ if (!module.children) module.children = [];
240
+ return module;
241
+ };
242
+ })();
84
243
  (()=>{
85
244
  var installedChunks = {
86
245
  410: 1
@@ -97,6 +256,7 @@ __webpack_require__.m = __webpack_modules__;
97
256
  })();
98
257
  var __webpack_exports__ = {};
99
258
  (()=>{
259
+ "use strict";
100
260
  __webpack_require__.r(__webpack_exports__);
101
261
  __webpack_require__.d(__webpack_exports__, {
102
262
  defineConfig: ()=>defineConfig,
@@ -107,77 +267,547 @@ var __webpack_exports__ = {};
107
267
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_);
108
268
  const external_node_util_namespaceObject = require("node:util");
109
269
  var external_node_util_default = /*#__PURE__*/ __webpack_require__.n(external_node_util_namespaceObject);
110
- var core_ = __webpack_require__("@rspack/core");
111
- const external_colorette_namespaceObject = require("colorette");
112
- const external_yargs_namespaceObject = require("yargs");
113
- var external_yargs_default = /*#__PURE__*/ __webpack_require__.n(external_yargs_namespaceObject);
114
- const helpers_namespaceObject = require("yargs/helpers");
115
- var external_node_fs_ = __webpack_require__("node:fs");
116
- var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_);
117
- const commonOptions = (yargs)=>yargs.options({
118
- config: {
119
- g: true,
120
- type: "string",
121
- describe: "config file",
122
- alias: "c"
123
- },
124
- configName: {
125
- type: "array",
126
- string: true,
127
- describe: "Name of the configuration to use."
128
- },
129
- configLoader: {
130
- type: "string",
131
- default: "register",
132
- describe: "Specify the loader to load the config file, can be `native` or `register`."
133
- },
134
- nodeEnv: {
135
- string: true,
136
- describe: "sets `process.env.NODE_ENV` to be specified value"
270
+ const external_events_namespaceObject = require("events");
271
+ function toArr(any) {
272
+ return null == any ? [] : Array.isArray(any) ? any : [
273
+ any
274
+ ];
275
+ }
276
+ function toVal(out, key, val, opts) {
277
+ var x, old = out[key], nxt = ~opts.string.indexOf(key) ? null == val || true === val ? '' : String(val) : 'boolean' == typeof val ? val : ~opts.boolean.indexOf(key) ? 'false' === val ? false : 'true' === val || (out._.push((x = +val, 0 * x === 0) ? x : val), !!val) : (x = +val, 0 * x === 0) ? x : val;
278
+ out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
279
+ old,
280
+ nxt
281
+ ];
282
+ }
283
+ function mri2(args, opts) {
284
+ args = args || [];
285
+ opts = opts || {};
286
+ var k, arr, arg, name, val, out = {
287
+ _: []
288
+ };
289
+ var i = 0, j = 0, idx = 0, len = args.length;
290
+ const alibi = void 0 !== opts.alias;
291
+ const strict = void 0 !== opts.unknown;
292
+ const defaults = void 0 !== opts.default;
293
+ opts.alias = opts.alias || {};
294
+ opts.string = toArr(opts.string);
295
+ opts.boolean = toArr(opts.boolean);
296
+ if (alibi) for(k in opts.alias){
297
+ arr = opts.alias[k] = toArr(opts.alias[k]);
298
+ for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
299
+ }
300
+ for(i = opts.boolean.length; i-- > 0;){
301
+ arr = opts.alias[opts.boolean[i]] || [];
302
+ for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]);
303
+ }
304
+ for(i = opts.string.length; i-- > 0;){
305
+ arr = opts.alias[opts.string[i]] || [];
306
+ for(j = arr.length; j-- > 0;)opts.string.push(arr[j]);
307
+ }
308
+ if (defaults) for(k in opts.default){
309
+ name = typeof opts.default[k];
310
+ arr = opts.alias[k] = opts.alias[k] || [];
311
+ if (void 0 !== opts[name]) {
312
+ opts[name].push(k);
313
+ for(i = 0; i < arr.length; i++)opts[name].push(arr[i]);
137
314
  }
138
- });
139
- const commonOptionsForBuildAndServe = (yargs)=>yargs.options({
140
- entry: {
141
- type: "array",
142
- string: true,
143
- describe: "entry file"
144
- },
145
- outputPath: {
146
- type: "string",
147
- describe: "output path dir",
148
- alias: "o"
149
- },
150
- mode: {
151
- type: "string",
152
- describe: "mode",
153
- alias: "m"
154
- },
155
- watch: {
156
- type: "boolean",
157
- default: false,
158
- describe: "watch",
159
- alias: "w"
160
- },
161
- env: {
162
- type: "array",
163
- string: true,
164
- describe: "env passed to config function"
165
- },
166
- devtool: {
167
- type: "string",
168
- describe: "Specify a developer tool for debugging. Defaults to `cheap-module-source-map` in development and `source-map` in production.",
169
- alias: "d",
170
- coerce: (arg)=>{
171
- if ("true" === arg) return "source-map";
172
- if ("false" === arg || "" === arg.trim()) return false;
173
- return arg;
315
+ }
316
+ const keys = strict ? Object.keys(opts.alias) : [];
317
+ for(i = 0; i < len; i++){
318
+ arg = args[i];
319
+ if ('--' === arg) {
320
+ out._ = out._.concat(args.slice(++i));
321
+ break;
322
+ }
323
+ for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
324
+ if (0 === j) out._.push(arg);
325
+ else if ('no-' === arg.substring(j, j + 3)) {
326
+ name = arg.substring(j + 3);
327
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
328
+ out[name] = false;
329
+ } else {
330
+ for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
331
+ name = arg.substring(j, idx);
332
+ val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i];
333
+ arr = 2 === j ? [
334
+ name
335
+ ] : name;
336
+ for(idx = 0; idx < arr.length; idx++){
337
+ name = arr[idx];
338
+ if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
339
+ toVal(out, name, idx + 1 < arr.length || val, opts);
174
340
  }
175
341
  }
176
- }).alias({
177
- v: "version",
178
- h: "help"
179
- });
180
- function normalizeEnv(argv) {
342
+ }
343
+ if (defaults) {
344
+ for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k];
345
+ }
346
+ if (alibi) for(k in out){
347
+ arr = opts.alias[k] || [];
348
+ while(arr.length > 0)out[arr.shift()] = out[k];
349
+ }
350
+ return out;
351
+ }
352
+ const removeBrackets = (v)=>v.replace(/[<[].+/, "").trim();
353
+ const findAllBrackets = (v)=>{
354
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
355
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
356
+ const res = [];
357
+ const parse = (match)=>{
358
+ let variadic = false;
359
+ let value = match[1];
360
+ if (value.startsWith("...")) {
361
+ value = value.slice(3);
362
+ variadic = true;
363
+ }
364
+ return {
365
+ required: match[0].startsWith("<"),
366
+ value,
367
+ variadic
368
+ };
369
+ };
370
+ let angledMatch;
371
+ while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch));
372
+ let squareMatch;
373
+ while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch));
374
+ return res;
375
+ };
376
+ const getMriOptions = (options)=>{
377
+ const result = {
378
+ alias: {},
379
+ boolean: []
380
+ };
381
+ for (const [index, option] of options.entries()){
382
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
383
+ if (option.isBoolean) if (option.negated) {
384
+ const hasStringTypeOption = options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required);
385
+ if (!hasStringTypeOption) result.boolean.push(option.names[0]);
386
+ } else result.boolean.push(option.names[0]);
387
+ }
388
+ return result;
389
+ };
390
+ const findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
391
+ const padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
392
+ const camelcase = (input)=>input.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
393
+ const setDotProp = (obj, keys, val)=>{
394
+ let i = 0;
395
+ let length = keys.length;
396
+ let t = obj;
397
+ let x;
398
+ for(; i < length; ++i){
399
+ x = t[keys[i]];
400
+ t = t[keys[i]] = i === length - 1 ? val : null != x ? x : !~keys[i + 1].indexOf(".") && +keys[i + 1] > -1 ? [] : {};
401
+ }
402
+ };
403
+ const setByType = (obj, transforms)=>{
404
+ for (const key of Object.keys(transforms)){
405
+ const transform = transforms[key];
406
+ if (transform.shouldTransform) {
407
+ obj[key] = Array.prototype.concat.call([], obj[key]);
408
+ if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction);
409
+ }
410
+ }
411
+ };
412
+ const getFileName = (input)=>{
413
+ const m = /([^\\\/]+)$/.exec(input);
414
+ return m ? m[1] : "";
415
+ };
416
+ const camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join(".");
417
+ class CACError extends Error {
418
+ constructor(message){
419
+ super(message);
420
+ this.name = this.constructor.name;
421
+ if ("function" == typeof Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
422
+ else this.stack = new Error(message).stack;
423
+ }
424
+ }
425
+ class Option {
426
+ constructor(rawName, description, config){
427
+ this.rawName = rawName;
428
+ this.description = description;
429
+ this.config = Object.assign({}, config);
430
+ rawName = rawName.replace(/\.\*/g, "");
431
+ this.negated = false;
432
+ this.names = removeBrackets(rawName).split(",").map((v)=>{
433
+ let name = v.trim().replace(/^-{1,2}/, "");
434
+ if (name.startsWith("no-")) {
435
+ this.negated = true;
436
+ name = name.replace(/^no-/, "");
437
+ }
438
+ return camelcaseOptionName(name);
439
+ }).sort((a, b)=>a.length > b.length ? 1 : -1);
440
+ this.name = this.names[this.names.length - 1];
441
+ if (this.negated && null == this.config.default) this.config.default = true;
442
+ if (rawName.includes("<")) this.required = true;
443
+ else if (rawName.includes("[")) this.required = false;
444
+ else this.isBoolean = true;
445
+ }
446
+ }
447
+ const processArgs = process.argv;
448
+ const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
449
+ class Command {
450
+ constructor(rawName, description, config = {}, cli){
451
+ this.rawName = rawName;
452
+ this.description = description;
453
+ this.config = config;
454
+ this.cli = cli;
455
+ this.options = [];
456
+ this.aliasNames = [];
457
+ this.name = removeBrackets(rawName);
458
+ this.args = findAllBrackets(rawName);
459
+ this.examples = [];
460
+ }
461
+ usage(text) {
462
+ this.usageText = text;
463
+ return this;
464
+ }
465
+ allowUnknownOptions() {
466
+ this.config.allowUnknownOptions = true;
467
+ return this;
468
+ }
469
+ ignoreOptionDefaultValue() {
470
+ this.config.ignoreOptionDefaultValue = true;
471
+ return this;
472
+ }
473
+ version(version, customFlags = "-v, --version") {
474
+ this.versionNumber = version;
475
+ this.option(customFlags, "Display version number");
476
+ return this;
477
+ }
478
+ example(example) {
479
+ this.examples.push(example);
480
+ return this;
481
+ }
482
+ option(rawName, description, config) {
483
+ const option = new Option(rawName, description, config);
484
+ this.options.push(option);
485
+ return this;
486
+ }
487
+ alias(name) {
488
+ this.aliasNames.push(name);
489
+ return this;
490
+ }
491
+ action(callback) {
492
+ this.commandAction = callback;
493
+ return this;
494
+ }
495
+ isMatched(name) {
496
+ return this.name === name || this.aliasNames.includes(name);
497
+ }
498
+ get isDefaultCommand() {
499
+ return "" === this.name || this.aliasNames.includes("!");
500
+ }
501
+ get isGlobalCommand() {
502
+ return this instanceof GlobalCommand;
503
+ }
504
+ hasOption(name) {
505
+ name = name.split(".")[0];
506
+ return this.options.find((option)=>option.names.includes(name));
507
+ }
508
+ outputHelp() {
509
+ const { name, commands } = this.cli;
510
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
511
+ let sections = [
512
+ {
513
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
514
+ }
515
+ ];
516
+ sections.push({
517
+ title: "Usage",
518
+ body: ` $ ${name} ${this.usageText || this.rawName}`
519
+ });
520
+ const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
521
+ if (showCommands) {
522
+ const longestCommandName = findLongest(commands.map((command)=>command.rawName));
523
+ sections.push({
524
+ title: "Commands",
525
+ body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
526
+ });
527
+ sections.push({
528
+ title: "For more info, run any command with the `--help` flag",
529
+ body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
530
+ });
531
+ }
532
+ let options = this.isGlobalCommand ? globalOptions : [
533
+ ...this.options,
534
+ ...globalOptions || []
535
+ ];
536
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name);
537
+ if (options.length > 0) {
538
+ const longestOptionName = findLongest(options.map((option)=>option.rawName));
539
+ sections.push({
540
+ title: "Options",
541
+ body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
542
+ });
543
+ }
544
+ if (this.examples.length > 0) sections.push({
545
+ title: "Examples",
546
+ body: this.examples.map((example)=>{
547
+ if ("function" == typeof example) return example(name);
548
+ return example;
549
+ }).join("\n")
550
+ });
551
+ if (helpCallback) sections = helpCallback(sections) || sections;
552
+ console.log(sections.map((section)=>section.title ? `${section.title}:
553
+ ${section.body}` : section.body).join("\n\n"));
554
+ }
555
+ outputVersion() {
556
+ const { name } = this.cli;
557
+ const { versionNumber } = this.cli.globalCommand;
558
+ if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`);
559
+ }
560
+ checkRequiredArgs() {
561
+ const minimalArgsCount = this.args.filter((arg)=>arg.required).length;
562
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
563
+ }
564
+ checkUnknownOptions() {
565
+ const { options, globalCommand } = this.cli;
566
+ if (!this.config.allowUnknownOptions) {
567
+ for (const name of Object.keys(options))if ("--" !== name && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
568
+ }
569
+ }
570
+ checkOptionValue() {
571
+ const { options: parsedOptions, globalCommand } = this.cli;
572
+ const options = [
573
+ ...globalCommand.options,
574
+ ...this.options
575
+ ];
576
+ for (const option of options){
577
+ const value = parsedOptions[option.name.split(".")[0]];
578
+ if (option.required) {
579
+ const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
580
+ if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
581
+ }
582
+ }
583
+ }
584
+ }
585
+ class GlobalCommand extends Command {
586
+ constructor(cli){
587
+ super("@@global@@", "", {}, cli);
588
+ }
589
+ }
590
+ var __assign = Object.assign;
591
+ class CAC extends external_events_namespaceObject.EventEmitter {
592
+ constructor(name = ""){
593
+ super();
594
+ this.name = name;
595
+ this.commands = [];
596
+ this.rawArgs = [];
597
+ this.args = [];
598
+ this.options = {};
599
+ this.globalCommand = new GlobalCommand(this);
600
+ this.globalCommand.usage("<command> [options]");
601
+ }
602
+ usage(text) {
603
+ this.globalCommand.usage(text);
604
+ return this;
605
+ }
606
+ command(rawName, description, config) {
607
+ const command = new Command(rawName, description || "", config, this);
608
+ command.globalCommand = this.globalCommand;
609
+ this.commands.push(command);
610
+ return command;
611
+ }
612
+ option(rawName, description, config) {
613
+ this.globalCommand.option(rawName, description, config);
614
+ return this;
615
+ }
616
+ help(callback) {
617
+ this.globalCommand.option("-h, --help", "Display this message");
618
+ this.globalCommand.helpCallback = callback;
619
+ this.showHelpOnExit = true;
620
+ return this;
621
+ }
622
+ version(version, customFlags = "-v, --version") {
623
+ this.globalCommand.version(version, customFlags);
624
+ this.showVersionOnExit = true;
625
+ return this;
626
+ }
627
+ example(example) {
628
+ this.globalCommand.example(example);
629
+ return this;
630
+ }
631
+ outputHelp() {
632
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
633
+ else this.globalCommand.outputHelp();
634
+ }
635
+ outputVersion() {
636
+ this.globalCommand.outputVersion();
637
+ }
638
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
639
+ this.args = args;
640
+ this.options = options;
641
+ if (matchedCommand) this.matchedCommand = matchedCommand;
642
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
643
+ return this;
644
+ }
645
+ unsetMatchedCommand() {
646
+ this.matchedCommand = void 0;
647
+ this.matchedCommandName = void 0;
648
+ }
649
+ parse(argv = processArgs, { run = true } = {}) {
650
+ this.rawArgs = argv;
651
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
652
+ let shouldParse = true;
653
+ for (const command of this.commands){
654
+ const parsed = this.mri(argv.slice(2), command);
655
+ const commandName = parsed.args[0];
656
+ if (command.isMatched(commandName)) {
657
+ shouldParse = false;
658
+ const parsedInfo = __assign(__assign({}, parsed), {
659
+ args: parsed.args.slice(1)
660
+ });
661
+ this.setParsedInfo(parsedInfo, command, commandName);
662
+ this.emit(`command:${commandName}`, command);
663
+ }
664
+ }
665
+ if (shouldParse) {
666
+ for (const command of this.commands)if ("" === command.name) {
667
+ shouldParse = false;
668
+ const parsed = this.mri(argv.slice(2), command);
669
+ this.setParsedInfo(parsed, command);
670
+ this.emit("command:!", command);
671
+ }
672
+ }
673
+ if (shouldParse) {
674
+ const parsed = this.mri(argv.slice(2));
675
+ this.setParsedInfo(parsed);
676
+ }
677
+ if (this.options.help && this.showHelpOnExit) {
678
+ this.outputHelp();
679
+ run = false;
680
+ this.unsetMatchedCommand();
681
+ }
682
+ if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) {
683
+ this.outputVersion();
684
+ run = false;
685
+ this.unsetMatchedCommand();
686
+ }
687
+ const parsedArgv = {
688
+ args: this.args,
689
+ options: this.options
690
+ };
691
+ if (run) this.runMatchedCommand();
692
+ if (!this.matchedCommand && this.args[0]) this.emit("command:*");
693
+ return parsedArgv;
694
+ }
695
+ mri(argv, command) {
696
+ const cliOptions = [
697
+ ...this.globalCommand.options,
698
+ ...command ? command.options : []
699
+ ];
700
+ const mriOptions = getMriOptions(cliOptions);
701
+ let argsAfterDoubleDashes = [];
702
+ const doubleDashesIndex = argv.indexOf("--");
703
+ if (doubleDashesIndex > -1) {
704
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
705
+ argv = argv.slice(0, doubleDashesIndex);
706
+ }
707
+ let parsed = mri2(argv, mriOptions);
708
+ parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), {
709
+ [camelcaseOptionName(name)]: parsed[name]
710
+ }), {
711
+ _: []
712
+ });
713
+ const args = parsed._;
714
+ const options = {
715
+ "--": argsAfterDoubleDashes
716
+ };
717
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
718
+ let transforms = Object.create(null);
719
+ for (const cliOption of cliOptions){
720
+ if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default;
721
+ if (Array.isArray(cliOption.config.type)) {
722
+ if (void 0 === transforms[cliOption.name]) {
723
+ transforms[cliOption.name] = Object.create(null);
724
+ transforms[cliOption.name]["shouldTransform"] = true;
725
+ transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
726
+ }
727
+ }
728
+ }
729
+ for (const key of Object.keys(parsed))if ("_" !== key) {
730
+ const keys = key.split(".");
731
+ setDotProp(options, keys, parsed[key]);
732
+ setByType(options, transforms);
733
+ }
734
+ return {
735
+ args,
736
+ options
737
+ };
738
+ }
739
+ runMatchedCommand() {
740
+ const { args, options, matchedCommand: command } = this;
741
+ if (!command || !command.commandAction) return;
742
+ command.checkUnknownOptions();
743
+ command.checkOptionValue();
744
+ command.checkRequiredArgs();
745
+ const actionArgs = [];
746
+ command.args.forEach((arg, index)=>{
747
+ if (arg.variadic) actionArgs.push(args.slice(index));
748
+ else actionArgs.push(args[index]);
749
+ });
750
+ actionArgs.push(options);
751
+ return command.commandAction.apply(this, actionArgs);
752
+ }
753
+ }
754
+ const cac = (name = "")=>new CAC(name);
755
+ const dist = cac;
756
+ var picocolors = __webpack_require__("../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");
757
+ var external_node_fs_ = __webpack_require__("node:fs");
758
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_);
759
+ const commonOptions = (command)=>command.option("-c, --config <path>", "config file").option("--config-name <name>", "Name(s) of the configuration to use.", {
760
+ type: [
761
+ String
762
+ ],
763
+ default: []
764
+ }).option("--config-loader <loader>", "Specify the loader to load the config file, can be `native` or `register`.", {
765
+ default: "register"
766
+ }).option("--env <env>", "env passed to config function", {
767
+ type: [
768
+ String
769
+ ],
770
+ default: []
771
+ }).option("--node-env <value>", "sets `process.env.NODE_ENV` to be specified value");
772
+ function normalizeDevtoolOption(value) {
773
+ if ("string" == typeof value) {
774
+ const trimmed = value.trim();
775
+ if ("" === trimmed || "false" === trimmed) return false;
776
+ if ("true" === trimmed) return "source-map";
777
+ return trimmed;
778
+ }
779
+ if ("boolean" == typeof value) return value ? "source-map" : false;
780
+ }
781
+ const normalizeCommonOptions = (options, action)=>{
782
+ const isEmptyArray = (arr)=>Array.isArray(arr) && 0 === arr.length;
783
+ for (const key of [
784
+ "entry",
785
+ "configName"
786
+ ]){
787
+ const val = options[key];
788
+ if (isEmptyArray(val)) options[key] = void 0;
789
+ }
790
+ const env = Array.isArray(options.env) ? normalizeEnvToObject(options) : {};
791
+ options.env = env;
792
+ if ("serve" === action) setBuiltinEnvArg(env, "SERVE", true);
793
+ else if ("build" === action) if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
794
+ else {
795
+ setBuiltinEnvArg(env, "BUNDLE", true);
796
+ setBuiltinEnvArg(env, "BUILD", true);
797
+ }
798
+ if ("devtool" in options) options.devtool = normalizeDevtoolOption(options.devtool);
799
+ };
800
+ const commonOptionsForBuildAndServe = (command)=>command.option("--analyze", "analyze").option("-d, --devtool <value>", "specify a developer tool for debugging. Defaults to `cheap-module-source-map` in development and `source-map` in production.").option("--entry <entry>", "entry file", {
801
+ type: [
802
+ String
803
+ ],
804
+ default: []
805
+ }).option("-m, --mode <mode>", "mode").option("-o, --output-path <dir>", "output path dir").option("--profile", "capture timing information for each module").option("-w, --watch", "watch");
806
+ function setBuiltinEnvArg(env, envNameSuffix, value) {
807
+ const envName = `RSPACK_${envNameSuffix}`;
808
+ if (!(envName in env)) env[envName] = value;
809
+ }
810
+ function normalizeEnvToObject(options) {
181
811
  function parseValue(previous, value) {
182
812
  const [allKeys, val] = value.split(/=(.+)/, 2);
183
813
  const splitKeys = allKeys.split(/\.(?!$)/);
@@ -196,155 +826,80 @@ var __webpack_exports__ = {};
196
826
  });
197
827
  return previous;
198
828
  }
199
- const envObj = (argv.env ?? []).reduce(parseValue, {});
200
- argv.env = envObj;
201
- }
202
- function setBuiltinEnvArg(env, envNameSuffix, value) {
203
- const envNames = [
204
- `RSPACK_${envNameSuffix}`
205
- ];
206
- for (const envName of envNames)if (!(envName in env)) env[envName] = value;
207
- }
208
- function ensureEnvObject(options) {
209
- if (Array.isArray(options.env)) normalizeEnv(options);
210
- options.env = options.env || {};
211
- return options.env;
829
+ return (options.env ?? []).reduce(parseValue, {});
212
830
  }
213
831
  function setDefaultNodeEnv(options, defaultEnv) {
214
- if (void 0 !== process.env.NODE_ENV) return;
215
- process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
832
+ if (void 0 === process.env.NODE_ENV) process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
216
833
  }
217
- class BuildCommand {
218
- async apply(cli) {
219
- cli.program.command([
220
- "build",
221
- "$0",
222
- "bundle",
223
- "b"
224
- ], "run the rspack build", (yargs)=>{
225
- commonOptionsForBuildAndServe(commonOptions(yargs)).options({
226
- analyze: {
227
- type: "boolean",
228
- default: false,
229
- describe: "analyze"
230
- },
231
- json: {
232
- describe: "emit stats json"
233
- },
234
- profile: {
235
- type: "boolean",
236
- default: false,
237
- describe: "capture timing information for each module"
238
- }
239
- });
240
- }, async (options)=>{
241
- setDefaultNodeEnv(options, "production");
242
- const env = ensureEnvObject(options);
243
- if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
244
- else {
245
- setBuiltinEnvArg(env, "BUNDLE", true);
246
- setBuiltinEnvArg(env, "BUILD", true);
247
- }
248
- const logger = cli.getLogger();
249
- let createJsonStringifyStream;
250
- if (options.json) {
251
- const jsonExt = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@discoveryjs/json-ext"));
252
- createJsonStringifyStream = jsonExt.default.stringifyStream;
253
- }
254
- const errorHandler = (error, stats)=>{
255
- if (error) {
256
- logger.error(error);
257
- process.exit(2);
258
- }
259
- if (stats?.hasErrors()) process.exitCode = 1;
260
- if (!compiler || !stats) return;
261
- const statsOptions = cli.isMultipleCompiler(compiler) ? {
262
- children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
263
- } : compiler.options ? compiler.options.stats : void 0;
264
- if (options.json && createJsonStringifyStream) {
265
- const handleWriteError = (error)=>{
266
- logger.error(error);
267
- process.exit(2);
268
- };
269
- if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
270
- else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_.createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{
271
- process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
272
- });
273
- } else {
274
- const printedStats = stats.toString(statsOptions);
275
- if (printedStats) logger.raw(printedStats);
276
- }
277
- };
278
- const rspackOptions = {
279
- ...options,
280
- argv: {
281
- ...options
282
- }
834
+ async function runBuild(cli, options) {
835
+ setDefaultNodeEnv(options, "production");
836
+ normalizeCommonOptions(options, "build");
837
+ const logger = cli.getLogger();
838
+ let createJsonStringifyStream;
839
+ if (options.json) {
840
+ const jsonExt = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@discoveryjs/json-ext"));
841
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
842
+ }
843
+ const errorHandler = (error, stats)=>{
844
+ if (error) {
845
+ logger.error(error);
846
+ process.exit(2);
847
+ }
848
+ if (stats?.hasErrors()) process.exitCode = 1;
849
+ if (!compiler || !stats) return;
850
+ const statsOptions = cli.isMultipleCompiler(compiler) ? {
851
+ children: compiler.compilers.map((item)=>item.options ? item.options.stats : void 0)
852
+ } : compiler.options?.stats;
853
+ if (options.json && createJsonStringifyStream) {
854
+ const handleWriteError = (error)=>{
855
+ logger.error(error);
856
+ process.exit(2);
283
857
  };
284
- const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler);
285
- if (!compiler || cli.isWatch(compiler)) return;
286
- compiler.run((error, stats)=>{
287
- compiler.close((closeErr)=>{
288
- if (closeErr) logger.error(closeErr);
289
- errorHandler(error, stats);
290
- });
858
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
859
+ else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_default().createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{
860
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
291
861
  });
862
+ } else {
863
+ const printedStats = stats.toString(statsOptions);
864
+ if (printedStats) logger.raw(printedStats);
865
+ }
866
+ };
867
+ const compiler = await cli.createCompiler(options, "build", errorHandler);
868
+ if (!compiler || cli.isWatch(compiler)) return;
869
+ compiler.run((error, stats)=>{
870
+ compiler.close((closeErr)=>{
871
+ if (closeErr) logger.error(closeErr);
872
+ errorHandler(error, stats);
873
+ });
874
+ });
875
+ }
876
+ class BuildCommand {
877
+ async apply(cli) {
878
+ const command = cli.program.command("", "run the Rspack build").alias("build").alias("bundle").alias("b");
879
+ commonOptionsForBuildAndServe(commonOptions(command)).option("--json [path]", "emit stats json");
880
+ command.action(async (options)=>{
881
+ await runBuild(cli, options);
292
882
  });
293
883
  }
294
884
  }
295
- const previewOptions = (yargs)=>{
296
- yargs.positional("dir", {
297
- type: "string",
298
- describe: "directory want to preview"
299
- });
300
- return commonOptions(yargs).options({
301
- publicPath: {
302
- type: "string",
303
- describe: "static resource server path"
304
- },
305
- port: {
306
- type: "number",
307
- describe: "preview server port"
308
- },
309
- host: {
310
- type: "string",
311
- describe: "preview server host"
312
- },
313
- open: {
314
- type: "boolean",
315
- describe: "open browser"
316
- },
317
- server: {
318
- type: "string",
319
- describe: "Configuration items for the server."
320
- }
321
- });
322
- };
323
- const defaultRoot = "dist";
885
+ var rspackCore = __webpack_require__("./src/utils/rspackCore.ts");
324
886
  class PreviewCommand {
325
887
  async apply(cli) {
326
- cli.program.command([
327
- "preview [dir]",
328
- "preview",
329
- "p"
330
- ], "run the rspack server for build output", previewOptions, async (options)=>{
888
+ const command = cli.program.command("preview [dir]", "run the Rspack server for build output").alias("p");
889
+ commonOptions(command).option("--public-path <path>", "static resource server path").option("--port <port>", "preview server port").option("--host <host>", "preview server host").option("--open", "open browser").option("--server <config>", "Configuration items for the server.");
890
+ command.action(async (dir, options)=>{
331
891
  setDefaultNodeEnv(options, "production");
332
- const rspackOptions = {
333
- ...options,
334
- argv: {
335
- ...options
336
- }
337
- };
892
+ normalizeCommonOptions(options, "preview");
338
893
  const { RspackDevServer } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@rspack/dev-server"));
339
- let { config } = await cli.loadConfig(rspackOptions);
340
- config = await getPreviewConfig(config, options);
894
+ let { config } = await cli.loadConfig(options);
895
+ config = await getPreviewConfig(config, options, dir);
341
896
  if (!Array.isArray(config)) config = [
342
897
  config
343
898
  ];
344
- config = config.find((item)=>item.devServer) || config[0];
345
- const devServerOptions = config.devServer;
899
+ const singleConfig = config.find((item)=>item.devServer) || config[0];
900
+ const devServerOptions = singleConfig.devServer;
346
901
  try {
347
- const compiler = (0, core_.rspack)({
902
+ const compiler = (0, rspackCore.Z)({
348
903
  entry: {}
349
904
  });
350
905
  if (!compiler) return;
@@ -358,11 +913,12 @@ var __webpack_exports__ = {};
358
913
  });
359
914
  }
360
915
  }
361
- async function getPreviewConfig(item, options) {
916
+ async function getPreviewConfig(item, options, dir) {
917
+ const DEFAULT_ROOT = "dist";
362
918
  const internalPreviewConfig = async (item)=>{
363
919
  item.devServer = {
364
920
  static: {
365
- directory: options.dir ? external_node_path_default().join(item.context ?? process.cwd(), options.dir) : item.output?.path ?? external_node_path_default().join(item.context ?? process.cwd(), defaultRoot),
921
+ directory: dir ? external_node_path_default().join(item.context ?? process.cwd(), dir) : item.output?.path ?? external_node_path_default().join(item.context ?? process.cwd(), DEFAULT_ROOT),
366
922
  publicPath: options.publicPath ?? "/"
367
923
  },
368
924
  port: options.port ?? 8080,
@@ -377,42 +933,21 @@ var __webpack_exports__ = {};
377
933
  if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
378
934
  return internalPreviewConfig(item);
379
935
  }
936
+ function normalizeHotOption(value) {
937
+ if ("boolean" == typeof value || "only" === value) return value;
938
+ if ("false" === value) return false;
939
+ return true;
940
+ }
380
941
  class ServeCommand {
381
942
  async apply(cli) {
382
- cli.program.command([
383
- "serve",
384
- "server",
385
- "s",
386
- "dev"
387
- ], "run the rspack dev server.", (yargs)=>commonOptionsForBuildAndServe(commonOptions(yargs)).options({
388
- hot: {
389
- coerce: (arg)=>{
390
- if ("boolean" == typeof arg || "only" === arg) return arg;
391
- if ("false" === arg) return false;
392
- return true;
393
- },
394
- describe: "enables hot module replacement"
395
- },
396
- port: {
397
- type: "number",
398
- coerce: (arg)=>Number.isInteger(arg) ? arg : void 0,
399
- describe: "allows to specify a port to use"
400
- },
401
- host: {
402
- type: "string",
403
- describe: "allows to specify a hostname to use"
404
- }
405
- }), async (options)=>{
943
+ const command = cli.program.command("serve", "run the rspack dev server.").alias("server").alias("s").alias("dev");
944
+ commonOptionsForBuildAndServe(commonOptions(command)).option("--hot [mode]", "enables hot module replacement").option("--port <port>", "allows to specify a port to use").option("--host <host>", "allows to specify a hostname to use");
945
+ command.action(async (options)=>{
406
946
  setDefaultNodeEnv(options, "development");
407
- setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true);
408
- const rspackOptions = {
409
- ...options,
410
- argv: {
411
- ...options
412
- }
413
- };
947
+ normalizeCommonOptions(options, "serve");
948
+ options.hot = normalizeHotOption(options.hot);
414
949
  const { RspackDevServer } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@rspack/dev-server"));
415
- const compiler = await cli.createCompiler(rspackOptions, "serve");
950
+ const compiler = await cli.createCompiler(options, "serve");
416
951
  if (!compiler) return;
417
952
  const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [
418
953
  compiler
@@ -436,8 +971,8 @@ var __webpack_exports__ = {};
436
971
  }
437
972
  }
438
973
  const result = compilerForDevServer.options.devServer ??= {};
439
- const setupMiddlewares = result.setupMiddlewares;
440
- const lazyCompileMiddleware = core_.rspack.experiments.lazyCompilationMiddleware(compiler);
974
+ const { setupMiddlewares } = result;
975
+ const lazyCompileMiddleware = rspackCore.Z.experiments.lazyCompilationMiddleware(compiler);
441
976
  result.setupMiddlewares = (middlewares, server)=>{
442
977
  let finalMiddlewares = middlewares;
443
978
  if (setupMiddlewares) finalMiddlewares = setupMiddlewares(finalMiddlewares, server);
@@ -448,7 +983,7 @@ var __webpack_exports__ = {};
448
983
  };
449
984
  result.hot = options.hot ?? result.hot ?? true;
450
985
  result.host = options.host || result.host;
451
- result.port = options.port || result.port;
986
+ result.port = options.port ?? result.port;
452
987
  if (false !== result.client) {
453
988
  if (true === result.client || null == result.client) result.client = {};
454
989
  result.client = {
@@ -479,7 +1014,7 @@ var __webpack_exports__ = {};
479
1014
  });
480
1015
  }
481
1016
  }
482
- const external_pirates_namespaceObject = require("pirates");
1017
+ var lib = __webpack_require__("../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js");
483
1018
  const external_node_url_namespaceObject = require("node:url");
484
1019
  const readPackageUp = (cwd = process.cwd())=>{
485
1020
  let currentDir = external_node_path_default().resolve(cwd);
@@ -535,7 +1070,7 @@ var __webpack_exports__ = {};
535
1070
  return TS_EXTENSION.includes(ext);
536
1071
  };
537
1072
  const isTsFile = isTsFile_isTsFile;
538
- const injectInlineSourceMap = ({ filename, code, map })=>{
1073
+ const injectInlineSourceMap = ({ code, map })=>{
539
1074
  if (map) {
540
1075
  const base64Map = Buffer.from(map, "utf8").toString("base64");
541
1076
  const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
@@ -544,7 +1079,7 @@ var __webpack_exports__ = {};
544
1079
  return code;
545
1080
  };
546
1081
  function compile(sourcecode, filename) {
547
- const { code, map } = core_.experiments.swc.transformSync(sourcecode, {
1082
+ const { code, map } = rspackCore.Z.experiments.swc.transformSync(sourcecode, {
548
1083
  jsc: {
549
1084
  parser: {
550
1085
  syntax: "typescript",
@@ -561,7 +1096,6 @@ var __webpack_exports__ = {};
561
1096
  isModule: true
562
1097
  });
563
1098
  return injectInlineSourceMap({
564
- filename,
565
1099
  code,
566
1100
  map
567
1101
  });
@@ -570,7 +1104,7 @@ var __webpack_exports__ = {};
570
1104
  const registerLoader = (configPath)=>{
571
1105
  if (utils_isEsmFile(configPath) && isTsFile(configPath)) return;
572
1106
  if (!isTsFile(configPath)) throw new Error(`config file "${configPath}" is not supported.`);
573
- (0, external_pirates_namespaceObject.addHook)((code, filename)=>{
1107
+ (0, lib.addHook)((code, filename)=>{
574
1108
  try {
575
1109
  return compile(code, filename);
576
1110
  } catch (err) {
@@ -635,7 +1169,7 @@ var __webpack_exports__ = {};
635
1169
  if (isTsFile(resolvedPath) && "register" === options.configLoader) registerLoader(resolvedPath);
636
1170
  let loadedConfig = await crossImport(resolvedPath, cwd);
637
1171
  if ("function" == typeof loadedConfig) {
638
- loadedConfig = loadedConfig(options.argv?.env, options.argv);
1172
+ loadedConfig = loadedConfig(options.env, options);
639
1173
  if ("function" == typeof loadedConfig.then) loadedConfig = await loadedConfig;
640
1174
  }
641
1175
  const { config: extendedConfig, pathMap: extendedPathMap } = await loadExtendedConfig(loadedConfig, resolvedPath, cwd, options);
@@ -643,7 +1177,7 @@ var __webpack_exports__ = {};
643
1177
  ...pathMap.get(resultConfig) || [],
644
1178
  ...extendedPathMap.get(extendedConfig) || []
645
1179
  ];
646
- resultConfig = core_.util.cleverMerge(extendedConfig, resultConfig);
1180
+ resultConfig = rspackCore.Z.util.cleverMerge(extendedConfig, resultConfig);
647
1181
  pathMap.set(resultConfig, configPaths);
648
1182
  }
649
1183
  return {
@@ -672,19 +1206,22 @@ var __webpack_exports__ = {};
672
1206
  colors;
673
1207
  program;
674
1208
  constructor(){
1209
+ const program = dist("rspack");
675
1210
  this.colors = this.createColors();
676
- this.program = external_yargs_default()();
1211
+ this.program = program;
1212
+ program.help();
1213
+ program.version("1.6.0-beta.1");
677
1214
  }
678
1215
  async createCompiler(options, rspackCommand, callback) {
679
- process.env.RSPACK_CONFIG_VALIDATE ??= "loose";
680
1216
  let { config, pathMap } = await this.loadConfig(options);
681
1217
  config = await this.buildConfig(config, pathMap, options, rspackCommand);
682
1218
  const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
683
1219
  let compiler;
684
1220
  try {
685
- compiler = (0, core_.rspack)(config, isWatch ? callback : void 0);
1221
+ compiler = (0, rspackCore.Z)(config, isWatch ? callback : void 0);
1222
+ if (!isWatch && compiler) compiler.unsafeFastDrop = true;
686
1223
  } catch (e) {
687
- if (e instanceof core_.ValidationError) {
1224
+ if (e instanceof rspackCore.Z.ValidationError) {
688
1225
  this.getLogger().error(e.message);
689
1226
  process.exit(2);
690
1227
  } else if (e instanceof Error) {
@@ -697,11 +1234,9 @@ var __webpack_exports__ = {};
697
1234
  return compiler;
698
1235
  }
699
1236
  createColors(useColor) {
700
- const shouldUseColor = useColor || external_colorette_namespaceObject.isColorSupported;
1237
+ const shouldUseColor = useColor || picocolors.isColorSupported;
701
1238
  return {
702
- ...(0, external_colorette_namespaceObject.createColors)({
703
- useColor: shouldUseColor
704
- }),
1239
+ ...(0, picocolors.createColors)(shouldUseColor),
705
1240
  isColorSupported: shouldUseColor
706
1241
  };
707
1242
  }
@@ -716,13 +1251,8 @@ var __webpack_exports__ = {};
716
1251
  };
717
1252
  }
718
1253
  async run(argv) {
719
- this.program.showHelpOnFail(false);
720
- this.program.usage("[options]");
721
- this.program.scriptName("rspack");
722
- this.program.strictCommands(true).strict(true);
723
- this.program.middleware(normalizeEnv);
724
- this.registerCommands();
725
- await this.program.parseAsync((0, helpers_namespaceObject.hideBin)(argv));
1254
+ await this.registerCommands();
1255
+ this.program.parse(argv);
726
1256
  }
727
1257
  async registerCommands() {
728
1258
  const builtinCommands = [
@@ -730,7 +1260,7 @@ var __webpack_exports__ = {};
730
1260
  new ServeCommand(),
731
1261
  new PreviewCommand()
732
1262
  ];
733
- for (const command of builtinCommands)command.apply(this);
1263
+ for (const command of builtinCommands)await command.apply(this);
734
1264
  }
735
1265
  async buildConfig(item, pathMap, options, command) {
736
1266
  const isBuild = "build" === command;
@@ -763,8 +1293,8 @@ var __webpack_exports__ = {};
763
1293
  if (void 0 === item.devtool) item.devtool = isBuild ? "source-map" : "cheap-module-source-map";
764
1294
  if (void 0 !== options.devtool) item.devtool = options.devtool;
765
1295
  if (isServe) {
766
- const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin);
767
- if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin());
1296
+ const installed = (item.plugins ||= []).find((item)=>item instanceof rspackCore.Z.ProgressPlugin);
1297
+ if (!installed) (item.plugins ??= []).push(new rspackCore.Z.ProgressPlugin());
768
1298
  }
769
1299
  const cacheOptions = item.experiments?.cache;
770
1300
  if ("object" == typeof cacheOptions && "persistent" === cacheOptions.type) {
@@ -800,7 +1330,7 @@ var __webpack_exports__ = {};
800
1330
  };
801
1331
  let { loadedConfig, configPath } = config;
802
1332
  if ("function" == typeof loadedConfig) {
803
- let functionResult = loadedConfig(options.argv?.env, options.argv);
1333
+ let functionResult = loadedConfig(options.env, options);
804
1334
  if ("function" == typeof functionResult.then) functionResult = await functionResult;
805
1335
  loadedConfig = functionResult;
806
1336
  }