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