@rspack-debug/cli 1.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,748 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__ from "@rspack/core";
2
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_colorette__ from "colorette";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_yargs__ from "yargs";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_yargs_helpers_525217b7__ from "yargs/helpers";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
9
+ var __webpack_modules__ = {
10
+ "@rspack/core": function(module) {
11
+ module.exports = __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__;
12
+ },
13
+ "node:fs": function(module) {
14
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
15
+ },
16
+ "node:path": function(module) {
17
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
18
+ }
19
+ };
20
+ var __webpack_module_cache__ = {};
21
+ function __webpack_require__(moduleId) {
22
+ var cachedModule = __webpack_module_cache__[moduleId];
23
+ if (void 0 !== cachedModule) return cachedModule.exports;
24
+ var module = __webpack_module_cache__[moduleId] = {
25
+ exports: {}
26
+ };
27
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
28
+ return module.exports;
29
+ }
30
+ __webpack_require__.m = __webpack_modules__;
31
+ (()=>{
32
+ __webpack_require__.d = (exports, definition)=>{
33
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
34
+ enumerable: true,
35
+ get: definition[key]
36
+ });
37
+ };
38
+ })();
39
+ (()=>{
40
+ __webpack_require__.f = {};
41
+ __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
42
+ __webpack_require__.f[key](chunkId, promises);
43
+ return promises;
44
+ }, []));
45
+ })();
46
+ (()=>{
47
+ __webpack_require__.u = (chunkId)=>"" + chunkId + ".mjs";
48
+ })();
49
+ (()=>{
50
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
51
+ })();
52
+ (()=>{
53
+ var installedChunks = {
54
+ 980: 0
55
+ };
56
+ var installChunk = (data)=>{
57
+ var __webpack_ids__ = data.__webpack_ids__;
58
+ var __webpack_modules__ = data.__webpack_modules__;
59
+ var __webpack_runtime__ = data.__webpack_runtime__;
60
+ var moduleId, chunkId, i = 0;
61
+ for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
62
+ if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
63
+ for(; i < __webpack_ids__.length; i++){
64
+ chunkId = __webpack_ids__[i];
65
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
66
+ installedChunks[__webpack_ids__[i]] = 0;
67
+ }
68
+ };
69
+ __webpack_require__.f.j = function(chunkId, promises) {
70
+ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
71
+ if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
72
+ else {
73
+ var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
74
+ if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
75
+ throw e;
76
+ });
77
+ var promise = Promise.race([
78
+ promise,
79
+ new Promise((resolve)=>{
80
+ installedChunkData = installedChunks[chunkId] = [
81
+ resolve
82
+ ];
83
+ })
84
+ ]);
85
+ promises.push(installedChunkData[1] = promise);
86
+ }
87
+ };
88
+ })();
89
+ var external_node_path_ = __webpack_require__("node:path");
90
+ var core_ = __webpack_require__("@rspack/core");
91
+ var external_node_fs_ = __webpack_require__("node:fs");
92
+ const commonOptions = (yargs)=>yargs.options({
93
+ config: {
94
+ g: true,
95
+ type: "string",
96
+ describe: "config file",
97
+ alias: "c"
98
+ },
99
+ configName: {
100
+ type: "array",
101
+ string: true,
102
+ describe: "Name of the configuration to use."
103
+ },
104
+ configLoader: {
105
+ type: "string",
106
+ default: "register",
107
+ describe: "Specify the loader to load the config file, can be `native` or `register`."
108
+ },
109
+ nodeEnv: {
110
+ string: true,
111
+ describe: "sets `process.env.NODE_ENV` to be specified value"
112
+ }
113
+ });
114
+ const commonOptionsForBuildAndServe = (yargs)=>yargs.options({
115
+ entry: {
116
+ type: "array",
117
+ string: true,
118
+ describe: "entry file"
119
+ },
120
+ outputPath: {
121
+ type: "string",
122
+ describe: "output path dir",
123
+ alias: "o"
124
+ },
125
+ mode: {
126
+ type: "string",
127
+ describe: "mode",
128
+ alias: "m"
129
+ },
130
+ watch: {
131
+ type: "boolean",
132
+ default: false,
133
+ describe: "watch",
134
+ alias: "w"
135
+ },
136
+ env: {
137
+ type: "array",
138
+ string: true,
139
+ describe: "env passed to config function"
140
+ },
141
+ devtool: {
142
+ type: "boolean",
143
+ default: false,
144
+ describe: "devtool",
145
+ alias: "d"
146
+ }
147
+ }).alias({
148
+ v: "version",
149
+ h: "help"
150
+ });
151
+ function normalizeEnv(argv) {
152
+ function parseValue(previous, value) {
153
+ const [allKeys, val] = value.split(/=(.+)/, 2);
154
+ const splitKeys = allKeys.split(/\.(?!$)/);
155
+ let prevRef = previous;
156
+ splitKeys.forEach((key, index)=>{
157
+ let someKey = key;
158
+ if (someKey.endsWith("=")) {
159
+ someKey = someKey.slice(0, -1);
160
+ prevRef[someKey] = void 0;
161
+ return;
162
+ }
163
+ if (!prevRef[someKey] || "string" == typeof prevRef[someKey]) prevRef[someKey] = {};
164
+ if (index === splitKeys.length - 1) if ("string" == typeof val) prevRef[someKey] = val;
165
+ else prevRef[someKey] = true;
166
+ prevRef = prevRef[someKey];
167
+ });
168
+ return previous;
169
+ }
170
+ const envObj = (argv.env ?? []).reduce(parseValue, {});
171
+ argv.env = envObj;
172
+ }
173
+ function setBuiltinEnvArg(env, envNameSuffix, value) {
174
+ const envNames = [
175
+ `RSPACK_${envNameSuffix}`
176
+ ];
177
+ for (const envName of envNames)if (!(envName in env)) env[envName] = value;
178
+ }
179
+ function ensureEnvObject(options) {
180
+ if (Array.isArray(options.env)) normalizeEnv(options);
181
+ options.env = options.env || {};
182
+ return options.env;
183
+ }
184
+ function setDefaultNodeEnv(options, defaultEnv) {
185
+ if (void 0 !== process.env.NODE_ENV) return;
186
+ process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
187
+ }
188
+ class BuildCommand {
189
+ async apply(cli) {
190
+ cli.program.command([
191
+ "build",
192
+ "$0",
193
+ "bundle",
194
+ "b"
195
+ ], "run the rspack build", (yargs)=>{
196
+ commonOptionsForBuildAndServe(commonOptions(yargs)).options({
197
+ analyze: {
198
+ type: "boolean",
199
+ default: false,
200
+ describe: "analyze"
201
+ },
202
+ json: {
203
+ describe: "emit stats json"
204
+ },
205
+ profile: {
206
+ type: "boolean",
207
+ default: false,
208
+ describe: "capture timing information for each module"
209
+ }
210
+ });
211
+ }, async (options)=>{
212
+ setDefaultNodeEnv(options, "production");
213
+ const env = ensureEnvObject(options);
214
+ if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
215
+ else {
216
+ setBuiltinEnvArg(env, "BUNDLE", true);
217
+ setBuiltinEnvArg(env, "BUILD", true);
218
+ }
219
+ const logger = cli.getLogger();
220
+ let createJsonStringifyStream;
221
+ if (options.json) {
222
+ const jsonExt = await import("@discoveryjs/json-ext");
223
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
224
+ }
225
+ const errorHandler = (error, stats)=>{
226
+ if (error) {
227
+ logger.error(error);
228
+ process.exit(2);
229
+ }
230
+ if (null == stats ? void 0 : stats.hasErrors()) process.exitCode = 1;
231
+ if (!compiler || !stats) return;
232
+ const statsOptions = cli.isMultipleCompiler(compiler) ? {
233
+ children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
234
+ } : compiler.options ? compiler.options.stats : void 0;
235
+ if (options.json && createJsonStringifyStream) {
236
+ const handleWriteError = (error)=>{
237
+ logger.error(error);
238
+ process.exit(2);
239
+ };
240
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
241
+ else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_.createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{
242
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
243
+ });
244
+ } else {
245
+ const printedStats = stats.toString(statsOptions);
246
+ if (printedStats) logger.raw(printedStats);
247
+ }
248
+ };
249
+ const rspackOptions = {
250
+ ...options,
251
+ argv: {
252
+ ...options
253
+ }
254
+ };
255
+ const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler);
256
+ if (!compiler || cli.isWatch(compiler)) return;
257
+ compiler.run((error, stats)=>{
258
+ compiler.close((closeErr)=>{
259
+ if (closeErr) logger.error(closeErr);
260
+ errorHandler(error, stats);
261
+ });
262
+ });
263
+ });
264
+ }
265
+ }
266
+ const previewOptions = (yargs)=>{
267
+ yargs.positional("dir", {
268
+ type: "string",
269
+ describe: "directory want to preview"
270
+ });
271
+ return commonOptions(yargs).options({
272
+ publicPath: {
273
+ type: "string",
274
+ describe: "static resource server path"
275
+ },
276
+ port: {
277
+ type: "number",
278
+ describe: "preview server port"
279
+ },
280
+ host: {
281
+ type: "string",
282
+ describe: "preview server host"
283
+ },
284
+ open: {
285
+ type: "boolean",
286
+ describe: "open browser"
287
+ },
288
+ server: {
289
+ type: "string",
290
+ describe: "Configuration items for the server."
291
+ }
292
+ });
293
+ };
294
+ const defaultRoot = "dist";
295
+ class PreviewCommand {
296
+ async apply(cli) {
297
+ cli.program.command([
298
+ "preview [dir]",
299
+ "preview",
300
+ "p"
301
+ ], "run the rspack server for build output", previewOptions, async (options)=>{
302
+ setDefaultNodeEnv(options, "production");
303
+ const rspackOptions = {
304
+ ...options,
305
+ argv: {
306
+ ...options
307
+ }
308
+ };
309
+ const { RspackDevServer } = await import("@rspack/dev-server");
310
+ let config = await cli.loadConfig(rspackOptions);
311
+ config = await getPreviewConfig(config, options);
312
+ if (!Array.isArray(config)) config = [
313
+ config
314
+ ];
315
+ config = config.find((item)=>item.devServer) || config[0];
316
+ const devServerOptions = config.devServer;
317
+ try {
318
+ const compiler = (0, core_.rspack)({
319
+ entry: {}
320
+ });
321
+ if (!compiler) return;
322
+ const server = new RspackDevServer(devServerOptions, compiler);
323
+ await server.start();
324
+ } catch (error) {
325
+ const logger = cli.getLogger();
326
+ logger.error(error);
327
+ process.exit(2);
328
+ }
329
+ });
330
+ }
331
+ }
332
+ async function getPreviewConfig(item, options) {
333
+ const internalPreviewConfig = async (item)=>{
334
+ var _item_output, _item_devServer, _item_devServer1, _item_devServer2, _item_devServer3, _item_devServer4;
335
+ item.devServer = {
336
+ static: {
337
+ directory: options.dir ? external_node_path_["default"].join(item.context ?? process.cwd(), options.dir) : (null == (_item_output = item.output) ? void 0 : _item_output.path) ?? external_node_path_["default"].join(item.context ?? process.cwd(), defaultRoot),
338
+ publicPath: options.publicPath ?? "/"
339
+ },
340
+ port: options.port ?? 8080,
341
+ proxy: null == (_item_devServer = item.devServer) ? void 0 : _item_devServer.proxy,
342
+ host: options.host ?? (null == (_item_devServer1 = item.devServer) ? void 0 : _item_devServer1.host),
343
+ open: options.open ?? (null == (_item_devServer2 = item.devServer) ? void 0 : _item_devServer2.open),
344
+ server: options.server ?? (null == (_item_devServer3 = item.devServer) ? void 0 : _item_devServer3.server),
345
+ historyApiFallback: null == (_item_devServer4 = item.devServer) ? void 0 : _item_devServer4.historyApiFallback
346
+ };
347
+ return item;
348
+ };
349
+ if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
350
+ return internalPreviewConfig(item);
351
+ }
352
+ class ServeCommand {
353
+ async apply(cli) {
354
+ cli.program.command([
355
+ "serve",
356
+ "server",
357
+ "s",
358
+ "dev"
359
+ ], "run the rspack dev server.", (yargs)=>commonOptionsForBuildAndServe(commonOptions(yargs)).options({
360
+ hot: {
361
+ coerce: (arg)=>{
362
+ if ("boolean" == typeof arg || "only" === arg) return arg;
363
+ if ("false" === arg) return false;
364
+ return true;
365
+ },
366
+ describe: "enables hot module replacement"
367
+ },
368
+ port: {
369
+ type: "number",
370
+ coerce: (arg)=>Number.isInteger(arg) ? arg : void 0,
371
+ describe: "allows to specify a port to use"
372
+ },
373
+ host: {
374
+ type: "string",
375
+ describe: "allows to specify a hostname to use"
376
+ }
377
+ }), async (options)=>{
378
+ setDefaultNodeEnv(options, "development");
379
+ setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true);
380
+ const rspackOptions = {
381
+ ...options,
382
+ argv: {
383
+ ...options
384
+ }
385
+ };
386
+ const { RspackDevServer } = await import("@rspack/dev-server");
387
+ const compiler = await cli.createCompiler(rspackOptions, "serve");
388
+ if (!compiler) return;
389
+ const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [
390
+ compiler
391
+ ];
392
+ const possibleCompilers = compilers.filter((compiler)=>compiler.options.devServer);
393
+ const usedPorts = [];
394
+ const servers = [];
395
+ const compilerForDevServer = possibleCompilers.length > 0 ? possibleCompilers[0] : compilers[0];
396
+ for (const compiler of compilers){
397
+ const devServer = compiler.options.devServer ??= {};
398
+ devServer.hot = options.hot ?? devServer.hot ?? true;
399
+ if (false !== devServer.client) {
400
+ if (true === devServer.client || null == devServer.client) devServer.client = {};
401
+ devServer.client = {
402
+ overlay: {
403
+ errors: true,
404
+ warnings: false
405
+ },
406
+ ...devServer.client
407
+ };
408
+ }
409
+ }
410
+ const result = compilerForDevServer.options.devServer ??= {};
411
+ if (compilerForDevServer.options.experiments.lazyCompilation) {
412
+ const options = compilerForDevServer.options.experiments.lazyCompilation;
413
+ const setupMiddlewares = result.setupMiddlewares;
414
+ const lazyCompileMiddleware = core_.rspack.experiments.lazyCompilationMiddleware(compilerForDevServer, options);
415
+ result.setupMiddlewares = (middlewares, server)=>{
416
+ let finalMiddlewares = middlewares;
417
+ if (setupMiddlewares) finalMiddlewares = setupMiddlewares(finalMiddlewares, server);
418
+ return [
419
+ lazyCompileMiddleware,
420
+ ...finalMiddlewares
421
+ ];
422
+ };
423
+ }
424
+ result.hot = options.hot ?? result.hot ?? true;
425
+ result.host = options.host || result.host;
426
+ result.port = options.port || result.port;
427
+ if (false !== result.client) {
428
+ if (true === result.client || null == result.client) result.client = {};
429
+ result.client = {
430
+ overlay: {
431
+ errors: true,
432
+ warnings: false
433
+ },
434
+ ...result.client
435
+ };
436
+ }
437
+ const devServerOptions = result;
438
+ if (devServerOptions.port) {
439
+ const portNumber = Number(devServerOptions.port);
440
+ if (!Number.isNaN(portNumber)) {
441
+ 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.");
442
+ usedPorts.push(portNumber);
443
+ }
444
+ }
445
+ try {
446
+ const server = new RspackDevServer(devServerOptions, compiler);
447
+ await server.start();
448
+ servers.push(server);
449
+ } catch (error) {
450
+ const logger = cli.getLogger();
451
+ logger.error(error);
452
+ process.exit(2);
453
+ }
454
+ });
455
+ }
456
+ }
457
+ const readPackageUp_readPackageUp = (cwd = process.cwd())=>{
458
+ let currentDir = external_node_path_["default"].resolve(cwd);
459
+ let packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
460
+ while(!external_node_fs_["default"].existsSync(packageJsonPath)){
461
+ const parentDir = external_node_path_["default"].dirname(currentDir);
462
+ if (parentDir === currentDir) return null;
463
+ currentDir = parentDir;
464
+ packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
465
+ }
466
+ try {
467
+ return JSON.parse(external_node_fs_["default"].readFileSync(packageJsonPath, "utf8"));
468
+ } catch (error) {
469
+ return null;
470
+ }
471
+ };
472
+ const readPackageUp = readPackageUp_readPackageUp;
473
+ const isEsmFile = (filePath, cwd = process.cwd())=>{
474
+ const ext = external_node_path_["default"].extname(filePath);
475
+ if (/\.(mjs|mts)$/.test(ext)) return true;
476
+ if (/\.(cjs|cts)/.test(ext)) return false;
477
+ const packageJson = readPackageUp(external_node_path_["default"].dirname(filePath));
478
+ return (null == packageJson ? void 0 : packageJson.type) === "module";
479
+ };
480
+ const utils_isEsmFile = isEsmFile;
481
+ const crossImport = async (path, cwd = process.cwd())=>{
482
+ if (utils_isEsmFile(path, cwd)) {
483
+ const url = (0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(path).href;
484
+ const { default: config } = await import(url);
485
+ return config;
486
+ }
487
+ let result = require(path);
488
+ if (result && "object" == typeof result && "default" in result) result = result.default || {};
489
+ return result;
490
+ };
491
+ const DEFAULT_EXTENSIONS = [
492
+ ".js",
493
+ ".ts",
494
+ ".mjs",
495
+ ".mts",
496
+ ".cjs",
497
+ ".cts"
498
+ ];
499
+ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_["default"].existsSync);
500
+ const utils_findConfig = findConfig;
501
+ const isTsFile = (configPath)=>{
502
+ const ext = external_node_path_["default"].extname(configPath);
503
+ return /\.(c|m)?ts$/.test(ext);
504
+ };
505
+ const utils_isTsFile = isTsFile;
506
+ const loadConfig_DEFAULT_CONFIG_NAME = "rspack.config";
507
+ const registerLoader = async (configPath)=>{
508
+ const ext = external_node_path_["default"].extname(configPath);
509
+ if (utils_isEsmFile(configPath) && utils_isTsFile(configPath)) return;
510
+ const { default: interpret } = await import("interpret");
511
+ const extensions = Object.fromEntries(Object.entries(interpret.extensions).filter(([key])=>key === ext));
512
+ if (0 === Object.keys(extensions).length) throw new Error(`config file "${configPath}" is not supported.`);
513
+ try {
514
+ const { default: rechoir } = await import("rechoir");
515
+ rechoir.prepare(extensions, configPath);
516
+ } catch (error) {
517
+ const failures = null == error ? void 0 : error.failures;
518
+ if (failures) {
519
+ const messages = failures.map((failure)=>failure.error.message);
520
+ throw new Error(`${messages.join("\n")}`);
521
+ }
522
+ throw error;
523
+ }
524
+ };
525
+ async function loadExtendedConfig(config, configPath, cwd, options) {
526
+ if (!("extends" in config) || !config.extends) return config;
527
+ const extendsList = Array.isArray(config.extends) ? config.extends : [
528
+ config.extends
529
+ ];
530
+ const { extends: _, ...configWithoutExtends } = config;
531
+ const baseDir = external_node_path_["default"].dirname(configPath);
532
+ let resultConfig = configWithoutExtends;
533
+ for (const extendPath of extendsList){
534
+ let resolvedPath;
535
+ if (extendPath.startsWith(".") || extendPath.startsWith("/") || extendPath.includes(":\\")) {
536
+ resolvedPath = external_node_path_["default"].resolve(baseDir, extendPath);
537
+ if (!external_node_path_["default"].extname(resolvedPath)) {
538
+ const foundConfig = utils_findConfig(resolvedPath);
539
+ if (foundConfig) resolvedPath = foundConfig;
540
+ else throw new Error(`Extended configuration file "${resolvedPath}" not found.`);
541
+ }
542
+ } else try {
543
+ resolvedPath = require.resolve(extendPath, {
544
+ paths: [
545
+ baseDir,
546
+ cwd
547
+ ]
548
+ });
549
+ } catch (error) {
550
+ throw new Error(`Cannot find module '${extendPath}' to extend from.`);
551
+ }
552
+ if (!external_node_fs_["default"].existsSync(resolvedPath)) throw new Error(`Extended configuration file "${resolvedPath}" not found.`);
553
+ if (utils_isTsFile(resolvedPath) && "register" === options.configLoader) await registerLoader(resolvedPath);
554
+ let extendedConfig = await crossImport(resolvedPath, cwd);
555
+ if ("function" == typeof extendedConfig) {
556
+ var _options_argv;
557
+ extendedConfig = extendedConfig(null == (_options_argv = options.argv) ? void 0 : _options_argv.env, options.argv);
558
+ if ("function" == typeof extendedConfig.then) extendedConfig = await extendedConfig;
559
+ }
560
+ extendedConfig = await loadExtendedConfig(extendedConfig, resolvedPath, cwd, options);
561
+ resultConfig = core_.util.cleverMerge(extendedConfig, resultConfig);
562
+ }
563
+ return resultConfig;
564
+ }
565
+ async function loadRspackConfig(options, cwd = process.cwd()) {
566
+ let configPath;
567
+ let loadedConfig;
568
+ if (options.config) {
569
+ configPath = external_node_path_["default"].resolve(cwd, options.config);
570
+ if (!external_node_fs_["default"].existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`);
571
+ if (utils_isTsFile(configPath) && "register" === options.configLoader) await registerLoader(configPath);
572
+ loadedConfig = await crossImport(configPath, cwd);
573
+ } else {
574
+ const defaultConfig = utils_findConfig(external_node_path_["default"].resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME));
575
+ if (!defaultConfig) return {};
576
+ configPath = defaultConfig;
577
+ if (utils_isTsFile(defaultConfig) && "register" === options.configLoader) await registerLoader(defaultConfig);
578
+ loadedConfig = await crossImport(defaultConfig, cwd);
579
+ }
580
+ if ("function" != typeof loadedConfig && configPath) loadedConfig = await loadExtendedConfig(loadedConfig, configPath, cwd, options);
581
+ return loadedConfig;
582
+ }
583
+ function _define_property(obj, key, value) {
584
+ if (key in obj) Object.defineProperty(obj, key, {
585
+ value: value,
586
+ enumerable: true,
587
+ configurable: true,
588
+ writable: true
589
+ });
590
+ else obj[key] = value;
591
+ return obj;
592
+ }
593
+ class RspackCLI {
594
+ async createCompiler(options, rspackCommand, callback) {
595
+ process.env.RSPACK_CONFIG_VALIDATE ??= "loose";
596
+ let config = await this.loadConfig(options);
597
+ config = await this.buildConfig(config, options, rspackCommand);
598
+ const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
599
+ let compiler;
600
+ try {
601
+ compiler = (0, core_.rspack)(config, isWatch ? callback : void 0);
602
+ } catch (e) {
603
+ if (e instanceof core_.ValidationError) {
604
+ this.getLogger().error(e.message);
605
+ process.exit(2);
606
+ } else if (e instanceof Error) {
607
+ if ("function" == typeof callback) callback(e);
608
+ else this.getLogger().error(e);
609
+ return null;
610
+ }
611
+ throw e;
612
+ }
613
+ return compiler;
614
+ }
615
+ createColors(useColor) {
616
+ const shouldUseColor = useColor || __WEBPACK_EXTERNAL_MODULE_colorette__.isColorSupported;
617
+ return {
618
+ ...(0, __WEBPACK_EXTERNAL_MODULE_colorette__.createColors)({
619
+ useColor: shouldUseColor
620
+ }),
621
+ isColorSupported: shouldUseColor
622
+ };
623
+ }
624
+ getLogger() {
625
+ return {
626
+ error: (val)=>console.error(`[rspack-cli] ${this.colors.red(__WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__["default"].format(val))}`),
627
+ warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`),
628
+ info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`),
629
+ success: (val)=>console.log(`[rspack-cli] ${this.colors.green(val)}`),
630
+ log: (val)=>console.log(`[rspack-cli] ${val}`),
631
+ raw: (val)=>console.log(val)
632
+ };
633
+ }
634
+ async run(argv) {
635
+ this.program.showHelpOnFail(false);
636
+ this.program.usage("[options]");
637
+ this.program.scriptName("rspack");
638
+ this.program.strictCommands(true).strict(true);
639
+ this.program.middleware(normalizeEnv);
640
+ this.registerCommands();
641
+ await this.program.parseAsync((0, __WEBPACK_EXTERNAL_MODULE_yargs_helpers_525217b7__.hideBin)(argv));
642
+ }
643
+ async registerCommands() {
644
+ const builtinCommands = [
645
+ new BuildCommand(),
646
+ new ServeCommand(),
647
+ new PreviewCommand()
648
+ ];
649
+ for (const command of builtinCommands)command.apply(this);
650
+ }
651
+ async buildConfig(item, options, command) {
652
+ const isBuild = "build" === command;
653
+ const isServe = "serve" === command;
654
+ const internalBuildConfig = async (item)=>{
655
+ if (options.entry) item.entry = {
656
+ main: options.entry.map((x)=>external_node_path_["default"].resolve(process.cwd(), x))[0]
657
+ };
658
+ item.output = item.output || {};
659
+ if (options.outputPath) item.output.path = external_node_path_["default"].resolve(process.cwd(), options.outputPath);
660
+ if (options.analyze) {
661
+ const { BundleAnalyzerPlugin } = await import("webpack-bundle-analyzer");
662
+ (item.plugins ??= []).push({
663
+ name: "rspack-bundle-analyzer",
664
+ apply (compiler) {
665
+ new BundleAnalyzerPlugin({
666
+ generateStatsFile: true
667
+ }).apply(compiler);
668
+ }
669
+ });
670
+ }
671
+ if (options.profile) item.profile = true;
672
+ if (process.env.RSPACK_PROFILE) {
673
+ const { applyProfile } = await __webpack_require__.e("556").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts"));
674
+ await applyProfile(process.env.RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
675
+ }
676
+ if (options.watch) item.watch = options.watch;
677
+ if (!item.mode) item.mode = isBuild ? "production" : "development";
678
+ if (options.mode) item.mode = options.mode;
679
+ if (void 0 === item.devtool) item.devtool = isBuild ? "source-map" : "cheap-module-source-map";
680
+ if (isServe) {
681
+ const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin);
682
+ if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin());
683
+ }
684
+ if (void 0 === item.stats) item.stats = {
685
+ preset: "errors-warnings",
686
+ timings: true
687
+ };
688
+ else if ("boolean" == typeof item.stats) item.stats = item.stats ? {
689
+ preset: "normal"
690
+ } : {
691
+ preset: "none"
692
+ };
693
+ else if ("string" == typeof item.stats) item.stats = {
694
+ preset: item.stats
695
+ };
696
+ if (this.colors.isColorSupported && void 0 === item.stats.colors) item.stats.colors = true;
697
+ return item;
698
+ };
699
+ if (Array.isArray(item)) return Promise.all(item.map(internalBuildConfig));
700
+ return internalBuildConfig(item);
701
+ }
702
+ async loadConfig(options) {
703
+ let loadedConfig = await loadRspackConfig(options);
704
+ if ("function" == typeof loadedConfig) {
705
+ var _options_argv;
706
+ let functionResult = loadedConfig(null == (_options_argv = options.argv) ? void 0 : _options_argv.env, options.argv);
707
+ if ("function" == typeof functionResult.then) functionResult = await functionResult;
708
+ loadedConfig = functionResult;
709
+ if ("extends" in loadedConfig && loadedConfig.extends) {
710
+ const tempConfigPath = external_node_path_["default"].resolve(process.cwd(), "rspack.config.js");
711
+ loadedConfig = await loadExtendedConfig(loadedConfig, tempConfigPath, process.cwd(), options);
712
+ }
713
+ }
714
+ if (options.configName) {
715
+ const notFoundConfigNames = [];
716
+ loadedConfig = options.configName.map((configName)=>{
717
+ let found;
718
+ found = Array.isArray(loadedConfig) ? loadedConfig.find((options)=>options.name === configName) : loadedConfig.name === configName ? loadedConfig : void 0;
719
+ if (!found) notFoundConfigNames.push(configName);
720
+ return found;
721
+ });
722
+ if (notFoundConfigNames.length > 0) {
723
+ this.getLogger().error(notFoundConfigNames.map((configName)=>`Configuration with the name "${configName}" was not found.`).join(" "));
724
+ process.exit(2);
725
+ }
726
+ }
727
+ return loadedConfig;
728
+ }
729
+ isMultipleCompiler(compiler) {
730
+ return Boolean(compiler.compilers);
731
+ }
732
+ isWatch(compiler) {
733
+ return Boolean(this.isMultipleCompiler(compiler) ? compiler.compilers.some((compiler)=>compiler.options.watch) : compiler.options.watch);
734
+ }
735
+ constructor(){
736
+ _define_property(this, "colors", void 0);
737
+ _define_property(this, "program", void 0);
738
+ this.colors = this.createColors();
739
+ this.program = (0, __WEBPACK_EXTERNAL_MODULE_yargs__["default"])();
740
+ }
741
+ }
742
+ function defineConfig(config) {
743
+ return config;
744
+ }
745
+ function definePlugin(plugin) {
746
+ return plugin;
747
+ }
748
+ export { RspackCLI, defineConfig, definePlugin };