@rspack-debug/cli
Advanced tools
| "use strict"; | ||
| exports.ids = [ | ||
| "361" | ||
| ]; | ||
| exports.modules = { | ||
| "./src/utils/profile.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| applyProfile: ()=>applyProfile | ||
| }); | ||
| var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:fs"); | ||
| var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); | ||
| var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("node:path"); | ||
| var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); | ||
| var _rspackCore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/utils/rspackCore.ts"); | ||
| const DEFAULT_RUST_TRACE_LAYER = "perfetto"; | ||
| async function applyProfile(filterValue, traceLayer = DEFAULT_RUST_TRACE_LAYER, traceOutput) { | ||
| const { asyncExitHook } = await import("exit-hook"); | ||
| if ("logger" !== traceLayer && "perfetto" !== traceLayer) throw new Error(`unsupported trace layer: ${traceLayer}`); | ||
| const timestamp = Date.now(); | ||
| const defaultOutputDir = node_path__WEBPACK_IMPORTED_MODULE_1___default().resolve(`.rspack-profile-${timestamp}-${process.pid}`); | ||
| if (traceOutput) { | ||
| if ("stdout" !== traceOutput && "stderr" !== traceOutput) traceOutput = node_path__WEBPACK_IMPORTED_MODULE_1___default().resolve(defaultOutputDir, traceOutput); | ||
| } else { | ||
| const defaultRustTracePerfettoOutput = node_path__WEBPACK_IMPORTED_MODULE_1___default().resolve(defaultOutputDir, "rspack.pftrace"); | ||
| const defaultRustTraceLoggerOutput = "stdout"; | ||
| const defaultTraceOutput = "perfetto" === traceLayer ? defaultRustTracePerfettoOutput : defaultRustTraceLoggerOutput; | ||
| traceOutput = defaultTraceOutput; | ||
| } | ||
| await ensureFileDir(traceOutput); | ||
| await _rspackCore__WEBPACK_IMPORTED_MODULE_2__.Z.experiments.globalTrace.register(filterValue, traceLayer, traceOutput); | ||
| asyncExitHook(_rspackCore__WEBPACK_IMPORTED_MODULE_2__.Z.experiments.globalTrace.cleanup, { | ||
| wait: 500 | ||
| }); | ||
| } | ||
| async function ensureFileDir(outputFilePath) { | ||
| const dir = node_path__WEBPACK_IMPORTED_MODULE_1___default().dirname(outputFilePath); | ||
| await node_fs__WEBPACK_IMPORTED_MODULE_0___default().promises.mkdir(dir, { | ||
| recursive: true | ||
| }); | ||
| } | ||
| } | ||
| }; |
| export const __webpack_id__ = "361"; | ||
| export const __webpack_ids__ = [ | ||
| "361" | ||
| ]; | ||
| export const __webpack_modules__ = { | ||
| "./src/utils/profile.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| applyProfile: ()=>applyProfile | ||
| }); | ||
| var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:fs"); | ||
| var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("node:path"); | ||
| var _rspackCore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("./src/utils/rspackCore.ts"); | ||
| const DEFAULT_RUST_TRACE_LAYER = "perfetto"; | ||
| async function applyProfile(filterValue, traceLayer = DEFAULT_RUST_TRACE_LAYER, traceOutput) { | ||
| const { asyncExitHook } = await import("exit-hook"); | ||
| if ("logger" !== traceLayer && "perfetto" !== traceLayer) throw new Error(`unsupported trace layer: ${traceLayer}`); | ||
| const timestamp = Date.now(); | ||
| const defaultOutputDir = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].resolve(`.rspack-profile-${timestamp}-${process.pid}`); | ||
| if (traceOutput) { | ||
| if ("stdout" !== traceOutput && "stderr" !== traceOutput) traceOutput = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].resolve(defaultOutputDir, traceOutput); | ||
| } else { | ||
| const defaultRustTracePerfettoOutput = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].resolve(defaultOutputDir, "rspack.pftrace"); | ||
| const defaultRustTraceLoggerOutput = "stdout"; | ||
| const defaultTraceOutput = "perfetto" === traceLayer ? defaultRustTracePerfettoOutput : defaultRustTraceLoggerOutput; | ||
| traceOutput = defaultTraceOutput; | ||
| } | ||
| await ensureFileDir(traceOutput); | ||
| await _rspackCore__WEBPACK_IMPORTED_MODULE_2__.Z.experiments.globalTrace.register(filterValue, traceLayer, traceOutput); | ||
| asyncExitHook(_rspackCore__WEBPACK_IMPORTED_MODULE_2__.Z.experiments.globalTrace.cleanup, { | ||
| wait: 500 | ||
| }); | ||
| } | ||
| async function ensureFileDir(outputFilePath) { | ||
| const dir = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].dirname(outputFilePath); | ||
| await node_fs__WEBPACK_IMPORTED_MODULE_0__["default"].promises.mkdir(dir, { | ||
| recursive: true | ||
| }); | ||
| } | ||
| } | ||
| }; |
| declare const rspack: (typeof import("@rspack/core"))["rspack"]; | ||
| export { rspack }; |
+15
-9
@@ -1,12 +0,14 @@ | ||
| import type { RspackPluginFunction, RspackPluginInstance } from "@rspack/core"; | ||
| import * as rspackCore from "@rspack/core"; | ||
| import { type Compiler, type MultiCompiler, type MultiRspackOptions, type MultiStats, type RspackOptions, type Stats } from "@rspack/core"; | ||
| import yargs from "yargs"; | ||
| import type { RspackBuildCLIOptions, RspackCLIColors, RspackCLILogger, RspackCLIOptions } from "./types"; | ||
| import type { Compiler, MultiCompiler, MultiRspackOptions, MultiStats, RspackOptions, RspackPluginFunction, RspackPluginInstance, Stats } from "@rspack/core"; | ||
| import { type CAC } from "cac"; | ||
| import type { RspackCLIColors, RspackCLILogger } from "./types"; | ||
| import type { CommonOptions, CommonOptionsForBuildAndServe } from "./utils/options"; | ||
| type Command = "serve" | "build"; | ||
| declare global { | ||
| const RSPACK_CLI_VERSION: string; | ||
| } | ||
| export declare class RspackCLI { | ||
| colors: RspackCLIColors; | ||
| program: yargs.Argv; | ||
| program: CAC; | ||
| constructor(); | ||
| createCompiler(options: RspackBuildCLIOptions, rspackCommand: Command, callback?: (e: Error | null, res?: Stats | MultiStats) => void): Promise<rspackCore.MultiCompiler | rspackCore.Compiler | null>; | ||
| createCompiler(options: CommonOptionsForBuildAndServe, rspackCommand: Command, callback?: (e: Error | null, res?: Stats | MultiStats) => void): Promise<MultiCompiler | Compiler | null>; | ||
| createColors(useColor?: boolean): RspackCLIColors; | ||
@@ -16,4 +18,8 @@ getLogger(): RspackCLILogger; | ||
| registerCommands(): Promise<void>; | ||
| buildConfig(item: RspackOptions | MultiRspackOptions, options: RspackBuildCLIOptions, command: Command): Promise<RspackOptions | MultiRspackOptions>; | ||
| loadConfig(options: RspackCLIOptions): Promise<RspackOptions | MultiRspackOptions>; | ||
| buildConfig(item: RspackOptions | MultiRspackOptions, pathMap: WeakMap<RspackOptions, string[]>, options: CommonOptionsForBuildAndServe, command: Command): Promise<RspackOptions | MultiRspackOptions>; | ||
| loadConfig(options: CommonOptions): Promise<{ | ||
| config: RspackOptions | MultiRspackOptions; | ||
| pathMap: WeakMap<RspackOptions, string[]>; | ||
| }>; | ||
| private filterConfig; | ||
| isMultipleCompiler(compiler: Compiler | MultiCompiler): compiler is MultiCompiler; | ||
@@ -20,0 +26,0 @@ isWatch(compiler: Compiler | MultiCompiler): boolean; |
+937
-379
@@ -1,41 +0,156 @@ | ||
| "use strict"; | ||
| const __rslib_import_meta_url__ = /*#__PURE__*/ function() { | ||
| return 'undefined' == typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href; | ||
| }(); | ||
| var __webpack_modules__ = { | ||
| "@rspack/core": function(module) { | ||
| module.exports = require("@rspack/core"); | ||
| "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js": function(module) { | ||
| let p = process || {}, argv = p.argv || [], env = p.env || {}; | ||
| 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); | ||
| let formatter = (open, close, replace = open)=>(input)=>{ | ||
| let string = "" + input, index = string.indexOf(close, open.length); | ||
| return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; | ||
| }; | ||
| let replaceClose = (string, close, replace, index)=>{ | ||
| let result = "", cursor = 0; | ||
| do { | ||
| result += string.substring(cursor, index) + replace; | ||
| cursor = index + close.length; | ||
| index = string.indexOf(close, cursor); | ||
| }while (~index); | ||
| return result + string.substring(cursor); | ||
| }; | ||
| let createColors = (enabled = isColorSupported)=>{ | ||
| let f = enabled ? formatter : ()=>String; | ||
| return { | ||
| isColorSupported: enabled, | ||
| reset: f("\x1b[0m", "\x1b[0m"), | ||
| bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), | ||
| dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), | ||
| italic: f("\x1b[3m", "\x1b[23m"), | ||
| underline: f("\x1b[4m", "\x1b[24m"), | ||
| inverse: f("\x1b[7m", "\x1b[27m"), | ||
| hidden: f("\x1b[8m", "\x1b[28m"), | ||
| strikethrough: f("\x1b[9m", "\x1b[29m"), | ||
| black: f("\x1b[30m", "\x1b[39m"), | ||
| red: f("\x1b[31m", "\x1b[39m"), | ||
| green: f("\x1b[32m", "\x1b[39m"), | ||
| yellow: f("\x1b[33m", "\x1b[39m"), | ||
| blue: f("\x1b[34m", "\x1b[39m"), | ||
| magenta: f("\x1b[35m", "\x1b[39m"), | ||
| cyan: f("\x1b[36m", "\x1b[39m"), | ||
| white: f("\x1b[37m", "\x1b[39m"), | ||
| gray: f("\x1b[90m", "\x1b[39m"), | ||
| bgBlack: f("\x1b[40m", "\x1b[49m"), | ||
| bgRed: f("\x1b[41m", "\x1b[49m"), | ||
| bgGreen: f("\x1b[42m", "\x1b[49m"), | ||
| bgYellow: f("\x1b[43m", "\x1b[49m"), | ||
| bgBlue: f("\x1b[44m", "\x1b[49m"), | ||
| bgMagenta: f("\x1b[45m", "\x1b[49m"), | ||
| bgCyan: f("\x1b[46m", "\x1b[49m"), | ||
| bgWhite: f("\x1b[47m", "\x1b[49m"), | ||
| blackBright: f("\x1b[90m", "\x1b[39m"), | ||
| redBright: f("\x1b[91m", "\x1b[39m"), | ||
| greenBright: f("\x1b[92m", "\x1b[39m"), | ||
| yellowBright: f("\x1b[93m", "\x1b[39m"), | ||
| blueBright: f("\x1b[94m", "\x1b[39m"), | ||
| magentaBright: f("\x1b[95m", "\x1b[39m"), | ||
| cyanBright: f("\x1b[96m", "\x1b[39m"), | ||
| whiteBright: f("\x1b[97m", "\x1b[39m"), | ||
| bgBlackBright: f("\x1b[100m", "\x1b[49m"), | ||
| bgRedBright: f("\x1b[101m", "\x1b[49m"), | ||
| bgGreenBright: f("\x1b[102m", "\x1b[49m"), | ||
| bgYellowBright: f("\x1b[103m", "\x1b[49m"), | ||
| bgBlueBright: f("\x1b[104m", "\x1b[49m"), | ||
| bgMagentaBright: f("\x1b[105m", "\x1b[49m"), | ||
| bgCyanBright: f("\x1b[106m", "\x1b[49m"), | ||
| bgWhiteBright: f("\x1b[107m", "\x1b[49m") | ||
| }; | ||
| }; | ||
| module.exports = createColors(); | ||
| module.exports.createColors = createColors; | ||
| }, | ||
| "../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js": function(module, exports1, __webpack_require__) { | ||
| "use strict"; | ||
| module = __webpack_require__.nmd(module); | ||
| const BuiltinModule = __webpack_require__("module"); | ||
| const path = __webpack_require__("path"); | ||
| const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/; | ||
| const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule; | ||
| 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."; | ||
| function shouldCompile(filename, exts, matcher, ignoreNodeModules) { | ||
| if ('string' != typeof filename) return false; | ||
| if (-1 === exts.indexOf(path.extname(filename))) return false; | ||
| const resolvedFilename = path.resolve(filename); | ||
| if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) return false; | ||
| if (matcher && 'function' == typeof matcher) return !!matcher(resolvedFilename); | ||
| return true; | ||
| } | ||
| function addHook(hook, opts = {}) { | ||
| let reverted = false; | ||
| const loaders = []; | ||
| const oldLoaders = []; | ||
| let exts; | ||
| const originalJSLoader = Module._extensions['.js']; | ||
| const matcher = opts.matcher || null; | ||
| const ignoreNodeModules = false !== opts.ignoreNodeModules; | ||
| exts = opts.extensions || opts.exts || opts.extension || opts.ext || [ | ||
| '.js' | ||
| ]; | ||
| if (!Array.isArray(exts)) exts = [ | ||
| exts | ||
| ]; | ||
| exts.forEach((ext)=>{ | ||
| if ('string' != typeof ext) throw new TypeError(`Invalid Extension: ${ext}`); | ||
| const oldLoader = Module._extensions[ext] || originalJSLoader; | ||
| oldLoaders[ext] = Module._extensions[ext]; | ||
| loaders[ext] = Module._extensions[ext] = function(mod, filename) { | ||
| let compile; | ||
| if (!reverted) { | ||
| if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) { | ||
| compile = mod._compile; | ||
| mod._compile = function(code) { | ||
| mod._compile = compile; | ||
| const newCode = hook(code, filename); | ||
| if ('string' != typeof newCode) throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE); | ||
| return mod._compile(newCode, filename); | ||
| }; | ||
| } | ||
| } | ||
| oldLoader(mod, filename); | ||
| }; | ||
| }); | ||
| return function() { | ||
| if (reverted) return; | ||
| reverted = true; | ||
| exts.forEach((ext)=>{ | ||
| if (Module._extensions[ext] === loaders[ext]) if (oldLoaders[ext]) Module._extensions[ext] = oldLoaders[ext]; | ||
| else delete Module._extensions[ext]; | ||
| }); | ||
| }; | ||
| } | ||
| exports1.addHook = addHook; | ||
| }, | ||
| "./src/utils/rspackCore.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { | ||
| "use strict"; | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| Z: ()=>rspack | ||
| }); | ||
| const external_node_module_namespaceObject = require("node:module"); | ||
| const rspackCore_require = (0, external_node_module_namespaceObject.createRequire)(__rslib_import_meta_url__); | ||
| const rspack = rspackCore_require("@rspack/core"); | ||
| }, | ||
| module: function(module) { | ||
| "use strict"; | ||
| module.exports = require("module"); | ||
| }, | ||
| "node:fs": function(module) { | ||
| "use strict"; | ||
| module.exports = require("node:fs"); | ||
| }, | ||
| "node:path": function(module) { | ||
| "use strict"; | ||
| module.exports = require("node:path"); | ||
| }, | ||
| "@discoveryjs/json-ext": function(module) { | ||
| module.exports = import("@discoveryjs/json-ext").then(function(module) { | ||
| return module; | ||
| }); | ||
| }, | ||
| "@rspack/dev-server": function(module) { | ||
| module.exports = import("@rspack/dev-server").then(function(module) { | ||
| return module; | ||
| }); | ||
| }, | ||
| "exit-hook": function(module) { | ||
| module.exports = import("exit-hook").then(function(module) { | ||
| return module; | ||
| }); | ||
| }, | ||
| interpret: function(module) { | ||
| module.exports = import("interpret").then(function(module) { | ||
| return module; | ||
| }); | ||
| }, | ||
| rechoir: function(module) { | ||
| module.exports = import("rechoir").then(function(module) { | ||
| return module; | ||
| }); | ||
| }, | ||
| "webpack-bundle-analyzer": function(module) { | ||
| module.exports = import("webpack-bundle-analyzer").then(function(module) { | ||
| return module; | ||
| }); | ||
| path: function(module) { | ||
| "use strict"; | ||
| module.exports = require("path"); | ||
| } | ||
@@ -48,5 +163,8 @@ }; | ||
| var module = __webpack_module_cache__[moduleId] = { | ||
| id: moduleId, | ||
| loaded: false, | ||
| exports: {} | ||
| }; | ||
| __webpack_modules__[moduleId](module, module.exports, __webpack_require__); | ||
| module.loaded = true; | ||
| return module.exports; | ||
@@ -80,3 +198,3 @@ } | ||
| (()=>{ | ||
| __webpack_require__.u = (chunkId)=>"" + chunkId + ".js"; | ||
| __webpack_require__.u = (chunkId)=>"0~" + chunkId + ".js"; | ||
| })(); | ||
@@ -97,4 +215,11 @@ (()=>{ | ||
| (()=>{ | ||
| __webpack_require__.nmd = (module)=>{ | ||
| module.paths = []; | ||
| if (!module.children) module.children = []; | ||
| return module; | ||
| }; | ||
| })(); | ||
| (()=>{ | ||
| var installedChunks = { | ||
| 980: 1 | ||
| 410: 1 | ||
| }; | ||
@@ -113,7 +238,8 @@ var installChunk = (chunk)=>{ | ||
| (()=>{ | ||
| "use strict"; | ||
| __webpack_require__.r(__webpack_exports__); | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| defineConfig: ()=>defineConfig, | ||
| definePlugin: ()=>definePlugin, | ||
| RspackCLI: ()=>RspackCLI | ||
| RspackCLI: ()=>RspackCLI, | ||
| defineConfig: ()=>defineConfig | ||
| }); | ||
@@ -124,73 +250,543 @@ var external_node_path_ = __webpack_require__("node:path"); | ||
| var external_node_util_default = /*#__PURE__*/ __webpack_require__.n(external_node_util_namespaceObject); | ||
| var core_ = __webpack_require__("@rspack/core"); | ||
| const external_colorette_namespaceObject = require("colorette"); | ||
| const external_yargs_namespaceObject = require("yargs"); | ||
| var external_yargs_default = /*#__PURE__*/ __webpack_require__.n(external_yargs_namespaceObject); | ||
| const helpers_namespaceObject = require("yargs/helpers"); | ||
| var external_node_fs_ = __webpack_require__("node:fs"); | ||
| var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_); | ||
| const commonOptions = (yargs)=>yargs.options({ | ||
| config: { | ||
| g: true, | ||
| type: "string", | ||
| describe: "config file", | ||
| alias: "c" | ||
| }, | ||
| configName: { | ||
| type: "array", | ||
| string: true, | ||
| describe: "Name of the configuration to use." | ||
| }, | ||
| configLoader: { | ||
| type: "string", | ||
| default: "register", | ||
| describe: "Specify the loader to load the config file, can be `native` or `register`." | ||
| }, | ||
| nodeEnv: { | ||
| string: true, | ||
| describe: "sets `process.env.NODE_ENV` to be specified value" | ||
| const external_events_namespaceObject = require("events"); | ||
| function toArr(any) { | ||
| return null == any ? [] : Array.isArray(any) ? any : [ | ||
| any | ||
| ]; | ||
| } | ||
| function toVal(out, key, val, opts) { | ||
| 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; | ||
| out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [ | ||
| old, | ||
| nxt | ||
| ]; | ||
| } | ||
| function mri2(args, opts) { | ||
| args = args || []; | ||
| opts = opts || {}; | ||
| var k, arr, arg, name, val, out = { | ||
| _: [] | ||
| }; | ||
| var i = 0, j = 0, idx = 0, len = args.length; | ||
| const alibi = void 0 !== opts.alias; | ||
| const strict = void 0 !== opts.unknown; | ||
| const defaults = void 0 !== opts.default; | ||
| opts.alias = opts.alias || {}; | ||
| opts.string = toArr(opts.string); | ||
| opts.boolean = toArr(opts.boolean); | ||
| if (alibi) for(k in opts.alias){ | ||
| arr = opts.alias[k] = toArr(opts.alias[k]); | ||
| for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); | ||
| } | ||
| for(i = opts.boolean.length; i-- > 0;){ | ||
| arr = opts.alias[opts.boolean[i]] || []; | ||
| for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]); | ||
| } | ||
| for(i = opts.string.length; i-- > 0;){ | ||
| arr = opts.alias[opts.string[i]] || []; | ||
| for(j = arr.length; j-- > 0;)opts.string.push(arr[j]); | ||
| } | ||
| if (defaults) for(k in opts.default){ | ||
| name = typeof opts.default[k]; | ||
| arr = opts.alias[k] = opts.alias[k] || []; | ||
| if (void 0 !== opts[name]) { | ||
| opts[name].push(k); | ||
| for(i = 0; i < arr.length; i++)opts[name].push(arr[i]); | ||
| } | ||
| }); | ||
| const commonOptionsForBuildAndServe = (yargs)=>yargs.options({ | ||
| entry: { | ||
| type: "array", | ||
| string: true, | ||
| describe: "entry file" | ||
| }, | ||
| outputPath: { | ||
| type: "string", | ||
| describe: "output path dir", | ||
| alias: "o" | ||
| }, | ||
| mode: { | ||
| type: "string", | ||
| describe: "mode", | ||
| alias: "m" | ||
| }, | ||
| watch: { | ||
| type: "boolean", | ||
| default: false, | ||
| describe: "watch", | ||
| alias: "w" | ||
| }, | ||
| env: { | ||
| type: "array", | ||
| string: true, | ||
| describe: "env passed to config function" | ||
| }, | ||
| devtool: { | ||
| type: "string", | ||
| describe: "Specify a developer tool for debugging. Defaults to `cheap-module-source-map` in development and `source-map` in production.", | ||
| alias: "d", | ||
| coerce: (arg)=>{ | ||
| if ("true" === arg) return "source-map"; | ||
| if ("false" === arg || "" === arg.trim()) return false; | ||
| return arg; | ||
| } | ||
| const keys = strict ? Object.keys(opts.alias) : []; | ||
| for(i = 0; i < len; i++){ | ||
| arg = args[i]; | ||
| if ('--' === arg) { | ||
| out._ = out._.concat(args.slice(++i)); | ||
| break; | ||
| } | ||
| for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++); | ||
| if (0 === j) out._.push(arg); | ||
| else if ('no-' === arg.substring(j, j + 3)) { | ||
| name = arg.substring(j + 3); | ||
| if (strict && !~keys.indexOf(name)) return opts.unknown(arg); | ||
| out[name] = false; | ||
| } else { | ||
| for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++); | ||
| name = arg.substring(j, idx); | ||
| val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i]; | ||
| arr = 2 === j ? [ | ||
| name | ||
| ] : name; | ||
| for(idx = 0; idx < arr.length; idx++){ | ||
| name = arr[idx]; | ||
| if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); | ||
| toVal(out, name, idx + 1 < arr.length || val, opts); | ||
| } | ||
| } | ||
| }).alias({ | ||
| v: "version", | ||
| h: "help" | ||
| }); | ||
| function normalizeEnv(argv) { | ||
| } | ||
| if (defaults) { | ||
| for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k]; | ||
| } | ||
| if (alibi) for(k in out){ | ||
| arr = opts.alias[k] || []; | ||
| while(arr.length > 0)out[arr.shift()] = out[k]; | ||
| } | ||
| return out; | ||
| } | ||
| const removeBrackets = (v)=>v.replace(/[<[].+/, "").trim(); | ||
| const findAllBrackets = (v)=>{ | ||
| const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; | ||
| const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; | ||
| const res = []; | ||
| const parse = (match)=>{ | ||
| let variadic = false; | ||
| let value = match[1]; | ||
| if (value.startsWith("...")) { | ||
| value = value.slice(3); | ||
| variadic = true; | ||
| } | ||
| return { | ||
| required: match[0].startsWith("<"), | ||
| value, | ||
| variadic | ||
| }; | ||
| }; | ||
| let angledMatch; | ||
| while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch)); | ||
| let squareMatch; | ||
| while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch)); | ||
| return res; | ||
| }; | ||
| const getMriOptions = (options)=>{ | ||
| const result = { | ||
| alias: {}, | ||
| boolean: [] | ||
| }; | ||
| for (const [index, option] of options.entries()){ | ||
| if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1); | ||
| if (option.isBoolean) if (option.negated) { | ||
| const hasStringTypeOption = options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required); | ||
| if (!hasStringTypeOption) result.boolean.push(option.names[0]); | ||
| } else result.boolean.push(option.names[0]); | ||
| } | ||
| return result; | ||
| }; | ||
| const findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0]; | ||
| const padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; | ||
| const camelcase = (input)=>input.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase()); | ||
| const setDotProp = (obj, keys, val)=>{ | ||
| let i = 0; | ||
| let length = keys.length; | ||
| let t = obj; | ||
| let x; | ||
| for(; i < length; ++i){ | ||
| x = t[keys[i]]; | ||
| t = t[keys[i]] = i === length - 1 ? val : null != x ? x : !~keys[i + 1].indexOf(".") && +keys[i + 1] > -1 ? [] : {}; | ||
| } | ||
| }; | ||
| const setByType = (obj, transforms)=>{ | ||
| for (const key of Object.keys(transforms)){ | ||
| const transform = transforms[key]; | ||
| if (transform.shouldTransform) { | ||
| obj[key] = Array.prototype.concat.call([], obj[key]); | ||
| if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction); | ||
| } | ||
| } | ||
| }; | ||
| const getFileName = (input)=>{ | ||
| const m = /([^\\\/]+)$/.exec(input); | ||
| return m ? m[1] : ""; | ||
| }; | ||
| const camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join("."); | ||
| class CACError extends Error { | ||
| constructor(message){ | ||
| super(message); | ||
| this.name = this.constructor.name; | ||
| if ("function" == typeof Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); | ||
| else this.stack = new Error(message).stack; | ||
| } | ||
| } | ||
| class Option { | ||
| constructor(rawName, description, config){ | ||
| this.rawName = rawName; | ||
| this.description = description; | ||
| this.config = Object.assign({}, config); | ||
| rawName = rawName.replace(/\.\*/g, ""); | ||
| this.negated = false; | ||
| this.names = removeBrackets(rawName).split(",").map((v)=>{ | ||
| let name = v.trim().replace(/^-{1,2}/, ""); | ||
| if (name.startsWith("no-")) { | ||
| this.negated = true; | ||
| name = name.replace(/^no-/, ""); | ||
| } | ||
| return camelcaseOptionName(name); | ||
| }).sort((a, b)=>a.length > b.length ? 1 : -1); | ||
| this.name = this.names[this.names.length - 1]; | ||
| if (this.negated && null == this.config.default) this.config.default = true; | ||
| if (rawName.includes("<")) this.required = true; | ||
| else if (rawName.includes("[")) this.required = false; | ||
| else this.isBoolean = true; | ||
| } | ||
| } | ||
| const processArgs = process.argv; | ||
| const platformInfo = `${process.platform}-${process.arch} node-${process.version}`; | ||
| class Command { | ||
| constructor(rawName, description, config = {}, cli){ | ||
| this.rawName = rawName; | ||
| this.description = description; | ||
| this.config = config; | ||
| this.cli = cli; | ||
| this.options = []; | ||
| this.aliasNames = []; | ||
| this.name = removeBrackets(rawName); | ||
| this.args = findAllBrackets(rawName); | ||
| this.examples = []; | ||
| } | ||
| usage(text) { | ||
| this.usageText = text; | ||
| return this; | ||
| } | ||
| allowUnknownOptions() { | ||
| this.config.allowUnknownOptions = true; | ||
| return this; | ||
| } | ||
| ignoreOptionDefaultValue() { | ||
| this.config.ignoreOptionDefaultValue = true; | ||
| return this; | ||
| } | ||
| version(version, customFlags = "-v, --version") { | ||
| this.versionNumber = version; | ||
| this.option(customFlags, "Display version number"); | ||
| return this; | ||
| } | ||
| example(example) { | ||
| this.examples.push(example); | ||
| return this; | ||
| } | ||
| option(rawName, description, config) { | ||
| const option = new Option(rawName, description, config); | ||
| this.options.push(option); | ||
| return this; | ||
| } | ||
| alias(name) { | ||
| this.aliasNames.push(name); | ||
| return this; | ||
| } | ||
| action(callback) { | ||
| this.commandAction = callback; | ||
| return this; | ||
| } | ||
| isMatched(name) { | ||
| return this.name === name || this.aliasNames.includes(name); | ||
| } | ||
| get isDefaultCommand() { | ||
| return "" === this.name || this.aliasNames.includes("!"); | ||
| } | ||
| get isGlobalCommand() { | ||
| return this instanceof GlobalCommand; | ||
| } | ||
| hasOption(name) { | ||
| name = name.split(".")[0]; | ||
| return this.options.find((option)=>option.names.includes(name)); | ||
| } | ||
| outputHelp() { | ||
| const { name, commands } = this.cli; | ||
| const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand; | ||
| let sections = [ | ||
| { | ||
| body: `${name}${versionNumber ? `/${versionNumber}` : ""}` | ||
| } | ||
| ]; | ||
| sections.push({ | ||
| title: "Usage", | ||
| body: ` $ ${name} ${this.usageText || this.rawName}` | ||
| }); | ||
| const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; | ||
| if (showCommands) { | ||
| const longestCommandName = findLongest(commands.map((command)=>command.rawName)); | ||
| sections.push({ | ||
| title: "Commands", | ||
| body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n") | ||
| }); | ||
| sections.push({ | ||
| title: "For more info, run any command with the `--help` flag", | ||
| body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n") | ||
| }); | ||
| } | ||
| let options = this.isGlobalCommand ? globalOptions : [ | ||
| ...this.options, | ||
| ...globalOptions || [] | ||
| ]; | ||
| if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name); | ||
| if (options.length > 0) { | ||
| const longestOptionName = findLongest(options.map((option)=>option.rawName)); | ||
| sections.push({ | ||
| title: "Options", | ||
| body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n") | ||
| }); | ||
| } | ||
| if (this.examples.length > 0) sections.push({ | ||
| title: "Examples", | ||
| body: this.examples.map((example)=>{ | ||
| if ("function" == typeof example) return example(name); | ||
| return example; | ||
| }).join("\n") | ||
| }); | ||
| if (helpCallback) sections = helpCallback(sections) || sections; | ||
| console.log(sections.map((section)=>section.title ? `${section.title}: | ||
| ${section.body}` : section.body).join("\n\n")); | ||
| } | ||
| outputVersion() { | ||
| const { name } = this.cli; | ||
| const { versionNumber } = this.cli.globalCommand; | ||
| if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`); | ||
| } | ||
| checkRequiredArgs() { | ||
| const minimalArgsCount = this.args.filter((arg)=>arg.required).length; | ||
| if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``); | ||
| } | ||
| checkUnknownOptions() { | ||
| const { options, globalCommand } = this.cli; | ||
| if (!this.config.allowUnknownOptions) { | ||
| 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}`}\``); | ||
| } | ||
| } | ||
| checkOptionValue() { | ||
| const { options: parsedOptions, globalCommand } = this.cli; | ||
| const options = [ | ||
| ...globalCommand.options, | ||
| ...this.options | ||
| ]; | ||
| for (const option of options){ | ||
| const value = parsedOptions[option.name.split(".")[0]]; | ||
| if (option.required) { | ||
| const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name)); | ||
| if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| class GlobalCommand extends Command { | ||
| constructor(cli){ | ||
| super("@@global@@", "", {}, cli); | ||
| } | ||
| } | ||
| var __assign = Object.assign; | ||
| class CAC extends external_events_namespaceObject.EventEmitter { | ||
| constructor(name = ""){ | ||
| super(); | ||
| this.name = name; | ||
| this.commands = []; | ||
| this.rawArgs = []; | ||
| this.args = []; | ||
| this.options = {}; | ||
| this.globalCommand = new GlobalCommand(this); | ||
| this.globalCommand.usage("<command> [options]"); | ||
| } | ||
| usage(text) { | ||
| this.globalCommand.usage(text); | ||
| return this; | ||
| } | ||
| command(rawName, description, config) { | ||
| const command = new Command(rawName, description || "", config, this); | ||
| command.globalCommand = this.globalCommand; | ||
| this.commands.push(command); | ||
| return command; | ||
| } | ||
| option(rawName, description, config) { | ||
| this.globalCommand.option(rawName, description, config); | ||
| return this; | ||
| } | ||
| help(callback) { | ||
| this.globalCommand.option("-h, --help", "Display this message"); | ||
| this.globalCommand.helpCallback = callback; | ||
| this.showHelpOnExit = true; | ||
| return this; | ||
| } | ||
| version(version, customFlags = "-v, --version") { | ||
| this.globalCommand.version(version, customFlags); | ||
| this.showVersionOnExit = true; | ||
| return this; | ||
| } | ||
| example(example) { | ||
| this.globalCommand.example(example); | ||
| return this; | ||
| } | ||
| outputHelp() { | ||
| if (this.matchedCommand) this.matchedCommand.outputHelp(); | ||
| else this.globalCommand.outputHelp(); | ||
| } | ||
| outputVersion() { | ||
| this.globalCommand.outputVersion(); | ||
| } | ||
| setParsedInfo({ args, options }, matchedCommand, matchedCommandName) { | ||
| this.args = args; | ||
| this.options = options; | ||
| if (matchedCommand) this.matchedCommand = matchedCommand; | ||
| if (matchedCommandName) this.matchedCommandName = matchedCommandName; | ||
| return this; | ||
| } | ||
| unsetMatchedCommand() { | ||
| this.matchedCommand = void 0; | ||
| this.matchedCommandName = void 0; | ||
| } | ||
| parse(argv = processArgs, { run = true } = {}) { | ||
| this.rawArgs = argv; | ||
| if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli"; | ||
| let shouldParse = true; | ||
| for (const command of this.commands){ | ||
| const parsed = this.mri(argv.slice(2), command); | ||
| const commandName = parsed.args[0]; | ||
| if (command.isMatched(commandName)) { | ||
| shouldParse = false; | ||
| const parsedInfo = __assign(__assign({}, parsed), { | ||
| args: parsed.args.slice(1) | ||
| }); | ||
| this.setParsedInfo(parsedInfo, command, commandName); | ||
| this.emit(`command:${commandName}`, command); | ||
| } | ||
| } | ||
| if (shouldParse) { | ||
| for (const command of this.commands)if ("" === command.name) { | ||
| shouldParse = false; | ||
| const parsed = this.mri(argv.slice(2), command); | ||
| this.setParsedInfo(parsed, command); | ||
| this.emit("command:!", command); | ||
| } | ||
| } | ||
| if (shouldParse) { | ||
| const parsed = this.mri(argv.slice(2)); | ||
| this.setParsedInfo(parsed); | ||
| } | ||
| if (this.options.help && this.showHelpOnExit) { | ||
| this.outputHelp(); | ||
| run = false; | ||
| this.unsetMatchedCommand(); | ||
| } | ||
| if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) { | ||
| this.outputVersion(); | ||
| run = false; | ||
| this.unsetMatchedCommand(); | ||
| } | ||
| const parsedArgv = { | ||
| args: this.args, | ||
| options: this.options | ||
| }; | ||
| if (run) this.runMatchedCommand(); | ||
| if (!this.matchedCommand && this.args[0]) this.emit("command:*"); | ||
| return parsedArgv; | ||
| } | ||
| mri(argv, command) { | ||
| const cliOptions = [ | ||
| ...this.globalCommand.options, | ||
| ...command ? command.options : [] | ||
| ]; | ||
| const mriOptions = getMriOptions(cliOptions); | ||
| let argsAfterDoubleDashes = []; | ||
| const doubleDashesIndex = argv.indexOf("--"); | ||
| if (doubleDashesIndex > -1) { | ||
| argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); | ||
| argv = argv.slice(0, doubleDashesIndex); | ||
| } | ||
| let parsed = mri2(argv, mriOptions); | ||
| parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), { | ||
| [camelcaseOptionName(name)]: parsed[name] | ||
| }), { | ||
| _: [] | ||
| }); | ||
| const args = parsed._; | ||
| const options = { | ||
| "--": argsAfterDoubleDashes | ||
| }; | ||
| const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; | ||
| let transforms = Object.create(null); | ||
| for (const cliOption of cliOptions){ | ||
| if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default; | ||
| if (Array.isArray(cliOption.config.type)) { | ||
| if (void 0 === transforms[cliOption.name]) { | ||
| transforms[cliOption.name] = Object.create(null); | ||
| transforms[cliOption.name]["shouldTransform"] = true; | ||
| transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; | ||
| } | ||
| } | ||
| } | ||
| for (const key of Object.keys(parsed))if ("_" !== key) { | ||
| const keys = key.split("."); | ||
| setDotProp(options, keys, parsed[key]); | ||
| setByType(options, transforms); | ||
| } | ||
| return { | ||
| args, | ||
| options | ||
| }; | ||
| } | ||
| runMatchedCommand() { | ||
| const { args, options, matchedCommand: command } = this; | ||
| if (!command || !command.commandAction) return; | ||
| command.checkUnknownOptions(); | ||
| command.checkOptionValue(); | ||
| command.checkRequiredArgs(); | ||
| const actionArgs = []; | ||
| command.args.forEach((arg, index)=>{ | ||
| if (arg.variadic) actionArgs.push(args.slice(index)); | ||
| else actionArgs.push(args[index]); | ||
| }); | ||
| actionArgs.push(options); | ||
| return command.commandAction.apply(this, actionArgs); | ||
| } | ||
| } | ||
| const cac = (name = "")=>new CAC(name); | ||
| const dist = cac; | ||
| var picocolors = __webpack_require__("../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"); | ||
| var external_node_fs_ = __webpack_require__("node:fs"); | ||
| var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_); | ||
| const commonOptions = (command)=>command.option("-c, --config <path>", "config file").option("--config-name <name>", "Name(s) of the configuration to use.", { | ||
| type: [ | ||
| String | ||
| ], | ||
| default: [] | ||
| }).option("--config-loader <loader>", "Specify the loader to load the config file, can be `native` or `register`.", { | ||
| default: "register" | ||
| }).option("--env <env>", "env passed to config function", { | ||
| type: [ | ||
| String | ||
| ], | ||
| default: [] | ||
| }).option("--node-env <value>", "sets `process.env.NODE_ENV` to be specified value"); | ||
| function normalizeDevtoolOption(value) { | ||
| if ("string" == typeof value) { | ||
| const trimmed = value.trim(); | ||
| if ("" === trimmed || "false" === trimmed) return false; | ||
| if ("true" === trimmed) return "source-map"; | ||
| return trimmed; | ||
| } | ||
| if ("boolean" == typeof value) return value ? "source-map" : false; | ||
| } | ||
| const normalizeCommonOptions = (options, action)=>{ | ||
| const isEmptyArray = (arr)=>Array.isArray(arr) && 0 === arr.length; | ||
| for (const key of [ | ||
| "entry", | ||
| "configName" | ||
| ]){ | ||
| const val = options[key]; | ||
| if (isEmptyArray(val)) options[key] = void 0; | ||
| } | ||
| const env = Array.isArray(options.env) ? normalizeEnvToObject(options) : {}; | ||
| options.env = env; | ||
| if ("serve" === action) setBuiltinEnvArg(env, "SERVE", true); | ||
| else if ("build" === action) if (options.watch) setBuiltinEnvArg(env, "WATCH", true); | ||
| else { | ||
| setBuiltinEnvArg(env, "BUNDLE", true); | ||
| setBuiltinEnvArg(env, "BUILD", true); | ||
| } | ||
| if ("devtool" in options) options.devtool = normalizeDevtoolOption(options.devtool); | ||
| }; | ||
| 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", { | ||
| type: [ | ||
| String | ||
| ], | ||
| default: [] | ||
| }).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"); | ||
| function setBuiltinEnvArg(env, envNameSuffix, value) { | ||
| const envName = `RSPACK_${envNameSuffix}`; | ||
| if (!(envName in env)) env[envName] = value; | ||
| } | ||
| function normalizeEnvToObject(options) { | ||
| function parseValue(previous, value) { | ||
@@ -214,151 +810,80 @@ const [allKeys, val] = value.split(/=(.+)/, 2); | ||
| } | ||
| const envObj = (argv.env ?? []).reduce(parseValue, {}); | ||
| argv.env = envObj; | ||
| return (options.env ?? []).reduce(parseValue, {}); | ||
| } | ||
| function setBuiltinEnvArg(env, envNameSuffix, value) { | ||
| const envNames = [ | ||
| `RSPACK_${envNameSuffix}` | ||
| ]; | ||
| for (const envName of envNames)if (!(envName in env)) env[envName] = value; | ||
| } | ||
| function ensureEnvObject(options) { | ||
| if (Array.isArray(options.env)) normalizeEnv(options); | ||
| options.env = options.env || {}; | ||
| return options.env; | ||
| } | ||
| function setDefaultNodeEnv(options, defaultEnv) { | ||
| if (void 0 !== process.env.NODE_ENV) return; | ||
| process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv; | ||
| if (void 0 === process.env.NODE_ENV) process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv; | ||
| } | ||
| class BuildCommand { | ||
| async apply(cli) { | ||
| cli.program.command([ | ||
| "build", | ||
| "$0", | ||
| "bundle", | ||
| "b" | ||
| ], "run the rspack build", (yargs)=>{ | ||
| commonOptionsForBuildAndServe(commonOptions(yargs)).options({ | ||
| analyze: { | ||
| type: "boolean", | ||
| default: false, | ||
| describe: "analyze" | ||
| }, | ||
| json: { | ||
| describe: "emit stats json" | ||
| }, | ||
| profile: { | ||
| type: "boolean", | ||
| default: false, | ||
| describe: "capture timing information for each module" | ||
| } | ||
| }); | ||
| }, async (options)=>{ | ||
| setDefaultNodeEnv(options, "production"); | ||
| const env = ensureEnvObject(options); | ||
| if (options.watch) setBuiltinEnvArg(env, "WATCH", true); | ||
| else { | ||
| setBuiltinEnvArg(env, "BUNDLE", true); | ||
| setBuiltinEnvArg(env, "BUILD", true); | ||
| } | ||
| const logger = cli.getLogger(); | ||
| let createJsonStringifyStream; | ||
| if (options.json) { | ||
| const jsonExt = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@discoveryjs/json-ext")); | ||
| createJsonStringifyStream = jsonExt.default.stringifyStream; | ||
| } | ||
| const errorHandler = (error, stats)=>{ | ||
| if (error) { | ||
| logger.error(error); | ||
| process.exit(2); | ||
| } | ||
| if (null == stats ? void 0 : stats.hasErrors()) process.exitCode = 1; | ||
| if (!compiler || !stats) return; | ||
| const statsOptions = cli.isMultipleCompiler(compiler) ? { | ||
| children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0) | ||
| } : compiler.options ? compiler.options.stats : void 0; | ||
| if (options.json && createJsonStringifyStream) { | ||
| const handleWriteError = (error)=>{ | ||
| logger.error(error); | ||
| process.exit(2); | ||
| }; | ||
| if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n")); | ||
| 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", ()=>{ | ||
| process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`); | ||
| }); | ||
| } else { | ||
| const printedStats = stats.toString(statsOptions); | ||
| if (printedStats) logger.raw(printedStats); | ||
| } | ||
| async function runBuild(cli, options) { | ||
| setDefaultNodeEnv(options, "production"); | ||
| normalizeCommonOptions(options, "build"); | ||
| const logger = cli.getLogger(); | ||
| let createJsonStringifyStream; | ||
| if (options.json) { | ||
| const jsonExt = await import("@discoveryjs/json-ext"); | ||
| createJsonStringifyStream = jsonExt.default.stringifyStream; | ||
| } | ||
| const errorHandler = (error, stats)=>{ | ||
| if (error) { | ||
| logger.error(error); | ||
| process.exit(2); | ||
| } | ||
| if (stats?.hasErrors()) process.exitCode = 1; | ||
| if (!compiler || !stats) return; | ||
| const getStatsOptions = ()=>{ | ||
| if (cli.isMultipleCompiler(compiler)) return { | ||
| children: compiler.compilers.map((item)=>item.options ? item.options.stats : void 0) | ||
| }; | ||
| const rspackOptions = { | ||
| ...options, | ||
| argv: { | ||
| ...options | ||
| } | ||
| return compiler.options?.stats; | ||
| }; | ||
| const statsOptions = getStatsOptions(); | ||
| if (options.json && createJsonStringifyStream) { | ||
| const handleWriteError = (error)=>{ | ||
| logger.error(error); | ||
| process.exit(2); | ||
| }; | ||
| const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler); | ||
| if (!compiler || cli.isWatch(compiler)) return; | ||
| compiler.run((error, stats)=>{ | ||
| compiler.close((closeErr)=>{ | ||
| if (closeErr) logger.error(closeErr); | ||
| errorHandler(error, stats); | ||
| }); | ||
| if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n")); | ||
| else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_default().createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{ | ||
| process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`); | ||
| }); | ||
| } else { | ||
| const printedStats = stats.toString(statsOptions); | ||
| if (printedStats) logger.raw(printedStats); | ||
| } | ||
| }; | ||
| const compiler = await cli.createCompiler(options, "build", errorHandler); | ||
| if (!compiler || cli.isWatch(compiler)) return; | ||
| compiler.run((error, stats)=>{ | ||
| compiler.close((closeErr)=>{ | ||
| if (closeErr) logger.error(closeErr); | ||
| errorHandler(error, stats); | ||
| }); | ||
| }); | ||
| } | ||
| class BuildCommand { | ||
| async apply(cli) { | ||
| const command = cli.program.command("", "run the Rspack build").alias("build").alias("bundle").alias("b"); | ||
| commonOptionsForBuildAndServe(commonOptions(command)).option("--json [path]", "emit stats json"); | ||
| command.action(async (options)=>{ | ||
| await runBuild(cli, options); | ||
| }); | ||
| } | ||
| } | ||
| const previewOptions = (yargs)=>{ | ||
| yargs.positional("dir", { | ||
| type: "string", | ||
| describe: "directory want to preview" | ||
| }); | ||
| return commonOptions(yargs).options({ | ||
| publicPath: { | ||
| type: "string", | ||
| describe: "static resource server path" | ||
| }, | ||
| port: { | ||
| type: "number", | ||
| describe: "preview server port" | ||
| }, | ||
| host: { | ||
| type: "string", | ||
| describe: "preview server host" | ||
| }, | ||
| open: { | ||
| type: "boolean", | ||
| describe: "open browser" | ||
| }, | ||
| server: { | ||
| type: "string", | ||
| describe: "Configuration items for the server." | ||
| } | ||
| }); | ||
| }; | ||
| const defaultRoot = "dist"; | ||
| var rspackCore = __webpack_require__("./src/utils/rspackCore.ts"); | ||
| class PreviewCommand { | ||
| async apply(cli) { | ||
| cli.program.command([ | ||
| "preview [dir]", | ||
| "preview", | ||
| "p" | ||
| ], "run the rspack server for build output", previewOptions, async (options)=>{ | ||
| const command = cli.program.command("preview [dir]", "run the Rspack server for build output").alias("p"); | ||
| 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."); | ||
| command.action(async (dir, options)=>{ | ||
| setDefaultNodeEnv(options, "production"); | ||
| const rspackOptions = { | ||
| ...options, | ||
| argv: { | ||
| ...options | ||
| } | ||
| }; | ||
| const { RspackDevServer } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@rspack/dev-server")); | ||
| let config = await cli.loadConfig(rspackOptions); | ||
| config = await getPreviewConfig(config, options); | ||
| normalizeCommonOptions(options, "preview"); | ||
| const { RspackDevServer } = await import("@rspack/dev-server"); | ||
| let { config } = await cli.loadConfig(options); | ||
| config = await getPreviewConfig(config, options, dir); | ||
| if (!Array.isArray(config)) config = [ | ||
| config | ||
| ]; | ||
| config = config.find((item)=>item.devServer) || config[0]; | ||
| const devServerOptions = config.devServer; | ||
| const singleConfig = config.find((item)=>item.devServer) || config[0]; | ||
| const devServerOptions = singleConfig.devServer; | ||
| try { | ||
| const compiler = (0, core_.rspack)({ | ||
| const compiler = (0, rspackCore.Z)({ | ||
| entry: {} | ||
@@ -377,16 +902,16 @@ }); | ||
| } | ||
| async function getPreviewConfig(item, options) { | ||
| async function getPreviewConfig(item, options, dir) { | ||
| const DEFAULT_ROOT = "dist"; | ||
| const internalPreviewConfig = async (item)=>{ | ||
| var _item_output, _item_devServer, _item_devServer1, _item_devServer2, _item_devServer3, _item_devServer4; | ||
| item.devServer = { | ||
| static: { | ||
| 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), | ||
| directory: dir ? external_node_path_default().join(item.context ?? process.cwd(), dir) : item.output?.path ?? external_node_path_default().join(item.context ?? process.cwd(), DEFAULT_ROOT), | ||
| publicPath: options.publicPath ?? "/" | ||
| }, | ||
| port: options.port ?? 8080, | ||
| proxy: null == (_item_devServer = item.devServer) ? void 0 : _item_devServer.proxy, | ||
| host: options.host ?? (null == (_item_devServer1 = item.devServer) ? void 0 : _item_devServer1.host), | ||
| open: options.open ?? (null == (_item_devServer2 = item.devServer) ? void 0 : _item_devServer2.open), | ||
| server: options.server ?? (null == (_item_devServer3 = item.devServer) ? void 0 : _item_devServer3.server), | ||
| historyApiFallback: null == (_item_devServer4 = item.devServer) ? void 0 : _item_devServer4.historyApiFallback | ||
| proxy: item.devServer?.proxy, | ||
| host: options.host ?? item.devServer?.host, | ||
| open: options.open ?? item.devServer?.open, | ||
| server: options.server ?? item.devServer?.server, | ||
| historyApiFallback: item.devServer?.historyApiFallback | ||
| }; | ||
@@ -398,38 +923,17 @@ return item; | ||
| } | ||
| function normalizeHotOption(value) { | ||
| if ("boolean" == typeof value || "only" === value) return value; | ||
| if ("false" === value) return false; | ||
| return true; | ||
| } | ||
| class ServeCommand { | ||
| async apply(cli) { | ||
| cli.program.command([ | ||
| "serve", | ||
| "server", | ||
| "s", | ||
| "dev" | ||
| ], "run the rspack dev server.", (yargs)=>commonOptionsForBuildAndServe(commonOptions(yargs)).options({ | ||
| hot: { | ||
| coerce: (arg)=>{ | ||
| if ("boolean" == typeof arg || "only" === arg) return arg; | ||
| if ("false" === arg) return false; | ||
| return true; | ||
| }, | ||
| describe: "enables hot module replacement" | ||
| }, | ||
| port: { | ||
| type: "number", | ||
| coerce: (arg)=>Number.isInteger(arg) ? arg : void 0, | ||
| describe: "allows to specify a port to use" | ||
| }, | ||
| host: { | ||
| type: "string", | ||
| describe: "allows to specify a hostname to use" | ||
| } | ||
| }), async (options)=>{ | ||
| const command = cli.program.command("serve", "run the rspack dev server.").alias("server").alias("s").alias("dev"); | ||
| 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"); | ||
| command.action(async (options)=>{ | ||
| setDefaultNodeEnv(options, "development"); | ||
| setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true); | ||
| const rspackOptions = { | ||
| ...options, | ||
| argv: { | ||
| ...options | ||
| } | ||
| }; | ||
| const { RspackDevServer } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@rspack/dev-server")); | ||
| const compiler = await cli.createCompiler(rspackOptions, "serve"); | ||
| normalizeCommonOptions(options, "serve"); | ||
| options.hot = normalizeHotOption(options.hot); | ||
| const { RspackDevServer } = await import("@rspack/dev-server"); | ||
| const compiler = await cli.createCompiler(options, "serve"); | ||
| if (!compiler) return; | ||
@@ -458,4 +962,4 @@ const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [ | ||
| const result = compilerForDevServer.options.devServer ??= {}; | ||
| const setupMiddlewares = result.setupMiddlewares; | ||
| const lazyCompileMiddleware = core_.rspack.experiments.lazyCompilationMiddleware(compiler); | ||
| const { setupMiddlewares } = result; | ||
| const lazyCompileMiddleware = rspackCore.Z.experiments.lazyCompilationMiddleware(compiler); | ||
| result.setupMiddlewares = (middlewares, server)=>{ | ||
@@ -465,4 +969,4 @@ let finalMiddlewares = middlewares; | ||
| return [ | ||
| lazyCompileMiddleware, | ||
| ...finalMiddlewares | ||
| ...finalMiddlewares, | ||
| lazyCompileMiddleware | ||
| ]; | ||
@@ -472,3 +976,3 @@ }; | ||
| result.host = options.host || result.host; | ||
| result.port = options.port || result.port; | ||
| result.port = options.port ?? result.port; | ||
| if (false !== result.client) { | ||
@@ -504,2 +1008,3 @@ if (true === result.client || null == result.client) result.client = {}; | ||
| } | ||
| var lib = __webpack_require__("../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js"); | ||
| const external_node_url_namespaceObject = require("node:url"); | ||
@@ -522,12 +1027,10 @@ const readPackageUp = (cwd = process.cwd())=>{ | ||
| const utils_readPackageUp = readPackageUp; | ||
| const isEsmFile = (filePath, cwd = process.cwd())=>{ | ||
| const ext = external_node_path_default().extname(filePath); | ||
| if (/\.(mjs|mts)$/.test(ext)) return true; | ||
| if (/\.(cjs|cts)/.test(ext)) return false; | ||
| const isEsmFile = (filePath)=>{ | ||
| if (/\.(mjs|mts)$/.test(filePath)) return true; | ||
| if (/\.(cjs|cts)$/.test(filePath)) return false; | ||
| const packageJson = utils_readPackageUp(external_node_path_default().dirname(filePath)); | ||
| return (null == packageJson ? void 0 : packageJson.type) === "module"; | ||
| return packageJson?.type === "module"; | ||
| }; | ||
| const utils_isEsmFile = isEsmFile; | ||
| const crossImport = async (path, cwd = process.cwd())=>{ | ||
| if (utils_isEsmFile(path, cwd)) { | ||
| const crossImport = async (path)=>{ | ||
| if (isEsmFile(path)) { | ||
| const url = (0, external_node_url_namespaceObject.pathToFileURL)(path).href; | ||
@@ -551,25 +1054,55 @@ const { default: config } = await import(url); | ||
| const utils_findConfig = findConfig; | ||
| const isTsFile_isTsFile = (configPath)=>{ | ||
| const TS_EXTENSION = [ | ||
| ".ts", | ||
| ".cts", | ||
| ".mts" | ||
| ]; | ||
| const isTsFile = (configPath)=>{ | ||
| const ext = external_node_path_default().extname(configPath); | ||
| return /\.(c|m)?ts$/.test(ext); | ||
| return TS_EXTENSION.includes(ext); | ||
| }; | ||
| const isTsFile = isTsFile_isTsFile; | ||
| const utils_isTsFile = isTsFile; | ||
| const injectInlineSourceMap = ({ code, map })=>{ | ||
| if (map) { | ||
| const base64Map = Buffer.from(map, "utf8").toString("base64"); | ||
| const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`; | ||
| return `${code}\n${sourceMapContent}`; | ||
| } | ||
| return code; | ||
| }; | ||
| function compile(sourcecode, filename) { | ||
| const { code, map } = rspackCore.Z.experiments.swc.transformSync(sourcecode, { | ||
| jsc: { | ||
| parser: { | ||
| syntax: "typescript", | ||
| tsx: false, | ||
| decorators: true, | ||
| dynamicImport: true | ||
| } | ||
| }, | ||
| filename: filename, | ||
| module: { | ||
| type: "commonjs" | ||
| }, | ||
| sourceMaps: true, | ||
| isModule: true | ||
| }); | ||
| return injectInlineSourceMap({ | ||
| code, | ||
| map | ||
| }); | ||
| } | ||
| const loadConfig_DEFAULT_CONFIG_NAME = "rspack.config"; | ||
| const registerLoader = async (configPath)=>{ | ||
| const ext = external_node_path_default().extname(configPath); | ||
| if (utils_isEsmFile(configPath) && isTsFile(configPath)) return; | ||
| const { default: interpret } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "interpret")); | ||
| const extensions = Object.fromEntries(Object.entries(interpret.extensions).filter(([key])=>key === ext)); | ||
| if (0 === Object.keys(extensions).length) throw new Error(`config file "${configPath}" is not supported.`); | ||
| try { | ||
| const { default: rechoir } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "rechoir")); | ||
| rechoir.prepare(extensions, configPath); | ||
| } catch (error) { | ||
| const failures = null == error ? void 0 : error.failures; | ||
| if (failures) { | ||
| const messages = failures.map((failure)=>failure.error.message); | ||
| throw new Error(`${messages.join("\n")}`); | ||
| const registerLoader = (configPath)=>{ | ||
| if (isEsmFile(configPath) && utils_isTsFile(configPath)) return; | ||
| if (!utils_isTsFile(configPath)) throw new Error(`config file "${configPath}" is not supported.`); | ||
| (0, lib.addHook)((code, filename)=>{ | ||
| try { | ||
| return compile(code, filename); | ||
| } catch (err) { | ||
| throw new Error(`Failed to transform file "${filename}" when loading TypeScript config file:\n ${err instanceof Error ? err.message : String(err)}`); | ||
| } | ||
| throw error; | ||
| } | ||
| }, { | ||
| exts: TS_EXTENSION | ||
| }); | ||
| }; | ||
@@ -579,7 +1112,22 @@ const checkIsMultiRspackOptions = (config)=>Array.isArray(config); | ||
| if (checkIsMultiRspackOptions(config)) { | ||
| const extendedConfigs = await Promise.all(config.map((item)=>loadExtendedConfig(item, configPath, cwd, options))); | ||
| const resultPathMap = new WeakMap(); | ||
| const extendedConfigs = await Promise.all(config.map(async (item)=>{ | ||
| const { config, pathMap } = await loadExtendedConfig(item, configPath, cwd, options); | ||
| resultPathMap.set(config, pathMap.get(config)); | ||
| return config; | ||
| })); | ||
| extendedConfigs.parallelism = config.parallelism; | ||
| return extendedConfigs; | ||
| return { | ||
| config: extendedConfigs, | ||
| pathMap: resultPathMap | ||
| }; | ||
| } | ||
| if (!("extends" in config) || !config.extends) return config; | ||
| const pathMap = new WeakMap(); | ||
| pathMap.set(config, [ | ||
| configPath | ||
| ]); | ||
| if (!("extends" in config) || !config.extends) return { | ||
| config, | ||
| pathMap | ||
| }; | ||
| const extendsList = Array.isArray(config.extends) ? config.extends : [ | ||
@@ -591,2 +1139,5 @@ config.extends | ||
| let resultConfig = configWithoutExtends; | ||
| pathMap.set(resultConfig, [ | ||
| configPath | ||
| ]); | ||
| for (const extendPath of extendsList){ | ||
@@ -612,53 +1163,58 @@ let resolvedPath; | ||
| if (!external_node_fs_default().existsSync(resolvedPath)) throw new Error(`Extended configuration file "${resolvedPath}" not found.`); | ||
| if (isTsFile(resolvedPath) && "register" === options.configLoader) await registerLoader(resolvedPath); | ||
| let extendedConfig = await crossImport(resolvedPath, cwd); | ||
| if ("function" == typeof extendedConfig) { | ||
| var _options_argv; | ||
| extendedConfig = extendedConfig(null == (_options_argv = options.argv) ? void 0 : _options_argv.env, options.argv); | ||
| if ("function" == typeof extendedConfig.then) extendedConfig = await extendedConfig; | ||
| if (utils_isTsFile(resolvedPath) && "register" === options.configLoader) registerLoader(resolvedPath); | ||
| let loadedConfig = await crossImport(resolvedPath); | ||
| if ("function" == typeof loadedConfig) { | ||
| loadedConfig = loadedConfig(options.env, options); | ||
| if ("function" == typeof loadedConfig.then) loadedConfig = await loadedConfig; | ||
| } | ||
| extendedConfig = await loadExtendedConfig(extendedConfig, resolvedPath, cwd, options); | ||
| resultConfig = core_.util.cleverMerge(extendedConfig, resultConfig); | ||
| const { config: extendedConfig, pathMap: extendedPathMap } = await loadExtendedConfig(loadedConfig, resolvedPath, cwd, options); | ||
| const configPaths = [ | ||
| ...pathMap.get(resultConfig) || [], | ||
| ...extendedPathMap.get(extendedConfig) || [] | ||
| ]; | ||
| resultConfig = rspackCore.Z.util.cleverMerge(extendedConfig, resultConfig); | ||
| pathMap.set(resultConfig, configPaths); | ||
| } | ||
| return resultConfig; | ||
| return { | ||
| config: resultConfig, | ||
| pathMap | ||
| }; | ||
| } | ||
| async function loadRspackConfig(options, cwd = process.cwd()) { | ||
| let configPath; | ||
| let loadedConfig; | ||
| let configPath = ""; | ||
| if (options.config) { | ||
| configPath = external_node_path_default().resolve(cwd, options.config); | ||
| if (!external_node_fs_default().existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`); | ||
| if (isTsFile(configPath) && "register" === options.configLoader) await registerLoader(configPath); | ||
| loadedConfig = await crossImport(configPath, cwd); | ||
| } else { | ||
| const defaultConfig = utils_findConfig(external_node_path_default().resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME)); | ||
| if (!defaultConfig) return {}; | ||
| if (!defaultConfig) return null; | ||
| configPath = defaultConfig; | ||
| if (isTsFile(defaultConfig) && "register" === options.configLoader) await registerLoader(defaultConfig); | ||
| loadedConfig = await crossImport(defaultConfig, cwd); | ||
| } | ||
| if ("function" != typeof loadedConfig && configPath) loadedConfig = await loadExtendedConfig(loadedConfig, configPath, cwd, options); | ||
| return loadedConfig; | ||
| if (utils_isTsFile(configPath) && "register" === options.configLoader) registerLoader(configPath); | ||
| const loadedConfig = await crossImport(configPath); | ||
| return { | ||
| loadedConfig, | ||
| configPath | ||
| }; | ||
| } | ||
| function _define_property(obj, key, value) { | ||
| if (key in obj) Object.defineProperty(obj, key, { | ||
| value: value, | ||
| enumerable: true, | ||
| configurable: true, | ||
| writable: true | ||
| }); | ||
| else obj[key] = value; | ||
| return obj; | ||
| } | ||
| class RspackCLI { | ||
| colors; | ||
| program; | ||
| constructor(){ | ||
| const program = dist("rspack"); | ||
| this.colors = this.createColors(); | ||
| this.program = program; | ||
| program.help(); | ||
| program.version("1.6.2"); | ||
| } | ||
| async createCompiler(options, rspackCommand, callback) { | ||
| process.env.RSPACK_CONFIG_VALIDATE ??= "loose"; | ||
| let config = await this.loadConfig(options); | ||
| config = await this.buildConfig(config, options, rspackCommand); | ||
| let { config, pathMap } = await this.loadConfig(options); | ||
| config = await this.buildConfig(config, pathMap, options, rspackCommand); | ||
| const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch; | ||
| let compiler; | ||
| try { | ||
| compiler = (0, core_.rspack)(config, isWatch ? callback : void 0); | ||
| compiler = (0, rspackCore.Z)(config, isWatch ? callback : void 0); | ||
| if (!isWatch && compiler) compiler.unsafeFastDrop = true; | ||
| } catch (e) { | ||
| if (e instanceof core_.ValidationError) { | ||
| if (e instanceof rspackCore.Z.ValidationError) { | ||
| this.getLogger().error(e.message); | ||
@@ -676,7 +1232,5 @@ process.exit(2); | ||
| createColors(useColor) { | ||
| const shouldUseColor = useColor || external_colorette_namespaceObject.isColorSupported; | ||
| const shouldUseColor = useColor || picocolors.isColorSupported; | ||
| return { | ||
| ...(0, external_colorette_namespaceObject.createColors)({ | ||
| useColor: shouldUseColor | ||
| }), | ||
| ...(0, picocolors.createColors)(shouldUseColor), | ||
| isColorSupported: shouldUseColor | ||
@@ -696,9 +1250,4 @@ }; | ||
| async run(argv) { | ||
| this.program.showHelpOnFail(false); | ||
| this.program.usage("[options]"); | ||
| this.program.scriptName("rspack"); | ||
| this.program.strictCommands(true).strict(true); | ||
| this.program.middleware(normalizeEnv); | ||
| this.registerCommands(); | ||
| await this.program.parseAsync((0, helpers_namespaceObject.hideBin)(argv)); | ||
| await this.registerCommands(); | ||
| this.program.parse(argv); | ||
| } | ||
@@ -711,5 +1260,5 @@ async registerCommands() { | ||
| ]; | ||
| for (const command of builtinCommands)command.apply(this); | ||
| for (const command of builtinCommands)await command.apply(this); | ||
| } | ||
| async buildConfig(item, options, command) { | ||
| async buildConfig(item, pathMap, options, command) { | ||
| const isBuild = "build" === command; | ||
@@ -724,3 +1273,3 @@ const isServe = "serve" === command; | ||
| if (options.analyze) { | ||
| const { BundleAnalyzerPlugin } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "webpack-bundle-analyzer")); | ||
| const { BundleAnalyzerPlugin } = await import("webpack-bundle-analyzer"); | ||
| (item.plugins ??= []).push({ | ||
@@ -737,3 +1286,3 @@ name: "rspack-bundle-analyzer", | ||
| if (process.env.RSPACK_PROFILE) { | ||
| const { applyProfile } = await __webpack_require__.e("556").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts")); | ||
| const { applyProfile } = await __webpack_require__.e("361").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts")); | ||
| await applyProfile(process.env.RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT); | ||
@@ -747,5 +1296,13 @@ } | ||
| if (isServe) { | ||
| const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin); | ||
| if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin()); | ||
| const installed = (item.plugins ||= []).find((item)=>item instanceof rspackCore.Z.ProgressPlugin); | ||
| if (!installed) (item.plugins ??= []).push(new rspackCore.Z.ProgressPlugin()); | ||
| } | ||
| const cacheOptions = item.experiments?.cache; | ||
| if ("object" == typeof cacheOptions && "persistent" === cacheOptions.type) { | ||
| const configPaths = pathMap.get(item); | ||
| if (configPaths) cacheOptions.buildDependencies = [ | ||
| ...configPaths, | ||
| ...cacheOptions.buildDependencies || [] | ||
| ]; | ||
| } | ||
| if (void 0 === item.stats) item.stats = { | ||
@@ -770,18 +1327,25 @@ preset: "errors-warnings", | ||
| async loadConfig(options) { | ||
| let loadedConfig = await loadRspackConfig(options); | ||
| const config = await loadRspackConfig(options); | ||
| if (!config) return { | ||
| config: this.filterConfig(options, {}), | ||
| pathMap: new WeakMap() | ||
| }; | ||
| let { loadedConfig, configPath } = config; | ||
| if ("function" == typeof loadedConfig) { | ||
| var _options_argv; | ||
| let functionResult = loadedConfig(null == (_options_argv = options.argv) ? void 0 : _options_argv.env, options.argv); | ||
| let functionResult = loadedConfig(options.env, options); | ||
| if ("function" == typeof functionResult.then) functionResult = await functionResult; | ||
| loadedConfig = functionResult; | ||
| if ("extends" in loadedConfig && loadedConfig.extends) { | ||
| const tempConfigPath = external_node_path_default().resolve(process.cwd(), "rspack.config.js"); | ||
| loadedConfig = await loadExtendedConfig(loadedConfig, tempConfigPath, process.cwd(), options); | ||
| } | ||
| } | ||
| const { config: extendedConfig, pathMap } = await loadExtendedConfig(loadedConfig, configPath, process.cwd(), options); | ||
| return { | ||
| config: this.filterConfig(options, extendedConfig), | ||
| pathMap | ||
| }; | ||
| } | ||
| filterConfig(options, config) { | ||
| if (options.configName) { | ||
| const notFoundConfigNames = []; | ||
| loadedConfig = options.configName.map((configName)=>{ | ||
| config = options.configName.map((configName)=>{ | ||
| let found; | ||
| found = Array.isArray(loadedConfig) ? loadedConfig.find((options)=>options.name === configName) : loadedConfig.name === configName ? loadedConfig : void 0; | ||
| found = Array.isArray(config) ? config.find((options)=>options.name === configName) : config.name === configName ? config : void 0; | ||
| if (!found) notFoundConfigNames.push(configName); | ||
@@ -795,3 +1359,3 @@ return found; | ||
| } | ||
| return loadedConfig; | ||
| return config; | ||
| } | ||
@@ -804,8 +1368,2 @@ isMultipleCompiler(compiler) { | ||
| } | ||
| constructor(){ | ||
| _define_property(this, "colors", void 0); | ||
| _define_property(this, "program", void 0); | ||
| this.colors = this.createColors(); | ||
| this.program = external_yargs_default()(); | ||
| } | ||
| } | ||
@@ -812,0 +1370,0 @@ function defineConfig(config) { |
+928
-347
@@ -1,13 +0,146 @@ | ||
| import * as __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__ from "@rspack/core"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path"; | ||
| import node_util from "node:util"; | ||
| import { createColors, isColorSupported } from "colorette"; | ||
| import yargs_0 from "yargs"; | ||
| import { hideBin } from "yargs/helpers"; | ||
| import { pathToFileURL } from "node:url"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_events__ from "events"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__ from "node:module"; | ||
| import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url"; | ||
| var __webpack_modules__ = { | ||
| "@rspack/core": function(module) { | ||
| module.exports = __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__; | ||
| "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js": function(module) { | ||
| let p = process || {}, argv = p.argv || [], env = p.env || {}; | ||
| 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); | ||
| let formatter = (open, close, replace = open)=>(input)=>{ | ||
| let string = "" + input, index = string.indexOf(close, open.length); | ||
| return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close; | ||
| }; | ||
| let replaceClose = (string, close, replace, index)=>{ | ||
| let result = "", cursor = 0; | ||
| do { | ||
| result += string.substring(cursor, index) + replace; | ||
| cursor = index + close.length; | ||
| index = string.indexOf(close, cursor); | ||
| }while (~index); | ||
| return result + string.substring(cursor); | ||
| }; | ||
| let createColors = (enabled = isColorSupported)=>{ | ||
| let f = enabled ? formatter : ()=>String; | ||
| return { | ||
| isColorSupported: enabled, | ||
| reset: f("\x1b[0m", "\x1b[0m"), | ||
| bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), | ||
| dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), | ||
| italic: f("\x1b[3m", "\x1b[23m"), | ||
| underline: f("\x1b[4m", "\x1b[24m"), | ||
| inverse: f("\x1b[7m", "\x1b[27m"), | ||
| hidden: f("\x1b[8m", "\x1b[28m"), | ||
| strikethrough: f("\x1b[9m", "\x1b[29m"), | ||
| black: f("\x1b[30m", "\x1b[39m"), | ||
| red: f("\x1b[31m", "\x1b[39m"), | ||
| green: f("\x1b[32m", "\x1b[39m"), | ||
| yellow: f("\x1b[33m", "\x1b[39m"), | ||
| blue: f("\x1b[34m", "\x1b[39m"), | ||
| magenta: f("\x1b[35m", "\x1b[39m"), | ||
| cyan: f("\x1b[36m", "\x1b[39m"), | ||
| white: f("\x1b[37m", "\x1b[39m"), | ||
| gray: f("\x1b[90m", "\x1b[39m"), | ||
| bgBlack: f("\x1b[40m", "\x1b[49m"), | ||
| bgRed: f("\x1b[41m", "\x1b[49m"), | ||
| bgGreen: f("\x1b[42m", "\x1b[49m"), | ||
| bgYellow: f("\x1b[43m", "\x1b[49m"), | ||
| bgBlue: f("\x1b[44m", "\x1b[49m"), | ||
| bgMagenta: f("\x1b[45m", "\x1b[49m"), | ||
| bgCyan: f("\x1b[46m", "\x1b[49m"), | ||
| bgWhite: f("\x1b[47m", "\x1b[49m"), | ||
| blackBright: f("\x1b[90m", "\x1b[39m"), | ||
| redBright: f("\x1b[91m", "\x1b[39m"), | ||
| greenBright: f("\x1b[92m", "\x1b[39m"), | ||
| yellowBright: f("\x1b[93m", "\x1b[39m"), | ||
| blueBright: f("\x1b[94m", "\x1b[39m"), | ||
| magentaBright: f("\x1b[95m", "\x1b[39m"), | ||
| cyanBright: f("\x1b[96m", "\x1b[39m"), | ||
| whiteBright: f("\x1b[97m", "\x1b[39m"), | ||
| bgBlackBright: f("\x1b[100m", "\x1b[49m"), | ||
| bgRedBright: f("\x1b[101m", "\x1b[49m"), | ||
| bgGreenBright: f("\x1b[102m", "\x1b[49m"), | ||
| bgYellowBright: f("\x1b[103m", "\x1b[49m"), | ||
| bgBlueBright: f("\x1b[104m", "\x1b[49m"), | ||
| bgMagentaBright: f("\x1b[105m", "\x1b[49m"), | ||
| bgCyanBright: f("\x1b[106m", "\x1b[49m"), | ||
| bgWhiteBright: f("\x1b[107m", "\x1b[49m") | ||
| }; | ||
| }; | ||
| module.exports = createColors(); | ||
| module.exports.createColors = createColors; | ||
| }, | ||
| "../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js": function(module, exports, __webpack_require__) { | ||
| module = __webpack_require__.nmd(module); | ||
| const BuiltinModule = __webpack_require__("module"); | ||
| const path = __webpack_require__("path"); | ||
| const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/; | ||
| const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule; | ||
| 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."; | ||
| function shouldCompile(filename, exts, matcher, ignoreNodeModules) { | ||
| if ('string' != typeof filename) return false; | ||
| if (-1 === exts.indexOf(path.extname(filename))) return false; | ||
| const resolvedFilename = path.resolve(filename); | ||
| if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) return false; | ||
| if (matcher && 'function' == typeof matcher) return !!matcher(resolvedFilename); | ||
| return true; | ||
| } | ||
| function addHook(hook, opts = {}) { | ||
| let reverted = false; | ||
| const loaders = []; | ||
| const oldLoaders = []; | ||
| let exts; | ||
| const originalJSLoader = Module._extensions['.js']; | ||
| const matcher = opts.matcher || null; | ||
| const ignoreNodeModules = false !== opts.ignoreNodeModules; | ||
| exts = opts.extensions || opts.exts || opts.extension || opts.ext || [ | ||
| '.js' | ||
| ]; | ||
| if (!Array.isArray(exts)) exts = [ | ||
| exts | ||
| ]; | ||
| exts.forEach((ext)=>{ | ||
| if ('string' != typeof ext) throw new TypeError(`Invalid Extension: ${ext}`); | ||
| const oldLoader = Module._extensions[ext] || originalJSLoader; | ||
| oldLoaders[ext] = Module._extensions[ext]; | ||
| loaders[ext] = Module._extensions[ext] = function(mod, filename) { | ||
| let compile; | ||
| if (!reverted) { | ||
| if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) { | ||
| compile = mod._compile; | ||
| mod._compile = function(code) { | ||
| mod._compile = compile; | ||
| const newCode = hook(code, filename); | ||
| if ('string' != typeof newCode) throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE); | ||
| return mod._compile(newCode, filename); | ||
| }; | ||
| } | ||
| } | ||
| oldLoader(mod, filename); | ||
| }; | ||
| }); | ||
| return function() { | ||
| if (reverted) return; | ||
| reverted = true; | ||
| exts.forEach((ext)=>{ | ||
| if (Module._extensions[ext] === loaders[ext]) if (oldLoaders[ext]) Module._extensions[ext] = oldLoaders[ext]; | ||
| else delete Module._extensions[ext]; | ||
| }); | ||
| }; | ||
| } | ||
| exports.addHook = addHook; | ||
| }, | ||
| "./src/utils/rspackCore.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| Z: ()=>rspack | ||
| }); | ||
| const rspackCore_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__.createRequire)(import.meta.url); | ||
| const rspack = rspackCore_require("@rspack/core"); | ||
| }, | ||
| module: function(module) { | ||
| module.exports = __WEBPACK_EXTERNAL_MODULE_module__; | ||
| }, | ||
| "node:fs": function(module) { | ||
@@ -18,2 +151,5 @@ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__; | ||
| module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__; | ||
| }, | ||
| path: function(module) { | ||
| module.exports = __WEBPACK_EXTERNAL_MODULE_path__; | ||
| } | ||
@@ -26,5 +162,8 @@ }; | ||
| var module = __webpack_module_cache__[moduleId] = { | ||
| id: moduleId, | ||
| loaded: false, | ||
| exports: {} | ||
| }; | ||
| __webpack_modules__[moduleId](module, module.exports, __webpack_require__); | ||
| module.loaded = true; | ||
| return module.exports; | ||
@@ -49,3 +188,3 @@ } | ||
| (()=>{ | ||
| __webpack_require__.u = (chunkId)=>"" + chunkId + ".mjs"; | ||
| __webpack_require__.u = (chunkId)=>"1~" + chunkId + ".mjs"; | ||
| })(); | ||
@@ -56,4 +195,11 @@ (()=>{ | ||
| (()=>{ | ||
| __webpack_require__.nmd = (module)=>{ | ||
| module.paths = []; | ||
| if (!module.children) module.children = []; | ||
| return module; | ||
| }; | ||
| })(); | ||
| (()=>{ | ||
| var installedChunks = { | ||
| 980: 0 | ||
| 410: 0 | ||
| }; | ||
@@ -94,68 +240,541 @@ var installChunk = (data)=>{ | ||
| var external_node_path_ = __webpack_require__("node:path"); | ||
| var core_ = __webpack_require__("@rspack/core"); | ||
| var external_node_fs_ = __webpack_require__("node:fs"); | ||
| const commonOptions = (yargs)=>yargs.options({ | ||
| config: { | ||
| g: true, | ||
| type: "string", | ||
| describe: "config file", | ||
| alias: "c" | ||
| }, | ||
| configName: { | ||
| type: "array", | ||
| string: true, | ||
| describe: "Name of the configuration to use." | ||
| }, | ||
| configLoader: { | ||
| type: "string", | ||
| default: "register", | ||
| describe: "Specify the loader to load the config file, can be `native` or `register`." | ||
| }, | ||
| nodeEnv: { | ||
| string: true, | ||
| describe: "sets `process.env.NODE_ENV` to be specified value" | ||
| function toArr(any) { | ||
| return null == any ? [] : Array.isArray(any) ? any : [ | ||
| any | ||
| ]; | ||
| } | ||
| function toVal(out, key, val, opts) { | ||
| 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; | ||
| out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [ | ||
| old, | ||
| nxt | ||
| ]; | ||
| } | ||
| function mri2(args, opts) { | ||
| args = args || []; | ||
| opts = opts || {}; | ||
| var k, arr, arg, name, val, out = { | ||
| _: [] | ||
| }; | ||
| var i = 0, j = 0, idx = 0, len = args.length; | ||
| const alibi = void 0 !== opts.alias; | ||
| const strict = void 0 !== opts.unknown; | ||
| const defaults = void 0 !== opts.default; | ||
| opts.alias = opts.alias || {}; | ||
| opts.string = toArr(opts.string); | ||
| opts.boolean = toArr(opts.boolean); | ||
| if (alibi) for(k in opts.alias){ | ||
| arr = opts.alias[k] = toArr(opts.alias[k]); | ||
| for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); | ||
| } | ||
| for(i = opts.boolean.length; i-- > 0;){ | ||
| arr = opts.alias[opts.boolean[i]] || []; | ||
| for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]); | ||
| } | ||
| for(i = opts.string.length; i-- > 0;){ | ||
| arr = opts.alias[opts.string[i]] || []; | ||
| for(j = arr.length; j-- > 0;)opts.string.push(arr[j]); | ||
| } | ||
| if (defaults) for(k in opts.default){ | ||
| name = typeof opts.default[k]; | ||
| arr = opts.alias[k] = opts.alias[k] || []; | ||
| if (void 0 !== opts[name]) { | ||
| opts[name].push(k); | ||
| for(i = 0; i < arr.length; i++)opts[name].push(arr[i]); | ||
| } | ||
| }); | ||
| const commonOptionsForBuildAndServe = (yargs)=>yargs.options({ | ||
| entry: { | ||
| type: "array", | ||
| string: true, | ||
| describe: "entry file" | ||
| }, | ||
| outputPath: { | ||
| type: "string", | ||
| describe: "output path dir", | ||
| alias: "o" | ||
| }, | ||
| mode: { | ||
| type: "string", | ||
| describe: "mode", | ||
| alias: "m" | ||
| }, | ||
| watch: { | ||
| type: "boolean", | ||
| default: false, | ||
| describe: "watch", | ||
| alias: "w" | ||
| }, | ||
| env: { | ||
| type: "array", | ||
| string: true, | ||
| describe: "env passed to config function" | ||
| }, | ||
| devtool: { | ||
| type: "string", | ||
| describe: "Specify a developer tool for debugging. Defaults to `cheap-module-source-map` in development and `source-map` in production.", | ||
| alias: "d", | ||
| coerce: (arg)=>{ | ||
| if ("true" === arg) return "source-map"; | ||
| if ("false" === arg || "" === arg.trim()) return false; | ||
| return arg; | ||
| } | ||
| const keys = strict ? Object.keys(opts.alias) : []; | ||
| for(i = 0; i < len; i++){ | ||
| arg = args[i]; | ||
| if ('--' === arg) { | ||
| out._ = out._.concat(args.slice(++i)); | ||
| break; | ||
| } | ||
| for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++); | ||
| if (0 === j) out._.push(arg); | ||
| else if ('no-' === arg.substring(j, j + 3)) { | ||
| name = arg.substring(j + 3); | ||
| if (strict && !~keys.indexOf(name)) return opts.unknown(arg); | ||
| out[name] = false; | ||
| } else { | ||
| for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++); | ||
| name = arg.substring(j, idx); | ||
| val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i]; | ||
| arr = 2 === j ? [ | ||
| name | ||
| ] : name; | ||
| for(idx = 0; idx < arr.length; idx++){ | ||
| name = arr[idx]; | ||
| if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); | ||
| toVal(out, name, idx + 1 < arr.length || val, opts); | ||
| } | ||
| } | ||
| }).alias({ | ||
| v: "version", | ||
| h: "help" | ||
| }); | ||
| function normalizeEnv(argv) { | ||
| } | ||
| if (defaults) { | ||
| for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k]; | ||
| } | ||
| if (alibi) for(k in out){ | ||
| arr = opts.alias[k] || []; | ||
| while(arr.length > 0)out[arr.shift()] = out[k]; | ||
| } | ||
| return out; | ||
| } | ||
| const removeBrackets = (v)=>v.replace(/[<[].+/, "").trim(); | ||
| const findAllBrackets = (v)=>{ | ||
| const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; | ||
| const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; | ||
| const res = []; | ||
| const parse = (match)=>{ | ||
| let variadic = false; | ||
| let value = match[1]; | ||
| if (value.startsWith("...")) { | ||
| value = value.slice(3); | ||
| variadic = true; | ||
| } | ||
| return { | ||
| required: match[0].startsWith("<"), | ||
| value, | ||
| variadic | ||
| }; | ||
| }; | ||
| let angledMatch; | ||
| while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch)); | ||
| let squareMatch; | ||
| while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch)); | ||
| return res; | ||
| }; | ||
| const getMriOptions = (options)=>{ | ||
| const result = { | ||
| alias: {}, | ||
| boolean: [] | ||
| }; | ||
| for (const [index, option] of options.entries()){ | ||
| if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1); | ||
| if (option.isBoolean) if (option.negated) { | ||
| const hasStringTypeOption = options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required); | ||
| if (!hasStringTypeOption) result.boolean.push(option.names[0]); | ||
| } else result.boolean.push(option.names[0]); | ||
| } | ||
| return result; | ||
| }; | ||
| const findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0]; | ||
| const padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; | ||
| const camelcase = (input)=>input.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase()); | ||
| const setDotProp = (obj, keys, val)=>{ | ||
| let i = 0; | ||
| let length = keys.length; | ||
| let t = obj; | ||
| let x; | ||
| for(; i < length; ++i){ | ||
| x = t[keys[i]]; | ||
| t = t[keys[i]] = i === length - 1 ? val : null != x ? x : !~keys[i + 1].indexOf(".") && +keys[i + 1] > -1 ? [] : {}; | ||
| } | ||
| }; | ||
| const setByType = (obj, transforms)=>{ | ||
| for (const key of Object.keys(transforms)){ | ||
| const transform = transforms[key]; | ||
| if (transform.shouldTransform) { | ||
| obj[key] = Array.prototype.concat.call([], obj[key]); | ||
| if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction); | ||
| } | ||
| } | ||
| }; | ||
| const getFileName = (input)=>{ | ||
| const m = /([^\\\/]+)$/.exec(input); | ||
| return m ? m[1] : ""; | ||
| }; | ||
| const camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join("."); | ||
| class CACError extends Error { | ||
| constructor(message){ | ||
| super(message); | ||
| this.name = this.constructor.name; | ||
| if ("function" == typeof Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); | ||
| else this.stack = new Error(message).stack; | ||
| } | ||
| } | ||
| class Option { | ||
| constructor(rawName, description, config){ | ||
| this.rawName = rawName; | ||
| this.description = description; | ||
| this.config = Object.assign({}, config); | ||
| rawName = rawName.replace(/\.\*/g, ""); | ||
| this.negated = false; | ||
| this.names = removeBrackets(rawName).split(",").map((v)=>{ | ||
| let name = v.trim().replace(/^-{1,2}/, ""); | ||
| if (name.startsWith("no-")) { | ||
| this.negated = true; | ||
| name = name.replace(/^no-/, ""); | ||
| } | ||
| return camelcaseOptionName(name); | ||
| }).sort((a, b)=>a.length > b.length ? 1 : -1); | ||
| this.name = this.names[this.names.length - 1]; | ||
| if (this.negated && null == this.config.default) this.config.default = true; | ||
| if (rawName.includes("<")) this.required = true; | ||
| else if (rawName.includes("[")) this.required = false; | ||
| else this.isBoolean = true; | ||
| } | ||
| } | ||
| const processArgs = process.argv; | ||
| const platformInfo = `${process.platform}-${process.arch} node-${process.version}`; | ||
| class Command { | ||
| constructor(rawName, description, config = {}, cli){ | ||
| this.rawName = rawName; | ||
| this.description = description; | ||
| this.config = config; | ||
| this.cli = cli; | ||
| this.options = []; | ||
| this.aliasNames = []; | ||
| this.name = removeBrackets(rawName); | ||
| this.args = findAllBrackets(rawName); | ||
| this.examples = []; | ||
| } | ||
| usage(text) { | ||
| this.usageText = text; | ||
| return this; | ||
| } | ||
| allowUnknownOptions() { | ||
| this.config.allowUnknownOptions = true; | ||
| return this; | ||
| } | ||
| ignoreOptionDefaultValue() { | ||
| this.config.ignoreOptionDefaultValue = true; | ||
| return this; | ||
| } | ||
| version(version, customFlags = "-v, --version") { | ||
| this.versionNumber = version; | ||
| this.option(customFlags, "Display version number"); | ||
| return this; | ||
| } | ||
| example(example) { | ||
| this.examples.push(example); | ||
| return this; | ||
| } | ||
| option(rawName, description, config) { | ||
| const option = new Option(rawName, description, config); | ||
| this.options.push(option); | ||
| return this; | ||
| } | ||
| alias(name) { | ||
| this.aliasNames.push(name); | ||
| return this; | ||
| } | ||
| action(callback) { | ||
| this.commandAction = callback; | ||
| return this; | ||
| } | ||
| isMatched(name) { | ||
| return this.name === name || this.aliasNames.includes(name); | ||
| } | ||
| get isDefaultCommand() { | ||
| return "" === this.name || this.aliasNames.includes("!"); | ||
| } | ||
| get isGlobalCommand() { | ||
| return this instanceof GlobalCommand; | ||
| } | ||
| hasOption(name) { | ||
| name = name.split(".")[0]; | ||
| return this.options.find((option)=>option.names.includes(name)); | ||
| } | ||
| outputHelp() { | ||
| const { name, commands } = this.cli; | ||
| const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand; | ||
| let sections = [ | ||
| { | ||
| body: `${name}${versionNumber ? `/${versionNumber}` : ""}` | ||
| } | ||
| ]; | ||
| sections.push({ | ||
| title: "Usage", | ||
| body: ` $ ${name} ${this.usageText || this.rawName}` | ||
| }); | ||
| const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; | ||
| if (showCommands) { | ||
| const longestCommandName = findLongest(commands.map((command)=>command.rawName)); | ||
| sections.push({ | ||
| title: "Commands", | ||
| body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n") | ||
| }); | ||
| sections.push({ | ||
| title: "For more info, run any command with the `--help` flag", | ||
| body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n") | ||
| }); | ||
| } | ||
| let options = this.isGlobalCommand ? globalOptions : [ | ||
| ...this.options, | ||
| ...globalOptions || [] | ||
| ]; | ||
| if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name); | ||
| if (options.length > 0) { | ||
| const longestOptionName = findLongest(options.map((option)=>option.rawName)); | ||
| sections.push({ | ||
| title: "Options", | ||
| body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n") | ||
| }); | ||
| } | ||
| if (this.examples.length > 0) sections.push({ | ||
| title: "Examples", | ||
| body: this.examples.map((example)=>{ | ||
| if ("function" == typeof example) return example(name); | ||
| return example; | ||
| }).join("\n") | ||
| }); | ||
| if (helpCallback) sections = helpCallback(sections) || sections; | ||
| console.log(sections.map((section)=>section.title ? `${section.title}: | ||
| ${section.body}` : section.body).join("\n\n")); | ||
| } | ||
| outputVersion() { | ||
| const { name } = this.cli; | ||
| const { versionNumber } = this.cli.globalCommand; | ||
| if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`); | ||
| } | ||
| checkRequiredArgs() { | ||
| const minimalArgsCount = this.args.filter((arg)=>arg.required).length; | ||
| if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``); | ||
| } | ||
| checkUnknownOptions() { | ||
| const { options, globalCommand } = this.cli; | ||
| if (!this.config.allowUnknownOptions) { | ||
| 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}`}\``); | ||
| } | ||
| } | ||
| checkOptionValue() { | ||
| const { options: parsedOptions, globalCommand } = this.cli; | ||
| const options = [ | ||
| ...globalCommand.options, | ||
| ...this.options | ||
| ]; | ||
| for (const option of options){ | ||
| const value = parsedOptions[option.name.split(".")[0]]; | ||
| if (option.required) { | ||
| const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name)); | ||
| if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| class GlobalCommand extends Command { | ||
| constructor(cli){ | ||
| super("@@global@@", "", {}, cli); | ||
| } | ||
| } | ||
| var __assign = Object.assign; | ||
| class CAC extends __WEBPACK_EXTERNAL_MODULE_events__.EventEmitter { | ||
| constructor(name = ""){ | ||
| super(); | ||
| this.name = name; | ||
| this.commands = []; | ||
| this.rawArgs = []; | ||
| this.args = []; | ||
| this.options = {}; | ||
| this.globalCommand = new GlobalCommand(this); | ||
| this.globalCommand.usage("<command> [options]"); | ||
| } | ||
| usage(text) { | ||
| this.globalCommand.usage(text); | ||
| return this; | ||
| } | ||
| command(rawName, description, config) { | ||
| const command = new Command(rawName, description || "", config, this); | ||
| command.globalCommand = this.globalCommand; | ||
| this.commands.push(command); | ||
| return command; | ||
| } | ||
| option(rawName, description, config) { | ||
| this.globalCommand.option(rawName, description, config); | ||
| return this; | ||
| } | ||
| help(callback) { | ||
| this.globalCommand.option("-h, --help", "Display this message"); | ||
| this.globalCommand.helpCallback = callback; | ||
| this.showHelpOnExit = true; | ||
| return this; | ||
| } | ||
| version(version, customFlags = "-v, --version") { | ||
| this.globalCommand.version(version, customFlags); | ||
| this.showVersionOnExit = true; | ||
| return this; | ||
| } | ||
| example(example) { | ||
| this.globalCommand.example(example); | ||
| return this; | ||
| } | ||
| outputHelp() { | ||
| if (this.matchedCommand) this.matchedCommand.outputHelp(); | ||
| else this.globalCommand.outputHelp(); | ||
| } | ||
| outputVersion() { | ||
| this.globalCommand.outputVersion(); | ||
| } | ||
| setParsedInfo({ args, options }, matchedCommand, matchedCommandName) { | ||
| this.args = args; | ||
| this.options = options; | ||
| if (matchedCommand) this.matchedCommand = matchedCommand; | ||
| if (matchedCommandName) this.matchedCommandName = matchedCommandName; | ||
| return this; | ||
| } | ||
| unsetMatchedCommand() { | ||
| this.matchedCommand = void 0; | ||
| this.matchedCommandName = void 0; | ||
| } | ||
| parse(argv = processArgs, { run = true } = {}) { | ||
| this.rawArgs = argv; | ||
| if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli"; | ||
| let shouldParse = true; | ||
| for (const command of this.commands){ | ||
| const parsed = this.mri(argv.slice(2), command); | ||
| const commandName = parsed.args[0]; | ||
| if (command.isMatched(commandName)) { | ||
| shouldParse = false; | ||
| const parsedInfo = __assign(__assign({}, parsed), { | ||
| args: parsed.args.slice(1) | ||
| }); | ||
| this.setParsedInfo(parsedInfo, command, commandName); | ||
| this.emit(`command:${commandName}`, command); | ||
| } | ||
| } | ||
| if (shouldParse) { | ||
| for (const command of this.commands)if ("" === command.name) { | ||
| shouldParse = false; | ||
| const parsed = this.mri(argv.slice(2), command); | ||
| this.setParsedInfo(parsed, command); | ||
| this.emit("command:!", command); | ||
| } | ||
| } | ||
| if (shouldParse) { | ||
| const parsed = this.mri(argv.slice(2)); | ||
| this.setParsedInfo(parsed); | ||
| } | ||
| if (this.options.help && this.showHelpOnExit) { | ||
| this.outputHelp(); | ||
| run = false; | ||
| this.unsetMatchedCommand(); | ||
| } | ||
| if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) { | ||
| this.outputVersion(); | ||
| run = false; | ||
| this.unsetMatchedCommand(); | ||
| } | ||
| const parsedArgv = { | ||
| args: this.args, | ||
| options: this.options | ||
| }; | ||
| if (run) this.runMatchedCommand(); | ||
| if (!this.matchedCommand && this.args[0]) this.emit("command:*"); | ||
| return parsedArgv; | ||
| } | ||
| mri(argv, command) { | ||
| const cliOptions = [ | ||
| ...this.globalCommand.options, | ||
| ...command ? command.options : [] | ||
| ]; | ||
| const mriOptions = getMriOptions(cliOptions); | ||
| let argsAfterDoubleDashes = []; | ||
| const doubleDashesIndex = argv.indexOf("--"); | ||
| if (doubleDashesIndex > -1) { | ||
| argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); | ||
| argv = argv.slice(0, doubleDashesIndex); | ||
| } | ||
| let parsed = mri2(argv, mriOptions); | ||
| parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), { | ||
| [camelcaseOptionName(name)]: parsed[name] | ||
| }), { | ||
| _: [] | ||
| }); | ||
| const args = parsed._; | ||
| const options = { | ||
| "--": argsAfterDoubleDashes | ||
| }; | ||
| const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; | ||
| let transforms = Object.create(null); | ||
| for (const cliOption of cliOptions){ | ||
| if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default; | ||
| if (Array.isArray(cliOption.config.type)) { | ||
| if (void 0 === transforms[cliOption.name]) { | ||
| transforms[cliOption.name] = Object.create(null); | ||
| transforms[cliOption.name]["shouldTransform"] = true; | ||
| transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; | ||
| } | ||
| } | ||
| } | ||
| for (const key of Object.keys(parsed))if ("_" !== key) { | ||
| const keys = key.split("."); | ||
| setDotProp(options, keys, parsed[key]); | ||
| setByType(options, transforms); | ||
| } | ||
| return { | ||
| args, | ||
| options | ||
| }; | ||
| } | ||
| runMatchedCommand() { | ||
| const { args, options, matchedCommand: command } = this; | ||
| if (!command || !command.commandAction) return; | ||
| command.checkUnknownOptions(); | ||
| command.checkOptionValue(); | ||
| command.checkRequiredArgs(); | ||
| const actionArgs = []; | ||
| command.args.forEach((arg, index)=>{ | ||
| if (arg.variadic) actionArgs.push(args.slice(index)); | ||
| else actionArgs.push(args[index]); | ||
| }); | ||
| actionArgs.push(options); | ||
| return command.commandAction.apply(this, actionArgs); | ||
| } | ||
| } | ||
| const cac = (name = "")=>new CAC(name); | ||
| const dist = cac; | ||
| var picocolors = __webpack_require__("../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"); | ||
| var external_node_fs_ = __webpack_require__("node:fs"); | ||
| const commonOptions = (command)=>command.option("-c, --config <path>", "config file").option("--config-name <name>", "Name(s) of the configuration to use.", { | ||
| type: [ | ||
| String | ||
| ], | ||
| default: [] | ||
| }).option("--config-loader <loader>", "Specify the loader to load the config file, can be `native` or `register`.", { | ||
| default: "register" | ||
| }).option("--env <env>", "env passed to config function", { | ||
| type: [ | ||
| String | ||
| ], | ||
| default: [] | ||
| }).option("--node-env <value>", "sets `process.env.NODE_ENV` to be specified value"); | ||
| function normalizeDevtoolOption(value) { | ||
| if ("string" == typeof value) { | ||
| const trimmed = value.trim(); | ||
| if ("" === trimmed || "false" === trimmed) return false; | ||
| if ("true" === trimmed) return "source-map"; | ||
| return trimmed; | ||
| } | ||
| if ("boolean" == typeof value) return value ? "source-map" : false; | ||
| } | ||
| const normalizeCommonOptions = (options, action)=>{ | ||
| const isEmptyArray = (arr)=>Array.isArray(arr) && 0 === arr.length; | ||
| for (const key of [ | ||
| "entry", | ||
| "configName" | ||
| ]){ | ||
| const val = options[key]; | ||
| if (isEmptyArray(val)) options[key] = void 0; | ||
| } | ||
| const env = Array.isArray(options.env) ? normalizeEnvToObject(options) : {}; | ||
| options.env = env; | ||
| if ("serve" === action) setBuiltinEnvArg(env, "SERVE", true); | ||
| else if ("build" === action) if (options.watch) setBuiltinEnvArg(env, "WATCH", true); | ||
| else { | ||
| setBuiltinEnvArg(env, "BUNDLE", true); | ||
| setBuiltinEnvArg(env, "BUILD", true); | ||
| } | ||
| if ("devtool" in options) options.devtool = normalizeDevtoolOption(options.devtool); | ||
| }; | ||
| 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", { | ||
| type: [ | ||
| String | ||
| ], | ||
| default: [] | ||
| }).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"); | ||
| function setBuiltinEnvArg(env, envNameSuffix, value) { | ||
| const envName = `RSPACK_${envNameSuffix}`; | ||
| if (!(envName in env)) env[envName] = value; | ||
| } | ||
| function normalizeEnvToObject(options) { | ||
| function parseValue(previous, value) { | ||
@@ -179,151 +798,80 @@ const [allKeys, val] = value.split(/=(.+)/, 2); | ||
| } | ||
| const envObj = (argv.env ?? []).reduce(parseValue, {}); | ||
| argv.env = envObj; | ||
| return (options.env ?? []).reduce(parseValue, {}); | ||
| } | ||
| function setBuiltinEnvArg(env, envNameSuffix, value) { | ||
| const envNames = [ | ||
| `RSPACK_${envNameSuffix}` | ||
| ]; | ||
| for (const envName of envNames)if (!(envName in env)) env[envName] = value; | ||
| } | ||
| function ensureEnvObject(options) { | ||
| if (Array.isArray(options.env)) normalizeEnv(options); | ||
| options.env = options.env || {}; | ||
| return options.env; | ||
| } | ||
| function setDefaultNodeEnv(options, defaultEnv) { | ||
| if (void 0 !== process.env.NODE_ENV) return; | ||
| process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv; | ||
| if (void 0 === process.env.NODE_ENV) process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv; | ||
| } | ||
| class BuildCommand { | ||
| async apply(cli) { | ||
| cli.program.command([ | ||
| "build", | ||
| "$0", | ||
| "bundle", | ||
| "b" | ||
| ], "run the rspack build", (yargs)=>{ | ||
| commonOptionsForBuildAndServe(commonOptions(yargs)).options({ | ||
| analyze: { | ||
| type: "boolean", | ||
| default: false, | ||
| describe: "analyze" | ||
| }, | ||
| json: { | ||
| describe: "emit stats json" | ||
| }, | ||
| profile: { | ||
| type: "boolean", | ||
| default: false, | ||
| describe: "capture timing information for each module" | ||
| } | ||
| }); | ||
| }, async (options)=>{ | ||
| setDefaultNodeEnv(options, "production"); | ||
| const env = ensureEnvObject(options); | ||
| if (options.watch) setBuiltinEnvArg(env, "WATCH", true); | ||
| else { | ||
| setBuiltinEnvArg(env, "BUNDLE", true); | ||
| setBuiltinEnvArg(env, "BUILD", true); | ||
| } | ||
| const logger = cli.getLogger(); | ||
| let createJsonStringifyStream; | ||
| if (options.json) { | ||
| const jsonExt = await import("@discoveryjs/json-ext"); | ||
| createJsonStringifyStream = jsonExt.default.stringifyStream; | ||
| } | ||
| const errorHandler = (error, stats)=>{ | ||
| if (error) { | ||
| logger.error(error); | ||
| process.exit(2); | ||
| } | ||
| if (null == stats ? void 0 : stats.hasErrors()) process.exitCode = 1; | ||
| if (!compiler || !stats) return; | ||
| const statsOptions = cli.isMultipleCompiler(compiler) ? { | ||
| children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0) | ||
| } : compiler.options ? compiler.options.stats : void 0; | ||
| if (options.json && createJsonStringifyStream) { | ||
| const handleWriteError = (error)=>{ | ||
| logger.error(error); | ||
| process.exit(2); | ||
| }; | ||
| if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n")); | ||
| 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", ()=>{ | ||
| process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`); | ||
| }); | ||
| } else { | ||
| const printedStats = stats.toString(statsOptions); | ||
| if (printedStats) logger.raw(printedStats); | ||
| } | ||
| async function runBuild(cli, options) { | ||
| setDefaultNodeEnv(options, "production"); | ||
| normalizeCommonOptions(options, "build"); | ||
| const logger = cli.getLogger(); | ||
| let createJsonStringifyStream; | ||
| if (options.json) { | ||
| const jsonExt = await import("@discoveryjs/json-ext"); | ||
| createJsonStringifyStream = jsonExt.default.stringifyStream; | ||
| } | ||
| const errorHandler = (error, stats)=>{ | ||
| if (error) { | ||
| logger.error(error); | ||
| process.exit(2); | ||
| } | ||
| if (stats?.hasErrors()) process.exitCode = 1; | ||
| if (!compiler || !stats) return; | ||
| const getStatsOptions = ()=>{ | ||
| if (cli.isMultipleCompiler(compiler)) return { | ||
| children: compiler.compilers.map((item)=>item.options ? item.options.stats : void 0) | ||
| }; | ||
| const rspackOptions = { | ||
| ...options, | ||
| argv: { | ||
| ...options | ||
| } | ||
| return compiler.options?.stats; | ||
| }; | ||
| const statsOptions = getStatsOptions(); | ||
| if (options.json && createJsonStringifyStream) { | ||
| const handleWriteError = (error)=>{ | ||
| logger.error(error); | ||
| process.exit(2); | ||
| }; | ||
| const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler); | ||
| if (!compiler || cli.isWatch(compiler)) return; | ||
| compiler.run((error, stats)=>{ | ||
| compiler.close((closeErr)=>{ | ||
| if (closeErr) logger.error(closeErr); | ||
| errorHandler(error, stats); | ||
| }); | ||
| if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n")); | ||
| else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_["default"].createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{ | ||
| process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`); | ||
| }); | ||
| } else { | ||
| const printedStats = stats.toString(statsOptions); | ||
| if (printedStats) logger.raw(printedStats); | ||
| } | ||
| }; | ||
| const compiler = await cli.createCompiler(options, "build", errorHandler); | ||
| if (!compiler || cli.isWatch(compiler)) return; | ||
| compiler.run((error, stats)=>{ | ||
| compiler.close((closeErr)=>{ | ||
| if (closeErr) logger.error(closeErr); | ||
| errorHandler(error, stats); | ||
| }); | ||
| }); | ||
| } | ||
| class BuildCommand { | ||
| async apply(cli) { | ||
| const command = cli.program.command("", "run the Rspack build").alias("build").alias("bundle").alias("b"); | ||
| commonOptionsForBuildAndServe(commonOptions(command)).option("--json [path]", "emit stats json"); | ||
| command.action(async (options)=>{ | ||
| await runBuild(cli, options); | ||
| }); | ||
| } | ||
| } | ||
| const previewOptions = (yargs)=>{ | ||
| yargs.positional("dir", { | ||
| type: "string", | ||
| describe: "directory want to preview" | ||
| }); | ||
| return commonOptions(yargs).options({ | ||
| publicPath: { | ||
| type: "string", | ||
| describe: "static resource server path" | ||
| }, | ||
| port: { | ||
| type: "number", | ||
| describe: "preview server port" | ||
| }, | ||
| host: { | ||
| type: "string", | ||
| describe: "preview server host" | ||
| }, | ||
| open: { | ||
| type: "boolean", | ||
| describe: "open browser" | ||
| }, | ||
| server: { | ||
| type: "string", | ||
| describe: "Configuration items for the server." | ||
| } | ||
| }); | ||
| }; | ||
| const defaultRoot = "dist"; | ||
| var rspackCore = __webpack_require__("./src/utils/rspackCore.ts"); | ||
| class PreviewCommand { | ||
| async apply(cli) { | ||
| cli.program.command([ | ||
| "preview [dir]", | ||
| "preview", | ||
| "p" | ||
| ], "run the rspack server for build output", previewOptions, async (options)=>{ | ||
| const command = cli.program.command("preview [dir]", "run the Rspack server for build output").alias("p"); | ||
| 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."); | ||
| command.action(async (dir, options)=>{ | ||
| setDefaultNodeEnv(options, "production"); | ||
| const rspackOptions = { | ||
| ...options, | ||
| argv: { | ||
| ...options | ||
| } | ||
| }; | ||
| normalizeCommonOptions(options, "preview"); | ||
| const { RspackDevServer } = await import("@rspack/dev-server"); | ||
| let config = await cli.loadConfig(rspackOptions); | ||
| config = await getPreviewConfig(config, options); | ||
| let { config } = await cli.loadConfig(options); | ||
| config = await getPreviewConfig(config, options, dir); | ||
| if (!Array.isArray(config)) config = [ | ||
| config | ||
| ]; | ||
| config = config.find((item)=>item.devServer) || config[0]; | ||
| const devServerOptions = config.devServer; | ||
| const singleConfig = config.find((item)=>item.devServer) || config[0]; | ||
| const devServerOptions = singleConfig.devServer; | ||
| try { | ||
| const compiler = (0, core_.rspack)({ | ||
| const compiler = (0, rspackCore.Z)({ | ||
| entry: {} | ||
@@ -342,16 +890,16 @@ }); | ||
| } | ||
| async function getPreviewConfig(item, options) { | ||
| async function getPreviewConfig(item, options, dir) { | ||
| const DEFAULT_ROOT = "dist"; | ||
| const internalPreviewConfig = async (item)=>{ | ||
| var _item_output, _item_devServer, _item_devServer1, _item_devServer2, _item_devServer3, _item_devServer4; | ||
| item.devServer = { | ||
| static: { | ||
| 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), | ||
| directory: dir ? external_node_path_["default"].join(item.context ?? process.cwd(), dir) : item.output?.path ?? external_node_path_["default"].join(item.context ?? process.cwd(), DEFAULT_ROOT), | ||
| publicPath: options.publicPath ?? "/" | ||
| }, | ||
| port: options.port ?? 8080, | ||
| proxy: null == (_item_devServer = item.devServer) ? void 0 : _item_devServer.proxy, | ||
| host: options.host ?? (null == (_item_devServer1 = item.devServer) ? void 0 : _item_devServer1.host), | ||
| open: options.open ?? (null == (_item_devServer2 = item.devServer) ? void 0 : _item_devServer2.open), | ||
| server: options.server ?? (null == (_item_devServer3 = item.devServer) ? void 0 : _item_devServer3.server), | ||
| historyApiFallback: null == (_item_devServer4 = item.devServer) ? void 0 : _item_devServer4.historyApiFallback | ||
| proxy: item.devServer?.proxy, | ||
| host: options.host ?? item.devServer?.host, | ||
| open: options.open ?? item.devServer?.open, | ||
| server: options.server ?? item.devServer?.server, | ||
| historyApiFallback: item.devServer?.historyApiFallback | ||
| }; | ||
@@ -363,38 +911,17 @@ return item; | ||
| } | ||
| function normalizeHotOption(value) { | ||
| if ("boolean" == typeof value || "only" === value) return value; | ||
| if ("false" === value) return false; | ||
| return true; | ||
| } | ||
| class ServeCommand { | ||
| async apply(cli) { | ||
| cli.program.command([ | ||
| "serve", | ||
| "server", | ||
| "s", | ||
| "dev" | ||
| ], "run the rspack dev server.", (yargs)=>commonOptionsForBuildAndServe(commonOptions(yargs)).options({ | ||
| hot: { | ||
| coerce: (arg)=>{ | ||
| if ("boolean" == typeof arg || "only" === arg) return arg; | ||
| if ("false" === arg) return false; | ||
| return true; | ||
| }, | ||
| describe: "enables hot module replacement" | ||
| }, | ||
| port: { | ||
| type: "number", | ||
| coerce: (arg)=>Number.isInteger(arg) ? arg : void 0, | ||
| describe: "allows to specify a port to use" | ||
| }, | ||
| host: { | ||
| type: "string", | ||
| describe: "allows to specify a hostname to use" | ||
| } | ||
| }), async (options)=>{ | ||
| const command = cli.program.command("serve", "run the rspack dev server.").alias("server").alias("s").alias("dev"); | ||
| 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"); | ||
| command.action(async (options)=>{ | ||
| setDefaultNodeEnv(options, "development"); | ||
| setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true); | ||
| const rspackOptions = { | ||
| ...options, | ||
| argv: { | ||
| ...options | ||
| } | ||
| }; | ||
| normalizeCommonOptions(options, "serve"); | ||
| options.hot = normalizeHotOption(options.hot); | ||
| const { RspackDevServer } = await import("@rspack/dev-server"); | ||
| const compiler = await cli.createCompiler(rspackOptions, "serve"); | ||
| const compiler = await cli.createCompiler(options, "serve"); | ||
| if (!compiler) return; | ||
@@ -423,4 +950,4 @@ const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [ | ||
| const result = compilerForDevServer.options.devServer ??= {}; | ||
| const setupMiddlewares = result.setupMiddlewares; | ||
| const lazyCompileMiddleware = core_.rspack.experiments.lazyCompilationMiddleware(compiler); | ||
| const { setupMiddlewares } = result; | ||
| const lazyCompileMiddleware = rspackCore.Z.experiments.lazyCompilationMiddleware(compiler); | ||
| result.setupMiddlewares = (middlewares, server)=>{ | ||
@@ -430,4 +957,4 @@ let finalMiddlewares = middlewares; | ||
| return [ | ||
| lazyCompileMiddleware, | ||
| ...finalMiddlewares | ||
| ...finalMiddlewares, | ||
| lazyCompileMiddleware | ||
| ]; | ||
@@ -437,3 +964,3 @@ }; | ||
| result.host = options.host || result.host; | ||
| result.port = options.port || result.port; | ||
| result.port = options.port ?? result.port; | ||
| if (false !== result.client) { | ||
@@ -469,2 +996,3 @@ if (true === result.client || null == result.client) result.client = {}; | ||
| } | ||
| var lib = __webpack_require__("../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js"); | ||
| const readPackageUp = (cwd = process.cwd())=>{ | ||
@@ -486,13 +1014,11 @@ let currentDir = external_node_path_["default"].resolve(cwd); | ||
| const utils_readPackageUp = readPackageUp; | ||
| const isEsmFile = (filePath, cwd = process.cwd())=>{ | ||
| const ext = external_node_path_["default"].extname(filePath); | ||
| if (/\.(mjs|mts)$/.test(ext)) return true; | ||
| if (/\.(cjs|cts)/.test(ext)) return false; | ||
| const isEsmFile = (filePath)=>{ | ||
| if (/\.(mjs|mts)$/.test(filePath)) return true; | ||
| if (/\.(cjs|cts)$/.test(filePath)) return false; | ||
| const packageJson = utils_readPackageUp(external_node_path_["default"].dirname(filePath)); | ||
| return (null == packageJson ? void 0 : packageJson.type) === "module"; | ||
| return packageJson?.type === "module"; | ||
| }; | ||
| const utils_isEsmFile = isEsmFile; | ||
| const crossImport = async (path, cwd = process.cwd())=>{ | ||
| if (utils_isEsmFile(path, cwd)) { | ||
| const url = pathToFileURL(path).href; | ||
| const crossImport = async (path)=>{ | ||
| if (isEsmFile(path)) { | ||
| const url = (0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(path).href; | ||
| const { default: config } = await import(url); | ||
@@ -515,25 +1041,55 @@ return config; | ||
| const utils_findConfig = findConfig; | ||
| const isTsFile_isTsFile = (configPath)=>{ | ||
| const TS_EXTENSION = [ | ||
| ".ts", | ||
| ".cts", | ||
| ".mts" | ||
| ]; | ||
| const isTsFile = (configPath)=>{ | ||
| const ext = external_node_path_["default"].extname(configPath); | ||
| return /\.(c|m)?ts$/.test(ext); | ||
| return TS_EXTENSION.includes(ext); | ||
| }; | ||
| const isTsFile = isTsFile_isTsFile; | ||
| const utils_isTsFile = isTsFile; | ||
| const injectInlineSourceMap = ({ code, map })=>{ | ||
| if (map) { | ||
| const base64Map = Buffer.from(map, "utf8").toString("base64"); | ||
| const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`; | ||
| return `${code}\n${sourceMapContent}`; | ||
| } | ||
| return code; | ||
| }; | ||
| function compile(sourcecode, filename) { | ||
| const { code, map } = rspackCore.Z.experiments.swc.transformSync(sourcecode, { | ||
| jsc: { | ||
| parser: { | ||
| syntax: "typescript", | ||
| tsx: false, | ||
| decorators: true, | ||
| dynamicImport: true | ||
| } | ||
| }, | ||
| filename: filename, | ||
| module: { | ||
| type: "commonjs" | ||
| }, | ||
| sourceMaps: true, | ||
| isModule: true | ||
| }); | ||
| return injectInlineSourceMap({ | ||
| code, | ||
| map | ||
| }); | ||
| } | ||
| const loadConfig_DEFAULT_CONFIG_NAME = "rspack.config"; | ||
| const registerLoader = async (configPath)=>{ | ||
| const ext = external_node_path_["default"].extname(configPath); | ||
| if (utils_isEsmFile(configPath) && isTsFile(configPath)) return; | ||
| const { default: interpret } = await import("interpret"); | ||
| const extensions = Object.fromEntries(Object.entries(interpret.extensions).filter(([key])=>key === ext)); | ||
| if (0 === Object.keys(extensions).length) throw new Error(`config file "${configPath}" is not supported.`); | ||
| try { | ||
| const { default: rechoir } = await import("rechoir"); | ||
| rechoir.prepare(extensions, configPath); | ||
| } catch (error) { | ||
| const failures = null == error ? void 0 : error.failures; | ||
| if (failures) { | ||
| const messages = failures.map((failure)=>failure.error.message); | ||
| throw new Error(`${messages.join("\n")}`); | ||
| const registerLoader = (configPath)=>{ | ||
| if (isEsmFile(configPath) && utils_isTsFile(configPath)) return; | ||
| if (!utils_isTsFile(configPath)) throw new Error(`config file "${configPath}" is not supported.`); | ||
| (0, lib.addHook)((code, filename)=>{ | ||
| try { | ||
| return compile(code, filename); | ||
| } catch (err) { | ||
| throw new Error(`Failed to transform file "${filename}" when loading TypeScript config file:\n ${err instanceof Error ? err.message : String(err)}`); | ||
| } | ||
| throw error; | ||
| } | ||
| }, { | ||
| exts: TS_EXTENSION | ||
| }); | ||
| }; | ||
@@ -543,7 +1099,22 @@ const checkIsMultiRspackOptions = (config)=>Array.isArray(config); | ||
| if (checkIsMultiRspackOptions(config)) { | ||
| const extendedConfigs = await Promise.all(config.map((item)=>loadExtendedConfig(item, configPath, cwd, options))); | ||
| const resultPathMap = new WeakMap(); | ||
| const extendedConfigs = await Promise.all(config.map(async (item)=>{ | ||
| const { config, pathMap } = await loadExtendedConfig(item, configPath, cwd, options); | ||
| resultPathMap.set(config, pathMap.get(config)); | ||
| return config; | ||
| })); | ||
| extendedConfigs.parallelism = config.parallelism; | ||
| return extendedConfigs; | ||
| return { | ||
| config: extendedConfigs, | ||
| pathMap: resultPathMap | ||
| }; | ||
| } | ||
| if (!("extends" in config) || !config.extends) return config; | ||
| const pathMap = new WeakMap(); | ||
| pathMap.set(config, [ | ||
| configPath | ||
| ]); | ||
| if (!("extends" in config) || !config.extends) return { | ||
| config, | ||
| pathMap | ||
| }; | ||
| const extendsList = Array.isArray(config.extends) ? config.extends : [ | ||
@@ -555,2 +1126,5 @@ config.extends | ||
| let resultConfig = configWithoutExtends; | ||
| pathMap.set(resultConfig, [ | ||
| configPath | ||
| ]); | ||
| for (const extendPath of extendsList){ | ||
@@ -576,53 +1150,58 @@ let resolvedPath; | ||
| if (!external_node_fs_["default"].existsSync(resolvedPath)) throw new Error(`Extended configuration file "${resolvedPath}" not found.`); | ||
| if (isTsFile(resolvedPath) && "register" === options.configLoader) await registerLoader(resolvedPath); | ||
| let extendedConfig = await crossImport(resolvedPath, cwd); | ||
| if ("function" == typeof extendedConfig) { | ||
| var _options_argv; | ||
| extendedConfig = extendedConfig(null == (_options_argv = options.argv) ? void 0 : _options_argv.env, options.argv); | ||
| if ("function" == typeof extendedConfig.then) extendedConfig = await extendedConfig; | ||
| if (utils_isTsFile(resolvedPath) && "register" === options.configLoader) registerLoader(resolvedPath); | ||
| let loadedConfig = await crossImport(resolvedPath); | ||
| if ("function" == typeof loadedConfig) { | ||
| loadedConfig = loadedConfig(options.env, options); | ||
| if ("function" == typeof loadedConfig.then) loadedConfig = await loadedConfig; | ||
| } | ||
| extendedConfig = await loadExtendedConfig(extendedConfig, resolvedPath, cwd, options); | ||
| resultConfig = core_.util.cleverMerge(extendedConfig, resultConfig); | ||
| const { config: extendedConfig, pathMap: extendedPathMap } = await loadExtendedConfig(loadedConfig, resolvedPath, cwd, options); | ||
| const configPaths = [ | ||
| ...pathMap.get(resultConfig) || [], | ||
| ...extendedPathMap.get(extendedConfig) || [] | ||
| ]; | ||
| resultConfig = rspackCore.Z.util.cleverMerge(extendedConfig, resultConfig); | ||
| pathMap.set(resultConfig, configPaths); | ||
| } | ||
| return resultConfig; | ||
| return { | ||
| config: resultConfig, | ||
| pathMap | ||
| }; | ||
| } | ||
| async function loadRspackConfig(options, cwd = process.cwd()) { | ||
| let configPath; | ||
| let loadedConfig; | ||
| let configPath = ""; | ||
| if (options.config) { | ||
| configPath = external_node_path_["default"].resolve(cwd, options.config); | ||
| if (!external_node_fs_["default"].existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`); | ||
| if (isTsFile(configPath) && "register" === options.configLoader) await registerLoader(configPath); | ||
| loadedConfig = await crossImport(configPath, cwd); | ||
| } else { | ||
| const defaultConfig = utils_findConfig(external_node_path_["default"].resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME)); | ||
| if (!defaultConfig) return {}; | ||
| if (!defaultConfig) return null; | ||
| configPath = defaultConfig; | ||
| if (isTsFile(defaultConfig) && "register" === options.configLoader) await registerLoader(defaultConfig); | ||
| loadedConfig = await crossImport(defaultConfig, cwd); | ||
| } | ||
| if ("function" != typeof loadedConfig && configPath) loadedConfig = await loadExtendedConfig(loadedConfig, configPath, cwd, options); | ||
| return loadedConfig; | ||
| if (utils_isTsFile(configPath) && "register" === options.configLoader) registerLoader(configPath); | ||
| const loadedConfig = await crossImport(configPath); | ||
| return { | ||
| loadedConfig, | ||
| configPath | ||
| }; | ||
| } | ||
| function _define_property(obj, key, value) { | ||
| if (key in obj) Object.defineProperty(obj, key, { | ||
| value: value, | ||
| enumerable: true, | ||
| configurable: true, | ||
| writable: true | ||
| }); | ||
| else obj[key] = value; | ||
| return obj; | ||
| } | ||
| class RspackCLI { | ||
| colors; | ||
| program; | ||
| constructor(){ | ||
| const program = dist("rspack"); | ||
| this.colors = this.createColors(); | ||
| this.program = program; | ||
| program.help(); | ||
| program.version("1.6.2"); | ||
| } | ||
| async createCompiler(options, rspackCommand, callback) { | ||
| process.env.RSPACK_CONFIG_VALIDATE ??= "loose"; | ||
| let config = await this.loadConfig(options); | ||
| config = await this.buildConfig(config, options, rspackCommand); | ||
| let { config, pathMap } = await this.loadConfig(options); | ||
| config = await this.buildConfig(config, pathMap, options, rspackCommand); | ||
| const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch; | ||
| let compiler; | ||
| try { | ||
| compiler = (0, core_.rspack)(config, isWatch ? callback : void 0); | ||
| compiler = (0, rspackCore.Z)(config, isWatch ? callback : void 0); | ||
| if (!isWatch && compiler) compiler.unsafeFastDrop = true; | ||
| } catch (e) { | ||
| if (e instanceof core_.ValidationError) { | ||
| if (e instanceof rspackCore.Z.ValidationError) { | ||
| this.getLogger().error(e.message); | ||
@@ -640,7 +1219,5 @@ process.exit(2); | ||
| createColors(useColor) { | ||
| const shouldUseColor = useColor || isColorSupported; | ||
| const shouldUseColor = useColor || picocolors.isColorSupported; | ||
| return { | ||
| ...createColors({ | ||
| useColor: shouldUseColor | ||
| }), | ||
| ...(0, picocolors.createColors)(shouldUseColor), | ||
| isColorSupported: shouldUseColor | ||
@@ -651,3 +1228,3 @@ }; | ||
| return { | ||
| error: (val)=>console.error(`[rspack-cli] ${this.colors.red(node_util.format(val))}`), | ||
| error: (val)=>console.error(`[rspack-cli] ${this.colors.red(__WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__["default"].format(val))}`), | ||
| warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`), | ||
@@ -661,9 +1238,4 @@ info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`), | ||
| async run(argv) { | ||
| this.program.showHelpOnFail(false); | ||
| this.program.usage("[options]"); | ||
| this.program.scriptName("rspack"); | ||
| this.program.strictCommands(true).strict(true); | ||
| this.program.middleware(normalizeEnv); | ||
| this.registerCommands(); | ||
| await this.program.parseAsync(hideBin(argv)); | ||
| await this.registerCommands(); | ||
| this.program.parse(argv); | ||
| } | ||
@@ -676,5 +1248,5 @@ async registerCommands() { | ||
| ]; | ||
| for (const command of builtinCommands)command.apply(this); | ||
| for (const command of builtinCommands)await command.apply(this); | ||
| } | ||
| async buildConfig(item, options, command) { | ||
| async buildConfig(item, pathMap, options, command) { | ||
| const isBuild = "build" === command; | ||
@@ -701,3 +1273,3 @@ const isServe = "serve" === command; | ||
| if (process.env.RSPACK_PROFILE) { | ||
| const { applyProfile } = await __webpack_require__.e("556").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts")); | ||
| const { applyProfile } = await __webpack_require__.e("361").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts")); | ||
| await applyProfile(process.env.RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT); | ||
@@ -711,5 +1283,13 @@ } | ||
| if (isServe) { | ||
| const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin); | ||
| if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin()); | ||
| const installed = (item.plugins ||= []).find((item)=>item instanceof rspackCore.Z.ProgressPlugin); | ||
| if (!installed) (item.plugins ??= []).push(new rspackCore.Z.ProgressPlugin()); | ||
| } | ||
| const cacheOptions = item.experiments?.cache; | ||
| if ("object" == typeof cacheOptions && "persistent" === cacheOptions.type) { | ||
| const configPaths = pathMap.get(item); | ||
| if (configPaths) cacheOptions.buildDependencies = [ | ||
| ...configPaths, | ||
| ...cacheOptions.buildDependencies || [] | ||
| ]; | ||
| } | ||
| if (void 0 === item.stats) item.stats = { | ||
@@ -734,18 +1314,25 @@ preset: "errors-warnings", | ||
| async loadConfig(options) { | ||
| let loadedConfig = await loadRspackConfig(options); | ||
| const config = await loadRspackConfig(options); | ||
| if (!config) return { | ||
| config: this.filterConfig(options, {}), | ||
| pathMap: new WeakMap() | ||
| }; | ||
| let { loadedConfig, configPath } = config; | ||
| if ("function" == typeof loadedConfig) { | ||
| var _options_argv; | ||
| let functionResult = loadedConfig(null == (_options_argv = options.argv) ? void 0 : _options_argv.env, options.argv); | ||
| let functionResult = loadedConfig(options.env, options); | ||
| if ("function" == typeof functionResult.then) functionResult = await functionResult; | ||
| loadedConfig = functionResult; | ||
| if ("extends" in loadedConfig && loadedConfig.extends) { | ||
| const tempConfigPath = external_node_path_["default"].resolve(process.cwd(), "rspack.config.js"); | ||
| loadedConfig = await loadExtendedConfig(loadedConfig, tempConfigPath, process.cwd(), options); | ||
| } | ||
| } | ||
| const { config: extendedConfig, pathMap } = await loadExtendedConfig(loadedConfig, configPath, process.cwd(), options); | ||
| return { | ||
| config: this.filterConfig(options, extendedConfig), | ||
| pathMap | ||
| }; | ||
| } | ||
| filterConfig(options, config) { | ||
| if (options.configName) { | ||
| const notFoundConfigNames = []; | ||
| loadedConfig = options.configName.map((configName)=>{ | ||
| config = options.configName.map((configName)=>{ | ||
| let found; | ||
| found = Array.isArray(loadedConfig) ? loadedConfig.find((options)=>options.name === configName) : loadedConfig.name === configName ? loadedConfig : void 0; | ||
| found = Array.isArray(config) ? config.find((options)=>options.name === configName) : config.name === configName ? config : void 0; | ||
| if (!found) notFoundConfigNames.push(configName); | ||
@@ -759,3 +1346,3 @@ return found; | ||
| } | ||
| return loadedConfig; | ||
| return config; | ||
| } | ||
@@ -768,8 +1355,2 @@ isMultipleCompiler(compiler) { | ||
| } | ||
| constructor(){ | ||
| _define_property(this, "colors", void 0); | ||
| _define_property(this, "program", void 0); | ||
| this.colors = this.createColors(); | ||
| this.program = yargs_0(); | ||
| } | ||
| } | ||
@@ -776,0 +1357,0 @@ function defineConfig(config) { |
+2
-33
@@ -1,12 +0,7 @@ | ||
| import type { DevServer } from "@rspack/core"; | ||
| import type { Colorette } from "colorette"; | ||
| import type { RspackCLI } from "./cli"; | ||
| export type { Configuration } from "@rspack/core"; | ||
| export interface IRspackCLI { | ||
| runRspack(): Promise<void>; | ||
| } | ||
| export type LogHandler = (value: any) => void; | ||
| export interface RspackCLIColors extends Colorette { | ||
| export type RspackCLIColors = { | ||
| isColorSupported: boolean; | ||
| } | ||
| } & Omit<typeof import("picocolors"), "createColors">; | ||
| export interface RspackCLILogger { | ||
@@ -20,30 +15,4 @@ error: LogHandler; | ||
| } | ||
| export interface RspackCLIOptions { | ||
| config?: string; | ||
| argv?: Record<string, any>; | ||
| configName?: string[]; | ||
| configLoader?: string; | ||
| nodeEnv?: string; | ||
| } | ||
| export interface RspackBuildCLIOptions extends RspackCLIOptions { | ||
| entry?: string[]; | ||
| devtool?: string | boolean; | ||
| mode?: string; | ||
| watch?: boolean; | ||
| analyze?: boolean; | ||
| profile?: boolean; | ||
| env?: Record<string, any>; | ||
| outputPath?: string; | ||
| } | ||
| export interface RspackPreviewCLIOptions extends RspackCLIOptions { | ||
| dir?: string; | ||
| port?: number; | ||
| host?: string; | ||
| open?: boolean; | ||
| server?: string; | ||
| publicPath?: string; | ||
| } | ||
| export interface RspackCommand { | ||
| apply(cli: RspackCLI): Promise<void>; | ||
| } | ||
| export type RspackDevServerOptions = DevServer; |
@@ -1,1 +0,1 @@ | ||
| export declare const crossImport: <T = any>(path: string, cwd?: string) => Promise<T>; | ||
| export declare const crossImport: <T = any>(path: string) => Promise<T>; |
@@ -1,2 +0,1 @@ | ||
| declare const isEsmFile: (filePath: string, cwd?: string) => boolean; | ||
| export default isEsmFile; | ||
| export declare const isEsmFile: (filePath: string) => boolean; |
@@ -0,2 +1,3 @@ | ||
| export declare const TS_EXTENSION: string[]; | ||
| declare const isTsFile: (configPath: string) => boolean; | ||
| export default isTsFile; |
@@ -1,3 +0,4 @@ | ||
| import { type MultiRspackOptions, type RspackOptions } from "@rspack/core"; | ||
| import type { RspackCLIOptions } from "../types"; | ||
| import type { MultiRspackOptions, RspackOptions } from "@rspack/core"; | ||
| import type { CommonOptions } from "./options"; | ||
| export declare function compile(sourcecode: string, filename: string): string; | ||
| export type LoadedRspackConfig = undefined | RspackOptions | MultiRspackOptions | ((env: Record<string, any>, argv?: Record<string, any>) => RspackOptions | MultiRspackOptions); | ||
@@ -12,3 +13,17 @@ /** | ||
| */ | ||
| export declare function loadExtendedConfig(config: RspackOptions | MultiRspackOptions, configPath: string, cwd: string, options: RspackCLIOptions): Promise<RspackOptions | MultiRspackOptions>; | ||
| export declare function loadRspackConfig(options: RspackCLIOptions, cwd?: string): Promise<LoadedRspackConfig>; | ||
| export declare function loadExtendedConfig(config: RspackOptions, configPath: string, cwd: string, options: CommonOptions): Promise<{ | ||
| config: RspackOptions; | ||
| pathMap: WeakMap<RspackOptions, string[]>; | ||
| }>; | ||
| export declare function loadExtendedConfig(config: MultiRspackOptions, configPath: string, cwd: string, options: CommonOptions): Promise<{ | ||
| config: MultiRspackOptions; | ||
| pathMap: WeakMap<RspackOptions, string[]>; | ||
| }>; | ||
| export declare function loadExtendedConfig(config: RspackOptions | MultiRspackOptions, configPath: string, cwd: string, options: CommonOptions): Promise<{ | ||
| config: RspackOptions | MultiRspackOptions; | ||
| pathMap: WeakMap<RspackOptions, string[]>; | ||
| }>; | ||
| export declare function loadRspackConfig(options: CommonOptions, cwd?: string): Promise<{ | ||
| loadedConfig: LoadedRspackConfig; | ||
| configPath: string; | ||
| } | null>; |
+23
-71
@@ -1,77 +0,29 @@ | ||
| import type yargs from "yargs"; | ||
| import type { Command } from "cac"; | ||
| /** | ||
| * Apply common options for all commands | ||
| */ | ||
| export declare const commonOptions: (yargs: yargs.Argv) => yargs.Argv<yargs.Omit<{}, "nodeEnv" | "config" | "configName" | "configLoader"> & yargs.InferredOptionTypes<{ | ||
| config: { | ||
| g: boolean; | ||
| type: "string"; | ||
| describe: string; | ||
| alias: string; | ||
| }; | ||
| configName: { | ||
| type: "array"; | ||
| string: true; | ||
| describe: string; | ||
| }; | ||
| configLoader: { | ||
| type: "string"; | ||
| default: string; | ||
| describe: string; | ||
| }; | ||
| nodeEnv: { | ||
| string: true; | ||
| describe: string; | ||
| }; | ||
| }>>; | ||
| export declare const commonOptions: (command: Command) => Command; | ||
| export type CommonOptions = { | ||
| config?: string; | ||
| configName?: string[]; | ||
| configLoader?: string; | ||
| env?: Record<string, unknown> | string[]; | ||
| nodeEnv?: string; | ||
| }; | ||
| export declare const normalizeCommonOptions: (options: CommonOptions | CommonOptionsForBuildAndServe, action: "serve" | "build" | "preview") => void; | ||
| /** | ||
| * Apply common options for `build` and `serve` commands | ||
| */ | ||
| export declare const commonOptionsForBuildAndServe: (yargs: yargs.Argv) => yargs.Argv<yargs.Omit<{}, "entry" | "devtool" | "mode" | "watch" | "env" | "outputPath"> & yargs.InferredOptionTypes<{ | ||
| entry: { | ||
| type: "array"; | ||
| string: true; | ||
| describe: string; | ||
| }; | ||
| outputPath: { | ||
| type: "string"; | ||
| describe: string; | ||
| alias: string; | ||
| }; | ||
| mode: { | ||
| type: "string"; | ||
| describe: string; | ||
| alias: string; | ||
| }; | ||
| watch: { | ||
| type: "boolean"; | ||
| default: boolean; | ||
| describe: string; | ||
| alias: string; | ||
| }; | ||
| env: { | ||
| type: "array"; | ||
| string: true; | ||
| describe: string; | ||
| }; | ||
| devtool: { | ||
| type: "string"; | ||
| describe: string; | ||
| alias: string; | ||
| coerce: (arg: any) => string | boolean; | ||
| }; | ||
| }>>; | ||
| export declare function normalizeEnv(argv: yargs.Arguments): void; | ||
| /** | ||
| * set builtin env from cli - like `WEBPACK_BUNDLE=true`. also for `RSPACK_` prefixed. | ||
| * @param env the `argv.env` object | ||
| * @param envNameSuffix the added env will be `WEBPACK_${envNameSuffix}` and `RSPACK_${envNameSuffix}` | ||
| * @param value | ||
| */ | ||
| export declare function setBuiltinEnvArg(env: Record<string, any>, envNameSuffix: string, value: any): void; | ||
| /** | ||
| * infer `argv.env` as an object for it was transformed from array to object after `normalizeEnv` middleware | ||
| * @returns the reference of `argv.env` object | ||
| */ | ||
| export declare function ensureEnvObject<T extends Record<string, unknown>>(options: yargs.Arguments): T; | ||
| export declare function setDefaultNodeEnv(options: yargs.Arguments, defaultEnv: string): void; | ||
| export declare const commonOptionsForBuildAndServe: (command: Command) => Command; | ||
| export type CommonOptionsForBuildAndServe = CommonOptions & { | ||
| analyze?: boolean; | ||
| devtool?: string | boolean; | ||
| entry?: string[]; | ||
| mode?: string; | ||
| outputPath?: string; | ||
| profile?: boolean; | ||
| watch?: boolean; | ||
| }; | ||
| export declare function setDefaultNodeEnv(options: { | ||
| nodeEnv?: unknown; | ||
| }, defaultEnv: string): void; |
+12
-15
| { | ||
| "name": "@rspack-debug/cli", | ||
| "version": "1.4.11", | ||
| "version": "1.6.2", | ||
| "description": "CLI for rspack", | ||
@@ -32,22 +32,19 @@ "homepage": "https://rspack.rs", | ||
| "@discoveryjs/json-ext": "^0.5.7", | ||
| "@rspack/dev-server": "~1.1.3", | ||
| "colorette": "2.0.20", | ||
| "@rspack/dev-server": "~1.1.4", | ||
| "exit-hook": "^4.0.0", | ||
| "interpret": "^3.1.1", | ||
| "rechoir": "^0.8.0", | ||
| "webpack-bundle-analyzer": "4.10.2", | ||
| "yargs": "17.7.2" | ||
| "webpack-bundle-analyzer": "4.10.2" | ||
| }, | ||
| "devDependencies": { | ||
| "@rslib/core": "0.11.0", | ||
| "@types/interpret": "^1.1.3", | ||
| "@types/rechoir": "^0.6.4", | ||
| "@rslib/core": "0.17.1", | ||
| "@types/webpack-bundle-analyzer": "^4.7.0", | ||
| "@types/yargs": "17.0.33", | ||
| "cac": "^6.7.14", | ||
| "concat-stream": "^2.0.0", | ||
| "cross-env": "^7.0.3", | ||
| "cross-env": "^10.1.0", | ||
| "execa": "^5.1.1", | ||
| "picocolors": "^1.1.1", | ||
| "pirates": "^4.0.7", | ||
| "ts-node": "^10.9.2", | ||
| "typescript": "^5.8.3", | ||
| "@rspack/core": "npm:@rspack-debug/core@1.4.11" | ||
| "typescript": "^5.9.3", | ||
| "@rspack/core": "npm:@rspack-debug/core@1.6.2", | ||
| "@rspack/test-tools": "npm:@rspack-debug/test-tools@1.6.2" | ||
| }, | ||
@@ -64,4 +61,4 @@ "peerDependencies": { | ||
| "dev": "rslib build -w", | ||
| "test": "cross-env RUST_BACKTRACE=full jest --colors" | ||
| "test": "rstest" | ||
| } | ||
| } |
-42
| "use strict"; | ||
| exports.ids = [ | ||
| "556" | ||
| ]; | ||
| exports.modules = { | ||
| "./src/utils/profile.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| applyProfile: ()=>applyProfile | ||
| }); | ||
| var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:fs"); | ||
| var node_fs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(node_fs__WEBPACK_IMPORTED_MODULE_0__); | ||
| var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("node:path"); | ||
| var node_path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n(node_path__WEBPACK_IMPORTED_MODULE_1__); | ||
| var _rspack_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("@rspack/core"); | ||
| const defaultRustTraceLayer = "perfetto"; | ||
| async function applyProfile(filterValue, traceLayer = defaultRustTraceLayer, traceOutput) { | ||
| const { asyncExitHook } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "exit-hook")); | ||
| if ("logger" !== traceLayer && "perfetto" !== traceLayer) throw new Error(`unsupported trace layer: ${traceLayer}`); | ||
| const timestamp = Date.now(); | ||
| const defaultOutputDir = node_path__WEBPACK_IMPORTED_MODULE_1___default().resolve(`.rspack-profile-${timestamp}-${process.pid}`); | ||
| if (traceOutput) { | ||
| if ("stdout" !== traceOutput && "stderr" !== traceOutput) traceOutput = node_path__WEBPACK_IMPORTED_MODULE_1___default().resolve(defaultOutputDir, traceOutput); | ||
| } else { | ||
| const defaultRustTracePerfettoOutput = node_path__WEBPACK_IMPORTED_MODULE_1___default().resolve(defaultOutputDir, "rspack.pftrace"); | ||
| const defaultRustTraceLoggerOutput = "stdout"; | ||
| const defaultTraceOutput = "perfetto" === traceLayer ? defaultRustTracePerfettoOutput : defaultRustTraceLoggerOutput; | ||
| traceOutput = defaultTraceOutput; | ||
| } | ||
| await ensureFileDir(traceOutput); | ||
| await _rspack_core__WEBPACK_IMPORTED_MODULE_2__.rspack.experiments.globalTrace.register(filterValue, traceLayer, traceOutput); | ||
| asyncExitHook(_rspack_core__WEBPACK_IMPORTED_MODULE_2__.rspack.experiments.globalTrace.cleanup, { | ||
| wait: 500 | ||
| }); | ||
| } | ||
| async function ensureFileDir(outputFilePath) { | ||
| const dir = node_path__WEBPACK_IMPORTED_MODULE_1___default().dirname(outputFilePath); | ||
| await node_fs__WEBPACK_IMPORTED_MODULE_0___default().promises.mkdir(dir, { | ||
| recursive: true | ||
| }); | ||
| } | ||
| } | ||
| }; |
-39
| export const __webpack_ids__ = [ | ||
| "556" | ||
| ]; | ||
| export const __webpack_modules__ = { | ||
| "./src/utils/profile.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { | ||
| __webpack_require__.d(__webpack_exports__, { | ||
| applyProfile: ()=>applyProfile | ||
| }); | ||
| var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:fs"); | ||
| var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("node:path"); | ||
| var _rspack_core__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("@rspack/core"); | ||
| const defaultRustTraceLayer = "perfetto"; | ||
| async function applyProfile(filterValue, traceLayer = defaultRustTraceLayer, traceOutput) { | ||
| const { asyncExitHook } = await import("exit-hook"); | ||
| if ("logger" !== traceLayer && "perfetto" !== traceLayer) throw new Error(`unsupported trace layer: ${traceLayer}`); | ||
| const timestamp = Date.now(); | ||
| const defaultOutputDir = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].resolve(`.rspack-profile-${timestamp}-${process.pid}`); | ||
| if (traceOutput) { | ||
| if ("stdout" !== traceOutput && "stderr" !== traceOutput) traceOutput = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].resolve(defaultOutputDir, traceOutput); | ||
| } else { | ||
| const defaultRustTracePerfettoOutput = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].resolve(defaultOutputDir, "rspack.pftrace"); | ||
| const defaultRustTraceLoggerOutput = "stdout"; | ||
| const defaultTraceOutput = "perfetto" === traceLayer ? defaultRustTracePerfettoOutput : defaultRustTraceLoggerOutput; | ||
| traceOutput = defaultTraceOutput; | ||
| } | ||
| await ensureFileDir(traceOutput); | ||
| await _rspack_core__WEBPACK_IMPORTED_MODULE_2__.rspack.experiments.globalTrace.register(filterValue, traceLayer, traceOutput); | ||
| asyncExitHook(_rspack_core__WEBPACK_IMPORTED_MODULE_2__.rspack.experiments.globalTrace.cleanup, { | ||
| wait: 500 | ||
| }); | ||
| } | ||
| async function ensureFileDir(outputFilePath) { | ||
| const dir = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].dirname(outputFilePath); | ||
| await node_fs__WEBPACK_IMPORTED_MODULE_0__["default"].promises.mkdir(dir, { | ||
| recursive: true | ||
| }); | ||
| } | ||
| } | ||
| }; |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
136599
57.71%5
-44.44%24
4.35%2958
58.35%12
9.09%1
Infinity%- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated