@rspack/cli 1.7.0-beta.0 → 1.7.0

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