@rspack/cli 2.0.0-rc.0 → 2.0.0-rc.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/697.js ADDED
@@ -0,0 +1,1406 @@
1
+ import node_path from "node:path";
2
+ import node_util from "node:util";
3
+ import { rspack } from "@rspack/core";
4
+ import node_fs from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import { pathToFileURL } from "node:url";
7
+ import { createRequire as __rspack_createRequire } from "node:module";
8
+ const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
9
+ var __webpack_modules__ = {};
10
+ var __webpack_module_cache__ = {};
11
+ function __webpack_require__(moduleId) {
12
+ var cachedModule = __webpack_module_cache__[moduleId];
13
+ if (void 0 !== cachedModule) return cachedModule.exports;
14
+ var module = __webpack_module_cache__[moduleId] = {
15
+ exports: {}
16
+ };
17
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
18
+ return module.exports;
19
+ }
20
+ __webpack_require__.m = __webpack_modules__;
21
+ (()=>{
22
+ var getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
23
+ var leafPrototypes;
24
+ __webpack_require__.t = function(value, mode) {
25
+ if (1 & mode) value = this(value);
26
+ if (8 & mode) return value;
27
+ if ('object' == typeof value && value) {
28
+ if (4 & mode && value.__esModule) return value;
29
+ if (16 & mode && 'function' == typeof value.then) return value;
30
+ }
31
+ var ns = Object.create(null);
32
+ __webpack_require__.r(ns);
33
+ var def = {};
34
+ leafPrototypes = leafPrototypes || [
35
+ null,
36
+ getProto({}),
37
+ getProto([]),
38
+ getProto(getProto)
39
+ ];
40
+ for(var current = 2 & mode && value; ('object' == typeof current || 'function' == typeof current) && !~leafPrototypes.indexOf(current); current = getProto(current))Object.getOwnPropertyNames(current).forEach((key)=>{
41
+ def[key] = ()=>value[key];
42
+ });
43
+ def['default'] = ()=>value;
44
+ __webpack_require__.d(ns, def);
45
+ return ns;
46
+ };
47
+ })();
48
+ (()=>{
49
+ __webpack_require__.d = (exports, definition)=>{
50
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
51
+ enumerable: true,
52
+ get: definition[key]
53
+ });
54
+ };
55
+ })();
56
+ (()=>{
57
+ __webpack_require__.add = function(modules) {
58
+ Object.assign(__webpack_require__.m, modules);
59
+ };
60
+ })();
61
+ var __webpack_require__temp = __webpack_require__;
62
+ (()=>{
63
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
64
+ })();
65
+ (()=>{
66
+ __webpack_require__.r = (exports)=>{
67
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
68
+ value: 'Module'
69
+ });
70
+ Object.defineProperty(exports, '__esModule', {
71
+ value: true
72
+ });
73
+ };
74
+ })();
75
+ (()=>{
76
+ __webpack_require__.nmd = (module)=>{
77
+ module.paths = [];
78
+ if (!module.children) module.children = [];
79
+ return module;
80
+ };
81
+ })();
82
+ (()=>{
83
+ var installedChunks = {
84
+ 410: 0,
85
+ 697: 0
86
+ };
87
+ var installChunk = (data)=>{
88
+ var __rspack_esm_ids = data.__rspack_esm_ids;
89
+ var __webpack_modules__ = data.__webpack_modules__;
90
+ var __rspack_esm_runtime = data.__rspack_esm_runtime;
91
+ var moduleId, chunkId, i = 0;
92
+ for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
93
+ if (__rspack_esm_runtime) __rspack_esm_runtime(__webpack_require__);
94
+ for(; i < __rspack_esm_ids.length; i++){
95
+ chunkId = __rspack_esm_ids[i];
96
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
97
+ installedChunks[__rspack_esm_ids[i]] = 0;
98
+ }
99
+ };
100
+ __webpack_require__.C = installChunk;
101
+ })();
102
+ __webpack_require__.add({
103
+ "../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js" (module, exports, __webpack_require__) {
104
+ module = __webpack_require__.nmd(module);
105
+ const BuiltinModule = __webpack_require__("module");
106
+ const path = __webpack_require__("path");
107
+ const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
108
+ const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule;
109
+ 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.";
110
+ function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
111
+ if ('string' != typeof filename) return false;
112
+ if (-1 === exts.indexOf(path.extname(filename))) return false;
113
+ const resolvedFilename = path.resolve(filename);
114
+ if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) return false;
115
+ if (matcher && 'function' == typeof matcher) return !!matcher(resolvedFilename);
116
+ return true;
117
+ }
118
+ function addHook(hook, opts = {}) {
119
+ let reverted = false;
120
+ const loaders = [];
121
+ const oldLoaders = [];
122
+ let exts;
123
+ const originalJSLoader = Module._extensions['.js'];
124
+ const matcher = opts.matcher || null;
125
+ const ignoreNodeModules = false !== opts.ignoreNodeModules;
126
+ exts = opts.extensions || opts.exts || opts.extension || opts.ext || [
127
+ '.js'
128
+ ];
129
+ if (!Array.isArray(exts)) exts = [
130
+ exts
131
+ ];
132
+ exts.forEach((ext)=>{
133
+ if ('string' != typeof ext) throw new TypeError(`Invalid Extension: ${ext}`);
134
+ const oldLoader = Module._extensions[ext] || originalJSLoader;
135
+ oldLoaders[ext] = Module._extensions[ext];
136
+ loaders[ext] = Module._extensions[ext] = function(mod, filename) {
137
+ let compile;
138
+ if (!reverted) {
139
+ if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
140
+ compile = mod._compile;
141
+ mod._compile = function(code) {
142
+ mod._compile = compile;
143
+ const newCode = hook(code, filename);
144
+ if ('string' != typeof newCode) throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
145
+ return mod._compile(newCode, filename);
146
+ };
147
+ }
148
+ }
149
+ oldLoader(mod, filename);
150
+ };
151
+ });
152
+ return function() {
153
+ if (reverted) return;
154
+ reverted = true;
155
+ exts.forEach((ext)=>{
156
+ if (Module._extensions[ext] === loaders[ext]) if (oldLoaders[ext]) Module._extensions[ext] = oldLoaders[ext];
157
+ else delete Module._extensions[ext];
158
+ });
159
+ };
160
+ }
161
+ exports.addHook = addHook;
162
+ },
163
+ module (module) {
164
+ module.exports = __rspack_createRequire_require("module");
165
+ },
166
+ path (module) {
167
+ module.exports = __rspack_createRequire_require("path");
168
+ },
169
+ stream (module) {
170
+ module.exports = __rspack_createRequire_require("stream");
171
+ },
172
+ util (module) {
173
+ module.exports = __rspack_createRequire_require("util");
174
+ }
175
+ });
176
+ function toArr(any) {
177
+ return null == any ? [] : Array.isArray(any) ? any : [
178
+ any
179
+ ];
180
+ }
181
+ function toVal(out, key, val, opts) {
182
+ 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;
183
+ out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
184
+ old,
185
+ nxt
186
+ ];
187
+ }
188
+ function lib_default(args, opts) {
189
+ args = args || [];
190
+ opts = opts || {};
191
+ var k, arr, arg, name, val, out = {
192
+ _: []
193
+ };
194
+ var i = 0, j = 0, idx = 0, len = args.length;
195
+ const alibi = void 0 !== opts.alias;
196
+ const strict = void 0 !== opts.unknown;
197
+ const defaults = void 0 !== opts.default;
198
+ opts.alias = opts.alias || {};
199
+ opts.string = toArr(opts.string);
200
+ opts.boolean = toArr(opts.boolean);
201
+ if (alibi) for(k in opts.alias){
202
+ arr = opts.alias[k] = toArr(opts.alias[k]);
203
+ for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
204
+ }
205
+ for(i = opts.boolean.length; i-- > 0;){
206
+ arr = opts.alias[opts.boolean[i]] || [];
207
+ for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]);
208
+ }
209
+ for(i = opts.string.length; i-- > 0;){
210
+ arr = opts.alias[opts.string[i]] || [];
211
+ for(j = arr.length; j-- > 0;)opts.string.push(arr[j]);
212
+ }
213
+ if (defaults) for(k in opts.default){
214
+ name = typeof opts.default[k];
215
+ arr = opts.alias[k] = opts.alias[k] || [];
216
+ if (void 0 !== opts[name]) {
217
+ opts[name].push(k);
218
+ for(i = 0; i < arr.length; i++)opts[name].push(arr[i]);
219
+ }
220
+ }
221
+ const keys = strict ? Object.keys(opts.alias) : [];
222
+ for(i = 0; i < len; i++){
223
+ arg = args[i];
224
+ if ("--" === arg) {
225
+ out._ = out._.concat(args.slice(++i));
226
+ break;
227
+ }
228
+ for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
229
+ if (0 === j) out._.push(arg);
230
+ else if ("no-" === arg.substring(j, j + 3)) {
231
+ name = arg.substring(j + 3);
232
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
233
+ out[name] = false;
234
+ } else {
235
+ for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
236
+ name = arg.substring(j, idx);
237
+ val = arg.substring(++idx) || i + 1 === len || 45 === ("" + args[i + 1]).charCodeAt(0) || args[++i];
238
+ arr = 2 === j ? [
239
+ name
240
+ ] : name;
241
+ for(idx = 0; idx < arr.length; idx++){
242
+ name = arr[idx];
243
+ if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
244
+ toVal(out, name, idx + 1 < arr.length || val, opts);
245
+ }
246
+ }
247
+ }
248
+ if (defaults) {
249
+ for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k];
250
+ }
251
+ if (alibi) for(k in out){
252
+ arr = opts.alias[k] || [];
253
+ while(arr.length > 0)out[arr.shift()] = out[k];
254
+ }
255
+ return out;
256
+ }
257
+ function removeBrackets(v) {
258
+ return v.replace(/[<[].+/, "").trim();
259
+ }
260
+ function findAllBrackets(v) {
261
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
262
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
263
+ const res = [];
264
+ const parse = (match)=>{
265
+ let variadic = false;
266
+ let value = match[1];
267
+ if (value.startsWith("...")) {
268
+ value = value.slice(3);
269
+ variadic = true;
270
+ }
271
+ return {
272
+ required: match[0].startsWith("<"),
273
+ value,
274
+ variadic
275
+ };
276
+ };
277
+ let angledMatch;
278
+ while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch));
279
+ let squareMatch;
280
+ while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch));
281
+ return res;
282
+ }
283
+ function getMriOptions(options) {
284
+ const result = {
285
+ alias: {},
286
+ boolean: []
287
+ };
288
+ for (const [index, option] of options.entries()){
289
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
290
+ if (option.isBoolean) if (option.negated) {
291
+ if (!options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required)) result.boolean.push(option.names[0]);
292
+ } else result.boolean.push(option.names[0]);
293
+ }
294
+ return result;
295
+ }
296
+ function findLongest(arr) {
297
+ return arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
298
+ }
299
+ function padRight(str, length) {
300
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
301
+ }
302
+ function camelcase(input) {
303
+ return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
304
+ }
305
+ function setDotProp(obj, keys, val) {
306
+ let current = obj;
307
+ for(let i = 0; i < keys.length; i++){
308
+ const key = keys[i];
309
+ if (i === keys.length - 1) {
310
+ current[key] = val;
311
+ return;
312
+ }
313
+ if (null == current[key]) {
314
+ const nextKeyIsArrayIndex = +keys[i + 1] > -1;
315
+ current[key] = nextKeyIsArrayIndex ? [] : {};
316
+ }
317
+ current = current[key];
318
+ }
319
+ }
320
+ function setByType(obj, transforms) {
321
+ for (const key of Object.keys(transforms)){
322
+ const transform = transforms[key];
323
+ if (transform.shouldTransform) {
324
+ obj[key] = [
325
+ obj[key]
326
+ ].flat();
327
+ if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction);
328
+ }
329
+ }
330
+ }
331
+ function getFileName(input) {
332
+ const m = /([^\\/]+)$/.exec(input);
333
+ return m ? m[1] : "";
334
+ }
335
+ function camelcaseOptionName(name) {
336
+ return name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join(".");
337
+ }
338
+ var CACError = class extends Error {
339
+ constructor(message){
340
+ super(message);
341
+ this.name = "CACError";
342
+ if ("function" != typeof Error.captureStackTrace) this.stack = new Error(message).stack;
343
+ }
344
+ };
345
+ var Option = class {
346
+ rawName;
347
+ description;
348
+ name;
349
+ names;
350
+ isBoolean;
351
+ required;
352
+ config;
353
+ negated;
354
+ constructor(rawName, description, config){
355
+ this.rawName = rawName;
356
+ this.description = description;
357
+ this.config = Object.assign({}, config);
358
+ rawName = rawName.replaceAll(".*", "");
359
+ this.negated = false;
360
+ this.names = removeBrackets(rawName).split(",").map((v)=>{
361
+ let name = v.trim().replace(/^-{1,2}/, "");
362
+ if (name.startsWith("no-")) {
363
+ this.negated = true;
364
+ name = name.replace(/^no-/, "");
365
+ }
366
+ return camelcaseOptionName(name);
367
+ }).sort((a, b)=>a.length > b.length ? 1 : -1);
368
+ this.name = this.names.at(-1);
369
+ if (this.negated && null == this.config.default) this.config.default = true;
370
+ if (rawName.includes("<")) this.required = true;
371
+ else if (rawName.includes("[")) this.required = false;
372
+ else this.isBoolean = true;
373
+ }
374
+ };
375
+ let runtimeProcessArgs;
376
+ let runtimeInfo;
377
+ if ("u" > typeof process) {
378
+ let runtimeName;
379
+ runtimeName = "u" > typeof Deno && "string" == typeof Deno.version?.deno ? "deno" : "u" > typeof Bun && "string" == typeof Bun.version ? "bun" : "node";
380
+ runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
381
+ runtimeProcessArgs = process.argv;
382
+ } else runtimeInfo = "u" < typeof navigator ? "unknown" : `${navigator.platform} ${navigator.userAgent}`;
383
+ var Command = class {
384
+ rawName;
385
+ description;
386
+ config;
387
+ cli;
388
+ options;
389
+ aliasNames;
390
+ name;
391
+ args;
392
+ commandAction;
393
+ usageText;
394
+ versionNumber;
395
+ examples;
396
+ helpCallback;
397
+ globalCommand;
398
+ constructor(rawName, description, config = {}, cli){
399
+ this.rawName = rawName;
400
+ this.description = description;
401
+ this.config = config;
402
+ this.cli = cli;
403
+ this.options = [];
404
+ this.aliasNames = [];
405
+ this.name = removeBrackets(rawName);
406
+ this.args = findAllBrackets(rawName);
407
+ this.examples = [];
408
+ }
409
+ usage(text) {
410
+ this.usageText = text;
411
+ return this;
412
+ }
413
+ allowUnknownOptions() {
414
+ this.config.allowUnknownOptions = true;
415
+ return this;
416
+ }
417
+ ignoreOptionDefaultValue() {
418
+ this.config.ignoreOptionDefaultValue = true;
419
+ return this;
420
+ }
421
+ version(version, customFlags = "-v, --version") {
422
+ this.versionNumber = version;
423
+ this.option(customFlags, "Display version number");
424
+ return this;
425
+ }
426
+ example(example) {
427
+ this.examples.push(example);
428
+ return this;
429
+ }
430
+ option(rawName, description, config) {
431
+ const option = new Option(rawName, description, config);
432
+ this.options.push(option);
433
+ return this;
434
+ }
435
+ alias(name) {
436
+ this.aliasNames.push(name);
437
+ return this;
438
+ }
439
+ action(callback) {
440
+ this.commandAction = callback;
441
+ return this;
442
+ }
443
+ isMatched(name) {
444
+ return this.name === name || this.aliasNames.includes(name);
445
+ }
446
+ get isDefaultCommand() {
447
+ return "" === this.name || this.aliasNames.includes("!");
448
+ }
449
+ get isGlobalCommand() {
450
+ return this instanceof GlobalCommand;
451
+ }
452
+ hasOption(name) {
453
+ name = name.split(".")[0];
454
+ return this.options.find((option)=>option.names.includes(name));
455
+ }
456
+ outputHelp() {
457
+ const { name, commands } = this.cli;
458
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
459
+ let sections = [
460
+ {
461
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
462
+ }
463
+ ];
464
+ sections.push({
465
+ title: "Usage",
466
+ body: ` $ ${name} ${this.usageText || this.rawName}`
467
+ });
468
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
469
+ const longestCommandName = findLongest(commands.map((command)=>command.rawName));
470
+ sections.push({
471
+ title: "Commands",
472
+ body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
473
+ }, {
474
+ title: "For more info, run any command with the `--help` flag",
475
+ body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
476
+ });
477
+ }
478
+ let options = this.isGlobalCommand ? globalOptions : [
479
+ ...this.options,
480
+ ...globalOptions || []
481
+ ];
482
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name);
483
+ if (options.length > 0) {
484
+ const longestOptionName = findLongest(options.map((option)=>option.rawName));
485
+ sections.push({
486
+ title: "Options",
487
+ body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
488
+ });
489
+ }
490
+ if (this.examples.length > 0) sections.push({
491
+ title: "Examples",
492
+ body: this.examples.map((example)=>{
493
+ if ("function" == typeof example) return example(name);
494
+ return example;
495
+ }).join("\n")
496
+ });
497
+ if (helpCallback) sections = helpCallback(sections) || sections;
498
+ console.info(sections.map((section)=>section.title ? `${section.title}:\n${section.body}` : section.body).join("\n\n"));
499
+ }
500
+ outputVersion() {
501
+ const { name } = this.cli;
502
+ const { versionNumber } = this.cli.globalCommand;
503
+ if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
504
+ }
505
+ checkRequiredArgs() {
506
+ const minimalArgsCount = this.args.filter((arg)=>arg.required).length;
507
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
508
+ }
509
+ checkUnknownOptions() {
510
+ const { options, globalCommand } = this.cli;
511
+ if (!this.config.allowUnknownOptions) {
512
+ 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}`}\``);
513
+ }
514
+ }
515
+ checkOptionValue() {
516
+ const { options: parsedOptions, globalCommand } = this.cli;
517
+ const options = [
518
+ ...globalCommand.options,
519
+ ...this.options
520
+ ];
521
+ for (const option of options){
522
+ const value = parsedOptions[option.name.split(".")[0]];
523
+ if (option.required) {
524
+ const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
525
+ if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
526
+ }
527
+ }
528
+ }
529
+ checkUnusedArgs() {
530
+ const maximumArgsCount = this.args.some((arg)=>arg.variadic) ? 1 / 0 : this.args.length;
531
+ if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg)=>`\`${arg}\``).join(", ")}`);
532
+ }
533
+ };
534
+ var GlobalCommand = class extends Command {
535
+ constructor(cli){
536
+ super("@@global@@", "", {}, cli);
537
+ }
538
+ };
539
+ var CAC = class extends EventTarget {
540
+ name;
541
+ commands;
542
+ globalCommand;
543
+ matchedCommand;
544
+ matchedCommandName;
545
+ rawArgs;
546
+ args;
547
+ options;
548
+ showHelpOnExit;
549
+ showVersionOnExit;
550
+ constructor(name = ""){
551
+ super();
552
+ this.name = name;
553
+ this.commands = [];
554
+ this.rawArgs = [];
555
+ this.args = [];
556
+ this.options = {};
557
+ this.globalCommand = new GlobalCommand(this);
558
+ this.globalCommand.usage("<command> [options]");
559
+ }
560
+ usage(text) {
561
+ this.globalCommand.usage(text);
562
+ return this;
563
+ }
564
+ command(rawName, description, config) {
565
+ const command = new Command(rawName, description || "", config, this);
566
+ command.globalCommand = this.globalCommand;
567
+ this.commands.push(command);
568
+ return command;
569
+ }
570
+ option(rawName, description, config) {
571
+ this.globalCommand.option(rawName, description, config);
572
+ return this;
573
+ }
574
+ help(callback) {
575
+ this.globalCommand.option("-h, --help", "Display this message");
576
+ this.globalCommand.helpCallback = callback;
577
+ this.showHelpOnExit = true;
578
+ return this;
579
+ }
580
+ version(version, customFlags = "-v, --version") {
581
+ this.globalCommand.version(version, customFlags);
582
+ this.showVersionOnExit = true;
583
+ return this;
584
+ }
585
+ example(example) {
586
+ this.globalCommand.example(example);
587
+ return this;
588
+ }
589
+ outputHelp() {
590
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
591
+ else this.globalCommand.outputHelp();
592
+ }
593
+ outputVersion() {
594
+ this.globalCommand.outputVersion();
595
+ }
596
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
597
+ this.args = args;
598
+ this.options = options;
599
+ if (matchedCommand) this.matchedCommand = matchedCommand;
600
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
601
+ return this;
602
+ }
603
+ unsetMatchedCommand() {
604
+ this.matchedCommand = void 0;
605
+ this.matchedCommandName = void 0;
606
+ }
607
+ parse(argv, { run = true } = {}) {
608
+ if (!argv) {
609
+ if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
610
+ argv = runtimeProcessArgs;
611
+ }
612
+ this.rawArgs = argv;
613
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
614
+ let shouldParse = true;
615
+ for (const command of this.commands){
616
+ const parsed = this.mri(argv.slice(2), command);
617
+ const commandName = parsed.args[0];
618
+ if (command.isMatched(commandName)) {
619
+ shouldParse = false;
620
+ const parsedInfo = {
621
+ ...parsed,
622
+ args: parsed.args.slice(1)
623
+ };
624
+ this.setParsedInfo(parsedInfo, command, commandName);
625
+ this.dispatchEvent(new CustomEvent(`command:${commandName}`, {
626
+ detail: command
627
+ }));
628
+ }
629
+ }
630
+ if (shouldParse) {
631
+ for (const command of this.commands)if (command.isDefaultCommand) {
632
+ shouldParse = false;
633
+ const parsed = this.mri(argv.slice(2), command);
634
+ this.setParsedInfo(parsed, command);
635
+ this.dispatchEvent(new CustomEvent("command:!", {
636
+ detail: command
637
+ }));
638
+ }
639
+ }
640
+ if (shouldParse) {
641
+ const parsed = this.mri(argv.slice(2));
642
+ this.setParsedInfo(parsed);
643
+ }
644
+ if (this.options.help && this.showHelpOnExit) {
645
+ this.outputHelp();
646
+ run = false;
647
+ this.unsetMatchedCommand();
648
+ }
649
+ if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) {
650
+ this.outputVersion();
651
+ run = false;
652
+ this.unsetMatchedCommand();
653
+ }
654
+ const parsedArgv = {
655
+ args: this.args,
656
+ options: this.options
657
+ };
658
+ if (run) this.runMatchedCommand();
659
+ if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", {
660
+ detail: this.args[0]
661
+ }));
662
+ return parsedArgv;
663
+ }
664
+ mri(argv, command) {
665
+ const cliOptions = [
666
+ ...this.globalCommand.options,
667
+ ...command ? command.options : []
668
+ ];
669
+ const mriOptions = getMriOptions(cliOptions);
670
+ let argsAfterDoubleDashes = [];
671
+ const doubleDashesIndex = argv.indexOf("--");
672
+ if (-1 !== doubleDashesIndex) {
673
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
674
+ argv = argv.slice(0, doubleDashesIndex);
675
+ }
676
+ let parsed = lib_default(argv, mriOptions);
677
+ parsed = Object.keys(parsed).reduce((res, name)=>({
678
+ ...res,
679
+ [camelcaseOptionName(name)]: parsed[name]
680
+ }), {
681
+ _: []
682
+ });
683
+ const args = parsed._;
684
+ const options = {
685
+ "--": argsAfterDoubleDashes
686
+ };
687
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
688
+ const transforms = Object.create(null);
689
+ for (const cliOption of cliOptions){
690
+ if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default;
691
+ if (Array.isArray(cliOption.config.type) && void 0 === transforms[cliOption.name]) {
692
+ transforms[cliOption.name] = Object.create(null);
693
+ transforms[cliOption.name].shouldTransform = true;
694
+ transforms[cliOption.name].transformFunction = cliOption.config.type[0];
695
+ }
696
+ }
697
+ for (const key of Object.keys(parsed))if ("_" !== key) {
698
+ setDotProp(options, key.split("."), parsed[key]);
699
+ setByType(options, transforms);
700
+ }
701
+ return {
702
+ args,
703
+ options
704
+ };
705
+ }
706
+ runMatchedCommand() {
707
+ const { args, options, matchedCommand: command } = this;
708
+ if (!command || !command.commandAction) return;
709
+ command.checkUnknownOptions();
710
+ command.checkOptionValue();
711
+ command.checkRequiredArgs();
712
+ command.checkUnusedArgs();
713
+ const actionArgs = [];
714
+ command.args.forEach((arg, index)=>{
715
+ if (arg.variadic) actionArgs.push(args.slice(index));
716
+ else actionArgs.push(args[index]);
717
+ });
718
+ actionArgs.push(options);
719
+ return command.commandAction.apply(this, actionArgs);
720
+ }
721
+ };
722
+ const cac = (name = "")=>new CAC(name);
723
+ const commonOptions = (command)=>command.option('-c, --config <path>', 'config file').option('--config-name <name>', 'Name(s) of the configuration to use.', {
724
+ type: [
725
+ String
726
+ ],
727
+ default: []
728
+ }).option('--config-loader <loader>', 'Specify the loader to load the config file, can be `native` or `register`.', {
729
+ default: 'register'
730
+ }).option('--env <env>', 'env passed to config function', {
731
+ type: [
732
+ String
733
+ ],
734
+ default: []
735
+ }).option('--node-env <value>', 'sets `process.env.NODE_ENV` to be specified value');
736
+ function normalizeDevtoolOption(value) {
737
+ if ('string' == typeof value) {
738
+ const trimmed = value.trim();
739
+ if ('' === trimmed || 'false' === trimmed) return false;
740
+ if ('true' === trimmed) return 'source-map';
741
+ return trimmed;
742
+ }
743
+ if ('boolean' == typeof value) return value ? 'source-map' : false;
744
+ }
745
+ const normalizeCommonOptions = (options, action)=>{
746
+ const isEmptyArray = (arr)=>Array.isArray(arr) && 0 === arr.length;
747
+ for (const key of [
748
+ 'entry',
749
+ 'configName'
750
+ ]){
751
+ const val = options[key];
752
+ if (isEmptyArray(val)) options[key] = void 0;
753
+ }
754
+ const env = Array.isArray(options.env) ? normalizeEnvToObject(options) : {};
755
+ options.env = env;
756
+ if ('serve' === action) setBuiltinEnvArg(env, 'SERVE', true);
757
+ else if ('build' === action) if (options.watch) setBuiltinEnvArg(env, 'WATCH', true);
758
+ else {
759
+ setBuiltinEnvArg(env, 'BUNDLE', true);
760
+ setBuiltinEnvArg(env, 'BUILD', true);
761
+ }
762
+ if ('devtool' in options) options.devtool = normalizeDevtoolOption(options.devtool);
763
+ };
764
+ const commonOptionsForBuildAndServe = (command)=>command.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', {
765
+ type: [
766
+ String
767
+ ],
768
+ default: []
769
+ }).option('-m, --mode <mode>', 'mode').option('-o, --output-path <dir>', 'output path dir').option('-w, --watch', 'watch');
770
+ function setBuiltinEnvArg(env, envNameSuffix, value) {
771
+ const envName = `RSPACK_${envNameSuffix}`;
772
+ if (!(envName in env)) env[envName] = value;
773
+ }
774
+ function normalizeEnvToObject(options) {
775
+ function parseValue(previous, value) {
776
+ const [allKeys, val] = value.split(/=(.+)/, 2);
777
+ const splitKeys = allKeys.split(/\.(?!$)/);
778
+ let prevRef = previous;
779
+ splitKeys.forEach((key, index)=>{
780
+ let someKey = key;
781
+ if (someKey.endsWith('=')) {
782
+ someKey = someKey.slice(0, -1);
783
+ prevRef[someKey] = void 0;
784
+ return;
785
+ }
786
+ if (!prevRef[someKey] || 'string' == typeof prevRef[someKey]) prevRef[someKey] = {};
787
+ if (index === splitKeys.length - 1) if ('string' == typeof val) prevRef[someKey] = val;
788
+ else prevRef[someKey] = true;
789
+ prevRef = prevRef[someKey];
790
+ });
791
+ return previous;
792
+ }
793
+ return (options.env ?? []).reduce(parseValue, {});
794
+ }
795
+ function setDefaultNodeEnv(options, defaultEnv) {
796
+ if (void 0 === process.env.NODE_ENV) process.env.NODE_ENV = 'string' == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
797
+ }
798
+ async function runBuild(cli, options) {
799
+ setDefaultNodeEnv(options, 'production');
800
+ normalizeCommonOptions(options, 'build');
801
+ const logger = cli.getLogger();
802
+ let createJsonStringifyStream;
803
+ if (options.json) {
804
+ const jsonExt = await import("./json-ext.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/@discoveryjs+json-ext@0.5.7/node_modules/@discoveryjs/json-ext/src/index.js", 23));
805
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
806
+ }
807
+ const errorHandler = (error, stats)=>{
808
+ if (error) {
809
+ logger.error(error);
810
+ process.exit(2);
811
+ }
812
+ if (stats?.hasErrors()) process.exitCode = 1;
813
+ if (!compiler || !stats) return;
814
+ const getStatsOptions = ()=>{
815
+ if (cli.isMultipleCompiler(compiler)) return {
816
+ children: compiler.compilers.map((item)=>item.options ? item.options.stats : void 0)
817
+ };
818
+ return compiler.options?.stats;
819
+ };
820
+ const statsOptions = getStatsOptions();
821
+ if (options.json && createJsonStringifyStream) {
822
+ const handleWriteError = (error)=>{
823
+ logger.error(error);
824
+ process.exit(2);
825
+ };
826
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on('error', handleWriteError).pipe(process.stdout).on('error', handleWriteError).on('close', ()=>process.stdout.write('\n'));
827
+ else if ('string' == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on('error', handleWriteError).pipe(node_fs.createWriteStream(options.json)).on('error', handleWriteError).on('close', ()=>{
828
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
829
+ });
830
+ } else {
831
+ const printedStats = stats.toString(statsOptions);
832
+ if (printedStats) logger.raw(printedStats);
833
+ }
834
+ };
835
+ const userOption = await cli.buildCompilerConfig(options, 'build');
836
+ const compiler = await cli.createCompiler(userOption, errorHandler);
837
+ if (!compiler || cli.isWatch(compiler)) return;
838
+ compiler.run((error, stats)=>{
839
+ compiler.close((closeErr)=>{
840
+ if (closeErr) logger.error(closeErr);
841
+ errorHandler(error, stats);
842
+ });
843
+ });
844
+ }
845
+ class BuildCommand {
846
+ async apply(cli) {
847
+ const command = cli.program.command('', 'run the Rspack build').alias('build').alias('bundle').alias('b');
848
+ commonOptionsForBuildAndServe(commonOptions(command)).option('--json [path]', 'emit stats json');
849
+ command.action(cli.wrapAction(async (options)=>{
850
+ await runBuild(cli, options);
851
+ }));
852
+ }
853
+ }
854
+ class PreviewCommand {
855
+ async apply(cli) {
856
+ const command = cli.program.command('preview [dir]', 'run the Rspack server for build output').alias('p');
857
+ 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.');
858
+ command.action(cli.wrapAction(async (dir, options)=>{
859
+ setDefaultNodeEnv(options, 'production');
860
+ normalizeCommonOptions(options, 'preview');
861
+ let RspackDevServer;
862
+ try {
863
+ const devServerModule = await import("@rspack/dev-server");
864
+ RspackDevServer = devServerModule.RspackDevServer;
865
+ } catch (error) {
866
+ const logger = cli.getLogger();
867
+ if (error?.code === 'MODULE_NOT_FOUND' || error?.code === 'ERR_MODULE_NOT_FOUND') logger.error('The "@rspack/dev-server" package is required to use the preview command.\nPlease install it by running:\n pnpm add -D @rspack/dev-server\n or\n npm install -D @rspack/dev-server');
868
+ else logger.error('Failed to load "@rspack/dev-server":\n' + (error?.message || String(error)));
869
+ process.exit(1);
870
+ }
871
+ let { config } = await cli.loadConfig(options);
872
+ config = await getPreviewConfig(config, options, dir);
873
+ if (!Array.isArray(config)) config = [
874
+ config
875
+ ];
876
+ const singleConfig = config.find((item)=>item.devServer) || config[0];
877
+ const devServerOptions = singleConfig.devServer;
878
+ try {
879
+ const compiler = rspack({
880
+ entry: {}
881
+ });
882
+ if (!compiler) return;
883
+ const server = new RspackDevServer(devServerOptions, compiler);
884
+ await server.start();
885
+ } catch (error) {
886
+ const logger = cli.getLogger();
887
+ logger.error(error);
888
+ process.exit(2);
889
+ }
890
+ }));
891
+ }
892
+ }
893
+ async function getPreviewConfig(item, options, dir) {
894
+ const DEFAULT_ROOT = 'dist';
895
+ const internalPreviewConfig = async (item)=>{
896
+ const devServer = false === item.devServer ? void 0 : item.devServer;
897
+ item.devServer = {
898
+ static: {
899
+ directory: dir ? node_path.join(item.context ?? process.cwd(), dir) : item.output?.path ?? node_path.join(item.context ?? process.cwd(), DEFAULT_ROOT),
900
+ publicPath: options.publicPath ?? '/'
901
+ },
902
+ port: options.port ?? 8080,
903
+ proxy: devServer?.proxy,
904
+ host: options.host ?? devServer?.host,
905
+ open: options.open ?? devServer?.open,
906
+ server: options.server ?? devServer?.server,
907
+ historyApiFallback: devServer?.historyApiFallback
908
+ };
909
+ return item;
910
+ };
911
+ if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
912
+ return internalPreviewConfig(item);
913
+ }
914
+ function normalizeHotOption(value) {
915
+ if ('false' === value) return false;
916
+ if ('true' === value) return true;
917
+ return value;
918
+ }
919
+ class ServeCommand {
920
+ async apply(cli) {
921
+ const command = cli.program.command('serve', 'run the rspack dev server.').alias('server').alias('s').alias('dev');
922
+ 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');
923
+ command.action(cli.wrapAction(async (cliOptions)=>{
924
+ setDefaultNodeEnv(cliOptions, 'development');
925
+ normalizeCommonOptions(cliOptions, 'serve');
926
+ cliOptions.hot = normalizeHotOption(cliOptions.hot);
927
+ let RspackDevServer;
928
+ try {
929
+ const devServerModule = await import("@rspack/dev-server");
930
+ RspackDevServer = devServerModule.RspackDevServer;
931
+ } catch (error) {
932
+ const logger = cli.getLogger();
933
+ if (error?.code === 'MODULE_NOT_FOUND' || error?.code === 'ERR_MODULE_NOT_FOUND') logger.error('The "@rspack/dev-server" package is required to use the serve command.\nPlease install it by running:\n pnpm add -D @rspack/dev-server\n or\n npm install -D @rspack/dev-server');
934
+ else logger.error('Failed to load "@rspack/dev-server":\n' + (error?.message || String(error)));
935
+ process.exit(1);
936
+ }
937
+ const userConfig = await cli.buildCompilerConfig(cliOptions, 'serve');
938
+ const compiler = await cli.createCompiler(userConfig);
939
+ if (!compiler) return;
940
+ const isMultiCompiler = cli.isMultipleCompiler(compiler);
941
+ const compilers = isMultiCompiler ? compiler.compilers : [
942
+ compiler
943
+ ];
944
+ const userConfigs = isMultiCompiler ? userConfig : [
945
+ userConfig
946
+ ];
947
+ const possibleCompilers = compilers.filter((compiler)=>compiler.options.devServer);
948
+ const usedPorts = [];
949
+ const servers = [];
950
+ const compilerForDevServer = possibleCompilers.length > 0 ? possibleCompilers[0] : compilers[0];
951
+ for (const [index, compiler] of compilers.entries()){
952
+ const userConfig = userConfigs[index];
953
+ const existingDevServer = compiler.options.devServer;
954
+ if (false === existingDevServer) continue;
955
+ const devServer = existingDevServer ?? (compiler.options.devServer = {});
956
+ const isWebAppOnly = compiler.platform.web && !compiler.platform.node && !compiler.platform.nwjs && !compiler.platform.electron && !compiler.platform.webworker;
957
+ if (isWebAppOnly && void 0 === userConfig.lazyCompilation) compiler.options.lazyCompilation = {
958
+ imports: true,
959
+ entries: false
960
+ };
961
+ devServer.hot = cliOptions.hot ?? devServer.hot ?? true;
962
+ if (false !== devServer.client) {
963
+ if (true === devServer.client || null == devServer.client) devServer.client = {};
964
+ devServer.client = {
965
+ overlay: {
966
+ errors: true,
967
+ warnings: false
968
+ },
969
+ ...devServer.client
970
+ };
971
+ }
972
+ }
973
+ const compilerForDevServerOptions = compilerForDevServer.options.devServer;
974
+ const devServerOptions = false === compilerForDevServerOptions ? {} : compilerForDevServerOptions ?? (compilerForDevServer.options.devServer = {});
975
+ const { setupMiddlewares } = devServerOptions;
976
+ const lazyCompileMiddleware = rspack.lazyCompilationMiddleware(compiler);
977
+ devServerOptions.setupMiddlewares = (middlewares, server)=>{
978
+ let finalMiddlewares = middlewares;
979
+ if (setupMiddlewares) finalMiddlewares = setupMiddlewares(finalMiddlewares, server);
980
+ return [
981
+ ...finalMiddlewares,
982
+ lazyCompileMiddleware
983
+ ];
984
+ };
985
+ devServerOptions.hot = cliOptions.hot ?? devServerOptions.hot ?? true;
986
+ devServerOptions.host = cliOptions.host || devServerOptions.host;
987
+ devServerOptions.port = cliOptions.port ?? devServerOptions.port;
988
+ if (false !== devServerOptions.client) {
989
+ if (true === devServerOptions.client || null == devServerOptions.client) devServerOptions.client = {};
990
+ devServerOptions.client = {
991
+ overlay: {
992
+ errors: true,
993
+ warnings: false
994
+ },
995
+ ...devServerOptions.client
996
+ };
997
+ }
998
+ if (devServerOptions.port) {
999
+ const portNumber = Number(devServerOptions.port);
1000
+ if (!Number.isNaN(portNumber)) {
1001
+ 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.');
1002
+ usedPorts.push(portNumber);
1003
+ }
1004
+ }
1005
+ try {
1006
+ const server = new RspackDevServer(devServerOptions, compiler);
1007
+ await server.start();
1008
+ servers.push(server);
1009
+ } catch (error) {
1010
+ const logger = cli.getLogger();
1011
+ logger.error(error);
1012
+ process.exit(2);
1013
+ }
1014
+ }));
1015
+ }
1016
+ }
1017
+ const readPackageUp = (cwd = process.cwd())=>{
1018
+ let currentDir = node_path.resolve(cwd);
1019
+ let packageJsonPath = node_path.join(currentDir, 'package.json');
1020
+ while(!node_fs.existsSync(packageJsonPath)){
1021
+ const parentDir = node_path.dirname(currentDir);
1022
+ if (parentDir === currentDir) return null;
1023
+ currentDir = parentDir;
1024
+ packageJsonPath = node_path.join(currentDir, 'package.json');
1025
+ }
1026
+ try {
1027
+ return JSON.parse(node_fs.readFileSync(packageJsonPath, 'utf8'));
1028
+ } catch {
1029
+ return null;
1030
+ }
1031
+ };
1032
+ const utils_readPackageUp = readPackageUp;
1033
+ const isEsmFile = (filePath)=>{
1034
+ if (/\.(mjs|mts)$/.test(filePath)) return true;
1035
+ if (/\.(cjs|cts)$/.test(filePath)) return false;
1036
+ const packageJson = utils_readPackageUp(node_path.dirname(filePath));
1037
+ return packageJson?.type === 'module';
1038
+ };
1039
+ const crossImport_require = createRequire(import.meta.url);
1040
+ const crossImport = async (path)=>{
1041
+ if (isEsmFile(path)) {
1042
+ const url = pathToFileURL(path).href;
1043
+ const { default: config } = await import(url);
1044
+ return config;
1045
+ }
1046
+ let result = crossImport_require(path);
1047
+ if (result && 'object' == typeof result && 'default' in result) result = result.default || {};
1048
+ return result;
1049
+ };
1050
+ const DEFAULT_EXTENSIONS = [
1051
+ '.js',
1052
+ '.ts',
1053
+ '.mjs',
1054
+ '.mts',
1055
+ '.cjs',
1056
+ '.cts'
1057
+ ];
1058
+ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(node_fs.existsSync);
1059
+ const utils_findConfig = findConfig;
1060
+ const TS_EXTENSION = [
1061
+ '.ts',
1062
+ '.cts',
1063
+ '.mts'
1064
+ ];
1065
+ const isTsFile = (configPath)=>{
1066
+ const ext = node_path.extname(configPath);
1067
+ return TS_EXTENSION.includes(ext);
1068
+ };
1069
+ const utils_isTsFile = isTsFile;
1070
+ const lib = __webpack_require__("../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js");
1071
+ const loadConfig_require = createRequire(import.meta.url);
1072
+ const injectInlineSourceMap = ({ code, map })=>{
1073
+ if (map) {
1074
+ const base64Map = Buffer.from(map, 'utf8').toString('base64');
1075
+ const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
1076
+ return `${code}\n${sourceMapContent}`;
1077
+ }
1078
+ return code;
1079
+ };
1080
+ function compile(sourcecode, filename) {
1081
+ const { code, map } = rspack.experiments.swc.transformSync(sourcecode, {
1082
+ jsc: {
1083
+ parser: {
1084
+ syntax: "typescript",
1085
+ tsx: false,
1086
+ decorators: true,
1087
+ dynamicImport: true
1088
+ }
1089
+ },
1090
+ filename: filename,
1091
+ module: {
1092
+ type: 'commonjs'
1093
+ },
1094
+ sourceMaps: true,
1095
+ isModule: true
1096
+ });
1097
+ return injectInlineSourceMap({
1098
+ code,
1099
+ map
1100
+ });
1101
+ }
1102
+ const loadConfig_DEFAULT_CONFIG_NAME = 'rspack.config';
1103
+ const registerLoader = (configPath)=>{
1104
+ if (isEsmFile(configPath) && utils_isTsFile(configPath)) return;
1105
+ if (!utils_isTsFile(configPath)) throw new Error(`config file "${configPath}" is not supported.`);
1106
+ (0, lib.addHook)((code, filename)=>{
1107
+ try {
1108
+ return compile(code, filename);
1109
+ } catch (err) {
1110
+ throw new Error(`Failed to transform file "${filename}" when loading TypeScript config file:\n ${err instanceof Error ? err.message : String(err)}`);
1111
+ }
1112
+ }, {
1113
+ exts: TS_EXTENSION
1114
+ });
1115
+ };
1116
+ const checkIsMultiRspackOptions = (config)=>Array.isArray(config);
1117
+ async function loadExtendedConfig(config, configPath, cwd, options) {
1118
+ if (checkIsMultiRspackOptions(config)) {
1119
+ const resultPathMap = new WeakMap();
1120
+ const extendedConfigs = await Promise.all(config.map(async (item)=>{
1121
+ const { config, pathMap } = await loadExtendedConfig(item, configPath, cwd, options);
1122
+ resultPathMap.set(config, pathMap.get(config));
1123
+ return config;
1124
+ }));
1125
+ extendedConfigs.parallelism = config.parallelism;
1126
+ return {
1127
+ config: extendedConfigs,
1128
+ pathMap: resultPathMap
1129
+ };
1130
+ }
1131
+ const pathMap = new WeakMap();
1132
+ pathMap.set(config, [
1133
+ configPath
1134
+ ]);
1135
+ if (!('extends' in config) || !config.extends) return {
1136
+ config,
1137
+ pathMap
1138
+ };
1139
+ const extendsList = Array.isArray(config.extends) ? config.extends : [
1140
+ config.extends
1141
+ ];
1142
+ const { extends: _, ...configWithoutExtends } = config;
1143
+ const baseDir = node_path.dirname(configPath);
1144
+ let resultConfig = configWithoutExtends;
1145
+ pathMap.set(resultConfig, [
1146
+ configPath
1147
+ ]);
1148
+ for (const extendPath of extendsList){
1149
+ let resolvedPath;
1150
+ if (extendPath.startsWith('.') || extendPath.startsWith('/') || extendPath.includes(':\\')) {
1151
+ resolvedPath = node_path.resolve(baseDir, extendPath);
1152
+ if (!node_path.extname(resolvedPath)) {
1153
+ const foundConfig = utils_findConfig(resolvedPath);
1154
+ if (foundConfig) resolvedPath = foundConfig;
1155
+ else throw new Error(`Extended configuration file "${resolvedPath}" not found.`);
1156
+ }
1157
+ } else try {
1158
+ resolvedPath = loadConfig_require.resolve(extendPath, {
1159
+ paths: [
1160
+ baseDir,
1161
+ cwd
1162
+ ]
1163
+ });
1164
+ } catch {
1165
+ throw new Error(`Cannot find module '${extendPath}' to extend from.`);
1166
+ }
1167
+ if (!node_fs.existsSync(resolvedPath)) throw new Error(`Extended configuration file "${resolvedPath}" not found.`);
1168
+ if (utils_isTsFile(resolvedPath) && 'register' === options.configLoader) registerLoader(resolvedPath);
1169
+ let loadedConfig = await crossImport(resolvedPath);
1170
+ if ('function' == typeof loadedConfig) {
1171
+ loadedConfig = loadedConfig(options.env, options);
1172
+ if ('function' == typeof loadedConfig.then) loadedConfig = await loadedConfig;
1173
+ }
1174
+ const { config: extendedConfig, pathMap: extendedPathMap } = await loadExtendedConfig(loadedConfig, resolvedPath, cwd, options);
1175
+ const configPaths = [
1176
+ ...pathMap.get(resultConfig) || [],
1177
+ ...extendedPathMap.get(extendedConfig) || []
1178
+ ];
1179
+ resultConfig = rspack.util.cleverMerge(extendedConfig, resultConfig);
1180
+ pathMap.set(resultConfig, configPaths);
1181
+ }
1182
+ return {
1183
+ config: resultConfig,
1184
+ pathMap
1185
+ };
1186
+ }
1187
+ async function loadRspackConfig(options, cwd = process.cwd()) {
1188
+ let configPath = '';
1189
+ if (options.config) {
1190
+ configPath = node_path.resolve(cwd, options.config);
1191
+ if (!node_fs.existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`);
1192
+ } else {
1193
+ const defaultConfig = utils_findConfig(node_path.resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME));
1194
+ if (!defaultConfig) return null;
1195
+ configPath = defaultConfig;
1196
+ }
1197
+ if (utils_isTsFile(configPath) && 'register' === options.configLoader) registerLoader(configPath);
1198
+ const loadedConfig = await crossImport(configPath);
1199
+ return {
1200
+ loadedConfig,
1201
+ configPath
1202
+ };
1203
+ }
1204
+ function isEnvColorSupported() {
1205
+ if ("u" < typeof process) return false;
1206
+ const p = process;
1207
+ const argv = p.argv ?? [];
1208
+ const env = p.env ?? {};
1209
+ return !('NO_COLOR' in env || argv.includes('--no-color')) && ('FORCE_COLOR' in env || argv.includes('--color') || 'win32' === p.platform || p.stdout?.isTTY && 'dumb' !== env.TERM || 'CI' in env);
1210
+ }
1211
+ function createAnsiFormatter(open, close, replace = open) {
1212
+ const closeLength = close.length;
1213
+ return (input)=>{
1214
+ const string = String(input);
1215
+ let index = string.indexOf(close, open.length);
1216
+ if (-1 === index) return open + string + close;
1217
+ let result = '';
1218
+ let cursor = 0;
1219
+ do {
1220
+ result += string.substring(cursor, index) + replace;
1221
+ cursor = index + closeLength;
1222
+ index = string.indexOf(close, cursor);
1223
+ }while (-1 !== index);
1224
+ return open + result + string.substring(cursor) + close;
1225
+ };
1226
+ }
1227
+ class RspackCLI {
1228
+ colors;
1229
+ program;
1230
+ _actionPromise;
1231
+ constructor(){
1232
+ const program = cac('rspack');
1233
+ this.colors = this.createColors();
1234
+ this.program = program;
1235
+ program.help();
1236
+ program.version("2.0.0-rc.1");
1237
+ }
1238
+ wrapAction(fn) {
1239
+ return (...args)=>{
1240
+ this._actionPromise = fn(...args);
1241
+ return this._actionPromise;
1242
+ };
1243
+ }
1244
+ async buildCompilerConfig(options, rspackCommand) {
1245
+ let { config, pathMap } = await this.loadConfig(options);
1246
+ config = await this.buildConfig(config, pathMap, options, rspackCommand);
1247
+ return config;
1248
+ }
1249
+ async createCompiler(config, callback) {
1250
+ const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
1251
+ let compiler;
1252
+ try {
1253
+ compiler = rspack(config, isWatch ? callback : void 0);
1254
+ if (!isWatch && compiler) compiler.unsafeFastDrop = true;
1255
+ } catch (e) {
1256
+ if (e instanceof rspack.ValidationError) {
1257
+ this.getLogger().error(e.message);
1258
+ process.exit(2);
1259
+ } else if (e instanceof Error) {
1260
+ if ('function' == typeof callback) callback(e);
1261
+ else this.getLogger().error(e);
1262
+ return null;
1263
+ }
1264
+ throw e;
1265
+ }
1266
+ return compiler;
1267
+ }
1268
+ createColors(useColor) {
1269
+ const envSupported = isEnvColorSupported();
1270
+ const enabled = useColor ?? envSupported;
1271
+ if (!enabled) {
1272
+ const passthrough = (text)=>String(text);
1273
+ return {
1274
+ isColorSupported: false,
1275
+ red: passthrough,
1276
+ yellow: passthrough,
1277
+ cyan: passthrough,
1278
+ green: passthrough
1279
+ };
1280
+ }
1281
+ return {
1282
+ isColorSupported: true,
1283
+ red: createAnsiFormatter('\x1b[31m', '\x1b[39m'),
1284
+ green: createAnsiFormatter('\x1b[32m', '\x1b[39m'),
1285
+ yellow: createAnsiFormatter('\x1b[33m', '\x1b[39m'),
1286
+ cyan: createAnsiFormatter('\x1b[36m', '\x1b[39m')
1287
+ };
1288
+ }
1289
+ getLogger() {
1290
+ return {
1291
+ error: (val)=>console.error(`[rspack-cli] ${this.colors.red(node_util.format(val))}`),
1292
+ warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`),
1293
+ info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`),
1294
+ success: (val)=>console.log(`[rspack-cli] ${this.colors.green(val)}`),
1295
+ log: (val)=>console.log(`[rspack-cli] ${val}`),
1296
+ raw: (val)=>console.log(val)
1297
+ };
1298
+ }
1299
+ async run(argv) {
1300
+ await this.registerCommands();
1301
+ this.program.parse(argv);
1302
+ if (this._actionPromise) await this._actionPromise;
1303
+ }
1304
+ async registerCommands() {
1305
+ const builtinCommands = [
1306
+ new BuildCommand(),
1307
+ new ServeCommand(),
1308
+ new PreviewCommand()
1309
+ ];
1310
+ for (const command of builtinCommands)await command.apply(this);
1311
+ }
1312
+ async buildConfig(item, pathMap, options, command) {
1313
+ const isBuild = 'build' === command;
1314
+ const isServe = 'serve' === command;
1315
+ const internalBuildConfig = async (item)=>{
1316
+ if (options.entry) item.entry = {
1317
+ main: options.entry.map((x)=>node_path.resolve(process.cwd(), x))[0]
1318
+ };
1319
+ item.output = item.output || {};
1320
+ if (options.outputPath) item.output.path = node_path.resolve(process.cwd(), options.outputPath);
1321
+ if (process.env.RSPACK_PROFILE) {
1322
+ const { applyProfile } = await import("./profile.js");
1323
+ await applyProfile(process.env.RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
1324
+ }
1325
+ if (options.watch) item.watch = options.watch;
1326
+ if (!item.mode) item.mode = isBuild ? 'production' : 'development';
1327
+ if (options.mode) item.mode = options.mode;
1328
+ if (void 0 === item.devtool) item.devtool = isBuild ? false : 'cheap-module-source-map';
1329
+ if (void 0 !== options.devtool) item.devtool = options.devtool;
1330
+ if (isServe) {
1331
+ const installed = (item.plugins ||= []).find((item)=>item instanceof rspack.ProgressPlugin);
1332
+ if (!installed) (item.plugins ??= []).push(new rspack.ProgressPlugin());
1333
+ }
1334
+ const cacheOptions = item.cache;
1335
+ if ('object' == typeof cacheOptions && 'persistent' === cacheOptions.type) {
1336
+ const configPaths = pathMap.get(item);
1337
+ if (configPaths) cacheOptions.buildDependencies = [
1338
+ ...configPaths,
1339
+ ...cacheOptions.buildDependencies || []
1340
+ ];
1341
+ }
1342
+ if (void 0 === item.stats) item.stats = {
1343
+ preset: 'errors-warnings',
1344
+ timings: true
1345
+ };
1346
+ else if ('boolean' == typeof item.stats) item.stats = item.stats ? {
1347
+ preset: 'normal'
1348
+ } : {
1349
+ preset: 'none'
1350
+ };
1351
+ else if ('string' == typeof item.stats) item.stats = {
1352
+ preset: item.stats
1353
+ };
1354
+ return item;
1355
+ };
1356
+ if (Array.isArray(item)) return Promise.all(item.map(internalBuildConfig));
1357
+ return internalBuildConfig(item);
1358
+ }
1359
+ async loadConfig(options) {
1360
+ const config = await loadRspackConfig(options);
1361
+ if (!config) return {
1362
+ config: this.filterConfig(options, {}),
1363
+ pathMap: new WeakMap()
1364
+ };
1365
+ let { loadedConfig, configPath } = config;
1366
+ if ('function' == typeof loadedConfig) {
1367
+ let functionResult = loadedConfig(options.env, options);
1368
+ if ('function' == typeof functionResult.then) functionResult = await functionResult;
1369
+ loadedConfig = functionResult;
1370
+ }
1371
+ const { config: extendedConfig, pathMap } = await loadExtendedConfig(loadedConfig, configPath, process.cwd(), options);
1372
+ return {
1373
+ config: this.filterConfig(options, extendedConfig),
1374
+ pathMap
1375
+ };
1376
+ }
1377
+ filterConfig(options, config) {
1378
+ if (options.configName) {
1379
+ const notFoundConfigNames = [];
1380
+ config = options.configName.map((configName)=>{
1381
+ let found;
1382
+ found = Array.isArray(config) ? config.find((options)=>options.name === configName) : config.name === configName ? config : void 0;
1383
+ if (!found) notFoundConfigNames.push(configName);
1384
+ return found;
1385
+ });
1386
+ if (notFoundConfigNames.length > 0) {
1387
+ this.getLogger().error(notFoundConfigNames.map((configName)=>`Configuration with the name "${configName}" was not found.`).join(' '));
1388
+ process.exit(2);
1389
+ }
1390
+ }
1391
+ return config;
1392
+ }
1393
+ isMultipleCompiler(compiler) {
1394
+ return Boolean(compiler.compilers);
1395
+ }
1396
+ isWatch(compiler) {
1397
+ return Boolean(this.isMultipleCompiler(compiler) ? compiler.compilers.some((compiler)=>compiler.options.watch) : compiler.options.watch);
1398
+ }
1399
+ }
1400
+ function defineConfig(config) {
1401
+ return config;
1402
+ }
1403
+ function definePlugin(plugin) {
1404
+ return plugin;
1405
+ }
1406
+ export { __webpack_require__temp as __webpack_require__, RspackCLI, defineConfig, definePlugin };