@rspack/core 2.0.8 → 2.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@ let _computedKey, _computedKey1, _computedKey2, createMd4, createXxhash64, servi
2
2
  import node_util, { inspect, promisify } from "node:util";
3
3
  import { createRequire, createRequire as __rspack_createRequire } from "node:module";
4
4
  import node_path, { isAbsolute, join, relative, resolve as external_node_path_resolve, sep } from "node:path";
5
- import node_querystring from "node:querystring";
6
5
  import node_fs, { readFileSync } from "node:fs";
6
+ import node_querystring from "node:querystring";
7
7
  import { __webpack_require__ } from "./612.js";
8
8
  let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
9
9
  import * as __rspack_external_node_util_1b29d436 from "node:util";
10
10
  __webpack_require__.add({
11
- "../../node_modules/.pnpm/enhanced-resolve@5.22.1/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js" (module, __unused_rspack_exports, __webpack_require__) {
11
+ "../../node_modules/.pnpm/enhanced-resolve@5.24.0/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js" (module, __unused_rspack_exports, __webpack_require__) {
12
12
  let { nextTick } = __webpack_require__("process"), dirname = (path)=>{
13
13
  let idx = path.length - 1;
14
14
  for(; idx >= 0;){
@@ -982,6 +982,9 @@ class ModuleGraph {
982
982
  getUsedExports(module, runtime) {
983
983
  return this.#inner.getUsedExports(module, runtime);
984
984
  }
985
+ getProvidedExports(module) {
986
+ return this.#inner.getProvidedExports(module);
987
+ }
985
988
  getParentModule(dependency) {
986
989
  return this.#inner.getParentModule(dependency);
987
990
  }
@@ -2034,10 +2037,12 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
2034
2037
  return this.#createCachedAssets();
2035
2038
  }
2036
2039
  get entrypoints() {
2037
- return new Map(this.#inner.entrypoints.map((entrypoint)=>[
2038
- entrypoint.name,
2039
- entrypoint
2040
- ]));
2040
+ let entrypoints = new Map(), rawEntryPoints = this.#inner.entrypoints;
2041
+ for(let i = 0; i < rawEntryPoints.length; i++){
2042
+ let entrypoint = rawEntryPoints[i];
2043
+ entrypoints.set(entrypoint.name, entrypoint);
2044
+ }
2045
+ return entrypoints;
2041
2046
  }
2042
2047
  get chunkGroups() {
2043
2048
  return this.#inner.chunkGroups;
@@ -2127,25 +2132,16 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
2127
2132
  this.#inner.renameAsset(filename, newFilename);
2128
2133
  }
2129
2134
  getAssets() {
2130
- return this.#inner.getAssets().map((asset)=>Object.defineProperties(asset, {
2131
- info: {
2132
- value: asset.info
2133
- },
2134
- source: {
2135
- get: ()=>this.__internal__getAssetSource(asset.name)
2136
- }
2137
- }));
2135
+ return this.#inner.getAssets().map((asset)=>this.#createAsset(asset));
2138
2136
  }
2139
2137
  getAsset(name) {
2140
2138
  let asset = this.#inner.getAsset(name);
2141
- if (asset) return Object.defineProperties(asset, {
2142
- info: {
2143
- value: asset.info
2144
- },
2145
- source: {
2146
- get: ()=>this.__internal__getAssetSource(asset.name)
2147
- }
2148
- });
2139
+ if (asset) return this.#createAsset(asset);
2140
+ }
2141
+ #createAsset(asset) {
2142
+ return Object.defineProperty(asset, 'source', {
2143
+ get: ()=>this.__internal__getAssetSource(asset.name)
2144
+ }), asset;
2149
2145
  }
2150
2146
  __internal__pushRspackDiagnostic(diagnostic) {
2151
2147
  this.#inner.pushDiagnostic(diagnostic);
@@ -2922,18 +2918,25 @@ let unsupported = (name, issue)=>{
2922
2918
  return innerSubCache?.set(identifier, result), result;
2923
2919
  };
2924
2920
  }, cachedFn;
2925
- }, makePathsRelative = makeCacheableWithContext((context, identifier)=>identifier.split(SEGMENTS_SPLIT_REGEXP).map((str)=>absoluteToRequest(context, str)).join('')), contextify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>absoluteToRequest(context, r)).join('!')), absolutify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>r.startsWith('./') || r.startsWith('../') ? node_path.join(context, r) : r).join('!')), PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/, PATH_QUERY_REGEXP = /^((?:\u200b.|[^?\u200b])*)(\?.*)?$/, parseResource = makeCacheable((str)=>{
2921
+ }, makePathsRelative = makeCacheableWithContext((context, identifier)=>identifier.split(SEGMENTS_SPLIT_REGEXP).map((str)=>absoluteToRequest(context, str)).join('')), contextify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>absoluteToRequest(context, r)).join('!')), absolutify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>r.startsWith('./') || r.startsWith('../') ? node_path.join(context, r) : r).join('!')), PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/, PATH_QUERY_REGEXP = /^((?:\u200b.|[^?\u200b])*)(\?.*)?$/, parseResource = makeCacheable(function(str) {
2922
+ if (!str.includes('?') && !str.includes('#') && !str.includes('\u200b')) return {
2923
+ path: str,
2924
+ query: '',
2925
+ fragment: ''
2926
+ };
2926
2927
  let match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
2927
- return {
2928
- resource: str,
2928
+ return match ? {
2929
2929
  path: match[1].replace(/\u200b(.)/g, '$1'),
2930
2930
  query: match[2] ? match[2].replace(/\u200b(.)/g, '$1') : '',
2931
2931
  fragment: match[3] || ''
2932
+ } : {
2933
+ path: '',
2934
+ query: '',
2935
+ fragment: ''
2932
2936
  };
2933
2937
  }), parseResourceWithoutFragment = makeCacheable((str)=>{
2934
2938
  let match = PATH_QUERY_REGEXP.exec(str);
2935
2939
  return {
2936
- resource: str,
2937
2940
  path: match[1].replace(/\u200b(.)/g, '$1'),
2938
2941
  query: match[2] ? match[2].replace(/\u200b(.)/g, '$1') : ''
2939
2942
  };
@@ -3070,1912 +3073,1887 @@ function resolvePluginImport(pluginImport) {
3070
3073
  }), rawConfig;
3071
3074
  });
3072
3075
  }
3073
- let $assets = Symbol('assets');
3074
- Object.defineProperty(binding_default().KnownBuildInfo.prototype, node_util.inspect.custom, {
3075
- enumerable: !0,
3076
- configurable: !0,
3077
- value () {
3076
+ let BUILTIN_LOADER_PREFIX = 'builtin:';
3077
+ function createRawModuleRuleUses(uses, path, options) {
3078
+ var uses1, path1, options1;
3079
+ let normalizeRuleSetUseItem = (item)=>'string' == typeof item ? {
3080
+ loader: item
3081
+ } : item;
3082
+ return uses1 = Array.isArray(uses) ? [
3083
+ ...uses
3084
+ ].map(normalizeRuleSetUseItem) : [
3085
+ normalizeRuleSetUseItem(uses)
3086
+ ], path1 = path, options1 = options, uses1.length ? uses1.filter(Boolean).map((use, index)=>{
3087
+ let o, isBuiltin = !1;
3088
+ if (use.loader.startsWith(BUILTIN_LOADER_PREFIX)) {
3089
+ let temp = function(identifier, o, options) {
3090
+ if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}swc-loader`)) return ((o, composeOptions)=>{
3091
+ let options = o ?? {};
3092
+ if ('object' == typeof options) {
3093
+ var options1;
3094
+ if (options.jsc ??= {}, options.jsc.experimental ??= {}, options.jsc.experimental.disableAllLints ??= !0, options.env?.targets === void 0 && options.jsc?.target === void 0) {
3095
+ if (composeOptions.compiler.target?.targets) options.env ??= {}, options.env.targets ??= function(targets) {
3096
+ let REMAP = {
3097
+ and_chr: 'chrome',
3098
+ and_ff: 'firefox',
3099
+ ie_mob: 'ie',
3100
+ ios_saf: 'ios',
3101
+ op_mob: 'opera',
3102
+ and_qq: null,
3103
+ and_uc: null,
3104
+ baidu: null,
3105
+ bb: null,
3106
+ kaios: null,
3107
+ op_mini: null
3108
+ }, result = {};
3109
+ for (let [k, version] of Object.entries(targets)){
3110
+ let remap = REMAP[k];
3111
+ null !== remap && (result[remap || k] = version);
3112
+ }
3113
+ return result;
3114
+ }(composeOptions.compiler.target.targets);
3115
+ else if (composeOptions.compiler.target?.esVersion) {
3116
+ let { esVersion } = composeOptions.compiler.target;
3117
+ options.jsc.target ??= esVersion >= 2015 ? `es${esVersion}` : 'es5';
3118
+ }
3119
+ }
3120
+ options.collectTypeScriptInfo && (options.collectTypeScriptInfo = {
3121
+ typeExports: (options1 = options.collectTypeScriptInfo).typeExports,
3122
+ exportedEnum: !0 === options1.exportedEnum ? 'all' : !1 === options1.exportedEnum || void 0 === options1.exportedEnum ? 'none' : 'const-only'
3123
+ }), options.transformImport && (options.transformImport = resolvePluginImport(options.transformImport));
3124
+ let { rspackExperiments } = options;
3125
+ rspackExperiments && (rspackExperiments.import || rspackExperiments.pluginImport) && (rspackExperiments.import = resolvePluginImport(rspackExperiments.import || rspackExperiments.pluginImport));
3126
+ }
3127
+ return options;
3128
+ })(o, options);
3129
+ if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}lightningcss-loader`)) {
3130
+ let options1;
3131
+ return 'object' == typeof (options1 = o ?? {}) && ('string' == typeof options1.targets ? options1.targets = [
3132
+ options1.targets
3133
+ ] : 'object' != typeof options1.targets || Array.isArray(options1.targets) ? void 0 === options1.targets && options.compiler.target?.targets && (options1.targets = defaultTargetsFromRspackTargets(options.compiler.target.targets)) : options1.targets = encodeTargets(options1.targets), options1.include && 'object' == typeof options1.include && (options1.include = toFeatures(options1.include)), options1.exclude && 'object' == typeof options1.exclude && (options1.exclude = toFeatures(options1.exclude))), options1;
3134
+ }
3135
+ return o;
3136
+ }(use.loader, use.options, options1);
3137
+ o = isNil(temp) ? void 0 : 'string' == typeof temp ? temp : JSON.stringify(temp, null, 2), isBuiltin = !0;
3138
+ }
3078
3139
  return {
3079
- ...this,
3080
- assets: this.assets,
3081
- fileDependencies: this.fileDependencies,
3082
- contextDependencies: this.contextDependencies,
3083
- missingDependencies: this.missingDependencies,
3084
- buildDependencies: this.buildDependencies
3140
+ loader: function(use, path, compiler, isBuiltin) {
3141
+ let obj = parseResource(use.loader), ident = use.ident;
3142
+ null === use.options || void 0 === use.options || ('string' == typeof use.options ? obj.query = `?${use.options}` : use.ident ? obj.query = `??${ident = use.ident}` : 'object' == typeof use.options && use.options.ident ? obj.query = `??${ident = use.options.ident}` : 'object' == typeof use.options ? obj.query = `??${ident = path}` : obj.query = `?${JSON.stringify(use.options)}`);
3143
+ let parallelism = use.parallel;
3144
+ if (parallelism && (!use.options || 'object' != typeof use.options)) throw Error(`\`Rule.use.parallel\` requires \`Rule.use.options\` to be an object.\nHowever the received value is \`${use.options}\` under option path \`${path}\`\nInternally, parallelism is provided by passing \`Rule.use.ident\` to the loader as an identifier to ident the parallelism option\nYou can either replace the \`Rule.use.loader\` with \`Rule.use.options = {}\` or remove \`Rule.use.parallel\`.`);
3145
+ return use.options && 'object' == typeof use.options && (ident || (ident = '[[missing ident]]'), compiler.__internal__ruleSet.references.set(ident, use.options), compiler.__internal__ruleSet.references.set(`${ident}$$parallelism`, parallelism), isBuiltin && compiler.__internal__ruleSet.builtinReferences.set(ident, use.options)), obj.path + obj.query + obj.fragment;
3146
+ }(use, `${path1}[${index}]`, options1.compiler, isBuiltin),
3147
+ options: o
3085
3148
  };
3086
- }
3087
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'assets', {
3088
- enumerable: !0,
3089
- configurable: !0,
3090
- get () {
3091
- if (this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets]) return this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets];
3092
- let assets = new Proxy(Object.create(null), {
3093
- ownKeys: ()=>this[binding_default().BUILD_INFO_ASSETS_SYMBOL].keys(),
3094
- getOwnPropertyDescriptor: ()=>({
3095
- enumerable: !0,
3096
- configurable: !0
3097
- })
3098
- });
3099
- return Object.defineProperty(this[binding_default().BUILD_INFO_ASSETS_SYMBOL], $assets, {
3100
- enumerable: !1,
3101
- configurable: !0,
3102
- value: assets
3103
- }), assets;
3104
- }
3105
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'fileDependencies', {
3106
- enumerable: !0,
3107
- configurable: !0,
3108
- get () {
3109
- return new Set(this[binding_default().BUILD_INFO_FILE_DEPENDENCIES_SYMBOL]);
3110
- }
3111
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'contextDependencies', {
3112
- enumerable: !0,
3113
- configurable: !0,
3114
- get () {
3115
- return new Set(this[binding_default().BUILD_INFO_CONTEXT_DEPENDENCIES_SYMBOL]);
3116
- }
3117
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'missingDependencies', {
3118
- enumerable: !0,
3119
- configurable: !0,
3120
- get () {
3121
- return new Set(this[binding_default().BUILD_INFO_MISSING_DEPENDENCIES_SYMBOL]);
3122
- }
3123
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'buildDependencies', {
3124
- enumerable: !0,
3125
- configurable: !0,
3126
- get () {
3127
- return new Set(this[binding_default().BUILD_INFO_BUILD_DEPENDENCIES_SYMBOL]);
3128
- }
3129
- });
3130
- let knownBuildInfoFields = new Set([
3131
- 'assets',
3132
- 'fileDependencies',
3133
- 'contextDependencies',
3134
- 'missingDependencies',
3135
- 'buildDependencies'
3136
- ]);
3137
- Object.defineProperty(binding_default().NormalModule.prototype, 'identifier', {
3138
- enumerable: !0,
3139
- configurable: !0,
3140
- value () {
3141
- return this[binding_default().MODULE_IDENTIFIER_SYMBOL];
3142
- }
3143
- }), Object.defineProperty(binding_default().NormalModule.prototype, 'originalSource', {
3144
- enumerable: !0,
3145
- configurable: !0,
3146
- value () {
3147
- let originalSource = this._originalSource();
3148
- return originalSource ? SourceAdapter.fromBinding(originalSource) : null;
3149
- }
3150
- }), Object.defineProperty(binding_default().NormalModule.prototype, 'emitFile', {
3151
- enumerable: !0,
3152
- configurable: !0,
3153
- value (filename, source, assetInfo) {
3154
- return this._emitFile(filename, SourceAdapter.toBinding(source), assetInfo);
3155
- }
3156
- }), Object.defineProperty(binding_default().NormalModule, 'getCompilationHooks', {
3157
- enumerable: !0,
3158
- configurable: !0,
3159
- value (compilation) {
3160
- if (!(binding_default().COMPILATION_HOOKS_MAP_SYMBOL in compilation)) throw TypeError("The 'compilation' argument must be an instance of Compilation");
3161
- let compilationHooksMap = compilation[binding_default().COMPILATION_HOOKS_MAP_SYMBOL], hooks = compilationHooksMap.get(compilation);
3162
- return void 0 === hooks && (hooks = {
3163
- loader: new SyncHook([
3164
- 'loaderContext',
3165
- 'module'
3166
- ]),
3167
- readResource: new HookMap(()=>new AsyncSeriesBailHook([
3168
- 'loaderContext'
3169
- ]))
3170
- }, compilationHooksMap.set(compilation, hooks)), hooks;
3171
- }
3172
- });
3173
- class NonErrorEmittedError extends Error {
3174
- constructor(error){
3175
- super(), this.name = 'NonErrorEmittedError', this.message = `(Emitted value instead of an instance of Error) ${error}`;
3176
- }
3149
+ }) : [];
3177
3150
  }
3178
- class DeadlockRiskError extends Error {
3179
- constructor(message){
3180
- super(message), this.name = 'DeadlockRiskError', this.stack = '';
3181
- }
3151
+ function isUseSourceMap(devtool) {
3152
+ return !!devtool && devtool.includes('source-map') && (devtool.includes('module') || !devtool.includes('cheap'));
3182
3153
  }
3183
- class ValidationError extends Error {
3184
- constructor(message){
3185
- super(message), this.name = 'ValidationError';
3154
+ function getRawAlias(alias = {}) {
3155
+ return !('object' != typeof alias || null === alias || Array.isArray(alias)) && Object.entries(alias).map(([key, value])=>({
3156
+ path: key,
3157
+ redirect: Array.isArray(value) ? value : [
3158
+ value
3159
+ ]
3160
+ }));
3161
+ }
3162
+ function getRawResolve(resolve) {
3163
+ var byDependency;
3164
+ return {
3165
+ ...resolve,
3166
+ alias: getRawAlias(resolve.alias),
3167
+ fallback: getRawAlias(resolve.fallback),
3168
+ extensionAlias: function(alias = {}) {
3169
+ if ('object' == typeof alias && null !== alias) return Object.fromEntries(Object.entries(alias).map(([key, value])=>Array.isArray(value) ? [
3170
+ key,
3171
+ value
3172
+ ] : [
3173
+ key,
3174
+ [
3175
+ value
3176
+ ]
3177
+ ]));
3178
+ }(resolve.extensionAlias),
3179
+ tsconfig: function(tsConfig) {
3180
+ if ('string' == typeof tsConfig) throw Error('should resolve string tsConfig in normalization');
3181
+ if (void 0 === tsConfig) return tsConfig;
3182
+ let { configFile, references } = tsConfig;
3183
+ return {
3184
+ configFile,
3185
+ referencesType: 'auto' === references ? 'auto' : references ? 'manual' : 'disabled',
3186
+ references: 'auto' === references ? void 0 : references
3187
+ };
3188
+ }(resolve.tsConfig),
3189
+ byDependency: void 0 === (byDependency = resolve.byDependency) ? byDependency : Object.fromEntries(Object.entries(byDependency).map(([k, v])=>[
3190
+ k,
3191
+ getRawResolve(v)
3192
+ ]))
3193
+ };
3194
+ }
3195
+ function tryMatch(payload, condition) {
3196
+ if ('string' == typeof condition) return payload.startsWith(condition);
3197
+ if (condition instanceof RegExp) return condition.test(payload);
3198
+ if ('function' == typeof condition) return condition(payload);
3199
+ if (Array.isArray(condition)) return condition.some((c)=>tryMatch(payload, c));
3200
+ if (condition && 'object' == typeof condition) {
3201
+ if (condition.and) return condition.and.every((c)=>tryMatch(payload, c));
3202
+ if (condition.or) return condition.or.some((c)=>tryMatch(payload, c));
3203
+ if (condition.not) return !tryMatch(payload, condition.not);
3186
3204
  }
3205
+ return !1;
3187
3206
  }
3188
- class JavaScriptTracer {
3189
- static state = 'uninitialized';
3190
- static startTime;
3191
- static events;
3192
- static layer;
3193
- static output;
3194
- static session;
3195
- static counter = 10000;
3196
- static async initJavaScriptTrace(layer, output) {
3197
- let { Session } = await import("node:inspector");
3198
- this.session = new Session(), this.layer = layer, this.output = output, this.events = [], this.state = 'on', this.startTime = process.hrtime.bigint();
3199
- }
3200
- static uuid() {
3201
- return this.counter++;
3202
- }
3203
- static initCpuProfiler() {
3204
- this.layer && (this.session.connect(), this.session.post('Profiler.enable'), this.session.post('Profiler.start'));
3207
+ let getRawModuleRule = (rule, path, options, upperType)=>{
3208
+ let funcUse, normalizedUse = rule.loader ? [
3209
+ {
3210
+ loader: rule.loader,
3211
+ options: rule.options
3212
+ }
3213
+ ] : rule.use;
3214
+ 'function' == typeof normalizedUse && (funcUse = (rawContext)=>createRawModuleRuleUses(normalizedUse({
3215
+ ...rawContext,
3216
+ compiler: options.compiler
3217
+ }) ?? [], `${path}.use`, options));
3218
+ let rawModuleRule = {
3219
+ test: rule.test ? getRawRuleSetCondition(rule.test) : void 0,
3220
+ include: rule.include ? getRawRuleSetCondition(rule.include) : void 0,
3221
+ exclude: rule.exclude ? getRawRuleSetCondition(rule.exclude) : void 0,
3222
+ issuer: rule.issuer ? getRawRuleSetCondition(rule.issuer) : void 0,
3223
+ issuerLayer: rule.issuerLayer ? getRawRuleSetCondition(rule.issuerLayer) : void 0,
3224
+ dependency: rule.dependency ? getRawRuleSetCondition(rule.dependency) : void 0,
3225
+ phase: rule.phase ? getRawRuleSetCondition(rule.phase) : void 0,
3226
+ descriptionData: rule.descriptionData ? Object.fromEntries(Object.entries(rule.descriptionData).map(([k, v])=>[
3227
+ k,
3228
+ getRawRuleSetCondition(v)
3229
+ ])) : void 0,
3230
+ with: rule.with ? Object.fromEntries(Object.entries(rule.with).map(([k, v])=>[
3231
+ k,
3232
+ getRawRuleSetCondition(v)
3233
+ ])) : void 0,
3234
+ resource: rule.resource ? getRawRuleSetCondition(rule.resource) : void 0,
3235
+ resourceQuery: rule.resourceQuery ? getRawRuleSetCondition(rule.resourceQuery) : void 0,
3236
+ resourceFragment: rule.resourceFragment ? getRawRuleSetCondition(rule.resourceFragment) : void 0,
3237
+ scheme: rule.scheme ? getRawRuleSetCondition(rule.scheme) : void 0,
3238
+ mimetype: rule.mimetype ? getRawRuleSetCondition(rule.mimetype) : void 0,
3239
+ sideEffects: rule.sideEffects,
3240
+ use: 'function' == typeof normalizedUse ? funcUse : createRawModuleRuleUses(normalizedUse ?? [], `${path}.use`, options),
3241
+ type: rule.type,
3242
+ layer: rule.layer,
3243
+ parser: rule.parser ? getRawParserOptions(rule.parser, rule.type ?? upperType) : void 0,
3244
+ generator: rule.generator ? getRawGeneratorOptions(rule.generator, rule.type ?? upperType) : void 0,
3245
+ resolve: rule.resolve ? getRawResolve(rule.resolve) : void 0,
3246
+ oneOf: rule.oneOf ? rule.oneOf.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.oneOf[${index}]`, options, rule.type ?? upperType)) : void 0,
3247
+ rules: rule.rules ? rule.rules.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.rules[${index}]`, options, rule.type ?? upperType)) : void 0,
3248
+ enforce: rule.enforce,
3249
+ extractSourceMap: rule.extractSourceMap
3250
+ };
3251
+ return ('function' == typeof rule.test || 'function' == typeof rule.resource || 'function' == typeof rule.resourceQuery || 'function' == typeof rule.resourceFragment) && (delete rawModuleRule.test, delete rawModuleRule.resource, delete rawModuleRule.resourceQuery, delete rawModuleRule.resourceFragment, rawModuleRule.rspackResource = getRawRuleSetCondition((resourceQueryFragment)=>{
3252
+ let { path, query, fragment } = parseResource(resourceQueryFragment);
3253
+ return (!rule.test || !!tryMatch(path, rule.test)) && (!rule.resource || !!tryMatch(path, rule.resource)) && (!rule.resourceQuery || !!tryMatch(query, rule.resourceQuery)) && (!rule.resourceFragment || !!tryMatch(fragment, rule.resourceFragment));
3254
+ })), rawModuleRule;
3255
+ };
3256
+ function getRawRuleSetCondition(condition) {
3257
+ if ('string' == typeof condition) return {
3258
+ type: binding_namespaceObject.RawRuleSetConditionType.string,
3259
+ string: condition
3260
+ };
3261
+ if (condition instanceof RegExp) return {
3262
+ type: binding_namespaceObject.RawRuleSetConditionType.regexp,
3263
+ regexp: condition
3264
+ };
3265
+ if ('function' == typeof condition) return {
3266
+ type: binding_namespaceObject.RawRuleSetConditionType.func,
3267
+ func: condition
3268
+ };
3269
+ if (Array.isArray(condition)) return {
3270
+ type: binding_namespaceObject.RawRuleSetConditionType.array,
3271
+ array: condition.map((i)=>getRawRuleSetCondition(i))
3272
+ };
3273
+ if ('object' == typeof condition && null !== condition) {
3274
+ var logical;
3275
+ return {
3276
+ type: binding_namespaceObject.RawRuleSetConditionType.logical,
3277
+ logical: [
3278
+ {
3279
+ and: (logical = condition).and ? logical.and.map((i)=>getRawRuleSetCondition(i)) : void 0,
3280
+ or: logical.or ? logical.or.map((i)=>getRawRuleSetCondition(i)) : void 0,
3281
+ not: logical.not ? getRawRuleSetCondition(logical.not) : void 0
3282
+ }
3283
+ ]
3284
+ };
3205
3285
  }
3206
- static async cleanupJavaScriptTrace() {
3207
- if ('uninitialized' === this.state) throw Error('JavaScriptTracer is not initialized, please call initJavaScriptTrace first');
3208
- if (!this.layer || 'off' === this.state) return;
3209
- let profileHandler = (err, param)=>{
3210
- let cpu_profile;
3211
- if (err ? console.error('Error stopping profiler:', err) : cpu_profile = param.profile, cpu_profile) {
3212
- let uuid = this.uuid();
3213
- this.pushEvent({
3214
- name: 'Profile',
3215
- ph: 'P',
3216
- trackName: 'JavaScript CPU Profiler',
3217
- processName: 'JavaScript CPU',
3218
- uuid,
3219
- ...this.getCommonEv(),
3220
- categories: [
3221
- 'disabled-by-default-v8.cpu_profiler'
3222
- ],
3223
- args: {
3224
- data: {
3225
- startTime: 0
3226
- }
3227
- }
3228
- }), this.pushEvent({
3229
- name: 'ProfileChunk',
3230
- ph: 'P',
3231
- trackName: 'JavaScript CPU Profiler',
3232
- processName: 'JavaScript CPU',
3233
- ...this.getCommonEv(),
3234
- categories: [
3235
- 'disabled-by-default-v8.cpu_profiler'
3236
- ],
3237
- uuid,
3238
- args: {
3239
- data: {
3240
- cpuProfile: cpu_profile,
3241
- timeDeltas: cpu_profile.timeDeltas
3286
+ throw Error('unreachable: condition should be one of string, RegExp, Array, Object');
3287
+ }
3288
+ function getRawParserOptions(parser, type) {
3289
+ var parser1, parser2, parser3;
3290
+ if ('asset' === type) {
3291
+ return {
3292
+ type: 'asset',
3293
+ asset: {
3294
+ dataUrlCondition: (parser1 = parser).dataUrlCondition ? function(dataUrlCondition) {
3295
+ if ('object' == typeof dataUrlCondition && null !== dataUrlCondition) return {
3296
+ type: 'options',
3297
+ options: {
3298
+ maxSize: dataUrlCondition.maxSize
3242
3299
  }
3243
- }
3244
- });
3300
+ };
3301
+ throw Error(`unreachable: AssetParserDataUrl type should be one of "options", but got ${dataUrlCondition}`);
3302
+ }(parser1.dataUrlCondition) : void 0
3245
3303
  }
3246
3304
  };
3247
- await new Promise((resolve, reject)=>{
3248
- this.session.post('Profiler.stop', (err, params)=>{
3249
- if (err) reject(err);
3250
- else try {
3251
- profileHandler(err, params), resolve();
3252
- } catch (err) {
3253
- reject(err);
3254
- }
3255
- });
3256
- }), this.state = 'off';
3257
- }
3258
- static getTs() {
3259
- return process.hrtime.bigint() - this.startTime;
3260
3305
  }
3261
- static getCommonEv() {
3306
+ if ("javascript" === type) return {
3307
+ type: "javascript",
3308
+ javascript: getRawJavascriptParserOptions(parser)
3309
+ };
3310
+ if ("javascript/auto" === type) return {
3311
+ type: "javascript/auto",
3312
+ javascript: getRawJavascriptParserOptions(parser)
3313
+ };
3314
+ if ("javascript/dynamic" === type) return {
3315
+ type: "javascript/dynamic",
3316
+ javascript: getRawJavascriptParserOptions(parser)
3317
+ };
3318
+ if ("javascript/esm" === type) return {
3319
+ type: "javascript/esm",
3320
+ javascript: getRawJavascriptParserOptions(parser)
3321
+ };
3322
+ if ('css' === type) {
3262
3323
  return {
3263
- ts: this.getTs(),
3264
- cat: 'rspack'
3324
+ type: 'css',
3325
+ css: {
3326
+ namedExports: (parser2 = parser).namedExports,
3327
+ url: parser2.url,
3328
+ import: parser2.import,
3329
+ resolveImport: parser2.resolveImport
3330
+ }
3265
3331
  };
3266
3332
  }
3267
- static pushEvent(event) {
3268
- let stringifiedArgs = Object.keys(event.args || {}).reduce((acc, key)=>(acc[key] = JSON.stringify(event.args[key]), acc), {});
3269
- this.events.push({
3270
- ...event,
3271
- args: stringifiedArgs
3272
- });
3273
- }
3274
- static startAsync(events) {
3275
- this.layer && this.pushEvent({
3276
- ...this.getCommonEv(),
3277
- ...events,
3278
- ph: 'b'
3279
- });
3280
- }
3281
- static endAsync(events) {
3282
- this.layer && this.pushEvent({
3283
- ...this.getCommonEv(),
3284
- ...events,
3285
- ph: 'e'
3286
- });
3333
+ if ('css/auto' === type) return {
3334
+ type: 'css/auto',
3335
+ cssAuto: getRawCssAutoOrModuleParserOptions(parser)
3336
+ };
3337
+ if ('css/global' === type) return {
3338
+ type: 'css/global',
3339
+ cssGlobal: getRawCssModuleParserOptions(parser)
3340
+ };
3341
+ if ('css/module' === type) return {
3342
+ type: 'css/module',
3343
+ cssModule: getRawCssAutoOrModuleParserOptions(parser)
3344
+ };
3345
+ if ('json' === type) {
3346
+ return {
3347
+ type: 'json',
3348
+ json: {
3349
+ exportsDepth: (parser3 = parser).exportsDepth,
3350
+ parse: 'function' == typeof parser3.parse ? (str)=>JSON.stringify(parser3.parse(str)) : void 0
3351
+ }
3352
+ };
3287
3353
  }
3354
+ throw Error(`unreachable: unknown module type: ${type}`);
3288
3355
  }
3289
- let CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
3290
- function createMessage(method) {
3291
- return `Abstract method${method ? ` ${method}` : ''}. Must be overridden.`;
3356
+ function getRawJavascriptParserOptions(parser) {
3357
+ return {
3358
+ dynamicImportMode: parser.dynamicImportMode,
3359
+ dynamicImportPreload: parser.dynamicImportPreload?.toString(),
3360
+ dynamicImportPrefetch: parser.dynamicImportPrefetch?.toString(),
3361
+ dynamicImportFetchPriority: parser.dynamicImportFetchPriority,
3362
+ importMeta: 'boolean' == typeof parser.importMeta ? String(parser.importMeta) : parser.importMeta,
3363
+ url: parser.url?.toString(),
3364
+ exprContextCritical: parser.exprContextCritical,
3365
+ unknownContextCritical: parser.unknownContextCritical,
3366
+ wrappedContextCritical: parser.wrappedContextCritical,
3367
+ strictThisContextOnImports: parser.strictThisContextOnImports,
3368
+ wrappedContextRegExp: parser.wrappedContextRegExp,
3369
+ exportsPresence: !1 === parser.exportsPresence ? 'false' : parser.exportsPresence,
3370
+ importExportsPresence: !1 === parser.importExportsPresence ? 'false' : parser.importExportsPresence,
3371
+ reexportExportsPresence: !1 === parser.reexportExportsPresence ? 'false' : parser.reexportExportsPresence,
3372
+ worker: 'boolean' == typeof parser.worker ? parser.worker ? [
3373
+ '...'
3374
+ ] : [] : parser.worker,
3375
+ overrideStrict: parser.overrideStrict,
3376
+ requireAsExpression: parser.requireAsExpression,
3377
+ requireAlias: parser.requireAlias,
3378
+ requireDynamic: parser.requireDynamic,
3379
+ requireResolve: parser.requireResolve,
3380
+ commonjs: parser.commonjs,
3381
+ importDynamic: parser.importDynamic,
3382
+ commonjsMagicComments: parser.commonjsMagicComments,
3383
+ createRequire: parser.createRequire,
3384
+ typeReexportsPresence: parser.typeReexportsPresence,
3385
+ jsx: parser.jsx,
3386
+ deferImport: parser.deferImport,
3387
+ sourceImport: parser.sourceImport,
3388
+ importMetaResolve: parser.importMetaResolve,
3389
+ pureFunctions: parser.pureFunctions
3390
+ };
3292
3391
  }
3293
- class Message extends Error {
3294
- constructor(){
3295
- super(), this.stack = void 0, Error.captureStackTrace(this);
3296
- let match = this.stack.split('\n')[3].match(CURRENT_METHOD_REGEXP);
3297
- this.message = match?.[1] ? createMessage(match[1]) : createMessage();
3298
- }
3299
- }
3300
- class AbstractMethodError extends lib_WebpackError {
3301
- constructor(){
3302
- super(new Message().message), this.name = 'AbstractMethodError';
3303
- }
3392
+ function getRawCssModuleParserOptions(parser) {
3393
+ return {
3394
+ namedExports: parser.namedExports,
3395
+ url: parser.url,
3396
+ import: parser.import,
3397
+ resolveImport: parser.resolveImport,
3398
+ animation: parser.animation,
3399
+ container: parser.container,
3400
+ customIdents: parser.customIdents,
3401
+ dashedIdents: parser.dashedIdents,
3402
+ function: parser.function,
3403
+ grid: parser.grid
3404
+ };
3304
3405
  }
3305
- class Hash {
3306
- update() {
3307
- throw new AbstractMethodError();
3308
- }
3309
- digest() {
3310
- throw new AbstractMethodError();
3311
- }
3406
+ function getRawCssAutoOrModuleParserOptions(parser) {
3407
+ return {
3408
+ ...getRawCssModuleParserOptions(parser),
3409
+ pure: parser.pure
3410
+ };
3312
3411
  }
3313
- let MAX_SHORT_STRING = -4 & Math.floor(16368);
3314
- class WasmHash {
3315
- exports;
3316
- instancesPool;
3317
- buffered;
3318
- mem;
3319
- chunkSize;
3320
- digestSize;
3321
- constructor(instance, instancesPool, chunkSize, digestSize){
3322
- let exports = instance.exports;
3323
- exports.init(), this.exports = exports, this.mem = Buffer.from(exports.memory.buffer, 0, 65536), this.buffered = 0, this.instancesPool = instancesPool, this.chunkSize = chunkSize, this.digestSize = digestSize;
3324
- }
3325
- reset() {
3326
- this.buffered = 0, this.exports.init();
3327
- }
3328
- update(data, encoding) {
3329
- if ('string' == typeof data) {
3330
- let normalizedData = data;
3331
- for(; normalizedData.length > MAX_SHORT_STRING;)this._updateWithShortString(normalizedData.slice(0, MAX_SHORT_STRING), encoding), normalizedData = normalizedData.slice(MAX_SHORT_STRING);
3332
- return this._updateWithShortString(normalizedData, encoding), this;
3333
- }
3334
- return this._updateWithBuffer(data), this;
3412
+ function getRawGeneratorOptions(generator, type) {
3413
+ var options, options1;
3414
+ if ('asset' === type) {
3415
+ return {
3416
+ type: 'asset',
3417
+ asset: generator ? {
3418
+ ...getRawAssetInlineGeneratorOptions(options = generator),
3419
+ ...getRawAssetResourceGeneratorOptions(options)
3420
+ } : void 0
3421
+ };
3335
3422
  }
3336
- _updateWithShortString(data, encoding) {
3337
- let endPos, { exports, buffered, mem, chunkSize } = this;
3338
- if (data.length < 70) if (encoding && 'utf-8' !== encoding && 'utf8' !== encoding) if ('latin1' === encoding) {
3339
- endPos = buffered;
3340
- for(let i = 0; i < data.length; i++){
3341
- let cc = data.charCodeAt(i);
3342
- mem[endPos++] = cc;
3343
- }
3344
- } else endPos = buffered + mem.write(data, buffered, encoding);
3345
- else {
3346
- endPos = buffered;
3347
- for(let i = 0; i < data.length; i++){
3348
- let cc = data.charCodeAt(i);
3349
- if (cc < 0x80) mem[endPos++] = cc;
3350
- else if (cc < 0x800) mem[endPos] = cc >> 6 | 0xc0, mem[endPos + 1] = 0x3f & cc | 0x80, endPos += 2;
3351
- else {
3352
- endPos += mem.write(data.slice(i), endPos, encoding);
3353
- break;
3354
- }
3423
+ if ('asset/inline' === type) return {
3424
+ type: 'asset/inline',
3425
+ assetInline: generator ? getRawAssetInlineGeneratorOptions(generator) : void 0
3426
+ };
3427
+ if ('asset/resource' === type) return {
3428
+ type: 'asset/resource',
3429
+ assetResource: generator ? getRawAssetResourceGeneratorOptions(generator) : void 0
3430
+ };
3431
+ if ('css' === type) {
3432
+ return {
3433
+ type: 'css',
3434
+ css: {
3435
+ exportsOnly: (options1 = generator).exportsOnly,
3436
+ esModule: options1.esModule
3355
3437
  }
3356
- }
3357
- else endPos = buffered + mem.write(data, buffered, encoding);
3358
- if (endPos < chunkSize) this.buffered = endPos;
3359
- else {
3360
- let l = endPos & ~(this.chunkSize - 1);
3361
- exports.update(l);
3362
- let newBuffered = endPos - l;
3363
- this.buffered = newBuffered, newBuffered > 0 && mem.copyWithin(0, l, endPos);
3364
- }
3438
+ };
3365
3439
  }
3366
- _updateWithBuffer(data) {
3367
- let { exports, buffered, mem } = this, length = data.length;
3368
- if (buffered + length < this.chunkSize) data.copy(mem, buffered, 0, length), this.buffered += length;
3369
- else {
3370
- let l = buffered + length & ~(this.chunkSize - 1);
3371
- if (l > 65536) {
3372
- let i = 65536 - buffered;
3373
- data.copy(mem, buffered, 0, i), exports.update(65536);
3374
- let stop = l - buffered - 65536;
3375
- for(; i < stop;)data.copy(mem, 0, i, i + 65536), exports.update(65536), i += 65536;
3376
- data.copy(mem, 0, i, l - buffered), exports.update(l - buffered - i);
3377
- } else data.copy(mem, buffered, 0, l - buffered), exports.update(l);
3378
- let newBuffered = length + buffered - l;
3379
- this.buffered = newBuffered, newBuffered > 0 && data.copy(mem, 0, length - newBuffered, length);
3440
+ if ('css/auto' === type) return {
3441
+ type: 'css/auto',
3442
+ cssAuto: getRawCssAutoOrModuleGeneratorOptions(generator)
3443
+ };
3444
+ if ('css/global' === type) return {
3445
+ type: 'css/global',
3446
+ cssGlobal: getRawCssAutoOrModuleGeneratorOptions(generator)
3447
+ };
3448
+ if ('css/module' === type) return {
3449
+ type: 'css/module',
3450
+ cssModule: getRawCssAutoOrModuleGeneratorOptions(generator)
3451
+ };
3452
+ if ('json' === type) return {
3453
+ type: 'json',
3454
+ json: {
3455
+ JSONParse: generator.JSONParse
3380
3456
  }
3381
- }
3382
- digest(type) {
3383
- let { exports, buffered, mem, digestSize } = this;
3384
- exports.final(buffered), this.instancesPool.push(this);
3385
- let hex = mem.toString('latin1', 0, digestSize);
3386
- return 'hex' === type ? hex : 'binary' !== type && type ? Buffer.from(hex, 'hex').toString(type) : Buffer.from(hex, 'hex');
3387
- }
3457
+ };
3458
+ if (![
3459
+ 'asset/source',
3460
+ 'asset/bytes',
3461
+ "javascript",
3462
+ "javascript/auto",
3463
+ "javascript/dynamic",
3464
+ "javascript/esm"
3465
+ ].includes(type)) throw Error(`unreachable: unknown module type: ${type}`);
3388
3466
  }
3389
- let wasm_hash = (wasmModule, instancesPool, chunkSize, digestSize)=>{
3390
- if (instancesPool.length > 0) {
3391
- let old = instancesPool.pop();
3392
- return old.reset(), old;
3393
- }
3394
- return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
3395
- }, createHash_require = createRequire(import.meta.url), digestCaches = {};
3396
- class BulkUpdateDecorator extends Hash {
3397
- hash;
3398
- hashFactory;
3399
- hashKey;
3400
- buffer;
3401
- constructor(hashOrFactory, hashKey){
3402
- super(), this.hashKey = hashKey, 'function' == typeof hashOrFactory ? (this.hashFactory = hashOrFactory, this.hash = void 0) : (this.hashFactory = void 0, this.hash = hashOrFactory), this.buffer = '';
3403
- }
3404
- update(data, inputEncoding) {
3405
- return void 0 !== inputEncoding || 'string' != typeof data || data.length > 2000 ? (void 0 === this.hash && (this.hash = this.hashFactory()), this.buffer.length > 0 && (this.hash.update(Buffer.from(this.buffer)), this.buffer = ''), Buffer.isBuffer(data) ? this.hash.update(data) : this.hash.update(data, inputEncoding)) : (this.buffer += data, this.buffer.length > 2000 && (void 0 === this.hash && (this.hash = this.hashFactory()), this.hash.update(Buffer.from(this.buffer)), this.buffer = '')), this;
3406
- }
3407
- digest(encoding) {
3408
- let digestCache, buffer = this.buffer;
3409
- if (void 0 === this.hash) {
3410
- let cacheKey = `${this.hashKey}-${encoding}`;
3411
- void 0 === (digestCache = digestCaches[cacheKey]) && (digestCache = digestCaches[cacheKey] = new Map());
3412
- let cacheEntry = digestCache.get(buffer);
3413
- if (void 0 !== cacheEntry) return encoding ? cacheEntry : Buffer.from(cacheEntry, 'hex');
3414
- this.hash = this.hashFactory();
3415
- }
3416
- buffer.length > 0 && this.hash.update(Buffer.from(buffer));
3417
- let result = encoding ? this.hash.digest(encoding) : this.hash.digest();
3418
- return void 0 !== digestCache && 'string' == typeof result && digestCache.set(buffer, result), result;
3419
- }
3467
+ function getRawAssetInlineGeneratorOptions(options) {
3468
+ return {
3469
+ dataUrl: options.dataUrl ? function(dataUrl) {
3470
+ if ('object' == typeof dataUrl && null !== dataUrl) return {
3471
+ encoding: !1 === dataUrl.encoding ? 'false' : dataUrl.encoding,
3472
+ mimetype: dataUrl.mimetype
3473
+ };
3474
+ if ('function' == typeof dataUrl && null !== dataUrl) return (source, context)=>dataUrl(source, context);
3475
+ throw Error(`unreachable: AssetGeneratorDataUrl type should be one of "options", "function", but got ${dataUrl}`);
3476
+ }(options.dataUrl) : void 0,
3477
+ binary: options.binary
3478
+ };
3420
3479
  }
3421
- class WasmHashAdapter extends Hash {
3422
- wasmHash;
3423
- constructor(wasmHash){
3424
- super(), this.wasmHash = wasmHash;
3480
+ function getRawAssetResourceGeneratorOptions(options) {
3481
+ return {
3482
+ emit: options.emit,
3483
+ filename: options.filename,
3484
+ outputPath: options.outputPath,
3485
+ publicPath: options.publicPath,
3486
+ importMode: options.importMode,
3487
+ binary: options.binary
3488
+ };
3489
+ }
3490
+ function getRawCssAutoOrModuleGeneratorOptions(options) {
3491
+ return {
3492
+ localIdentName: options.localIdentName,
3493
+ localIdentHashDigest: options.localIdentHashDigest,
3494
+ localIdentHashDigestLength: options.localIdentHashDigestLength,
3495
+ localIdentHashFunction: options.localIdentHashFunction,
3496
+ localIdentHashSalt: options.localIdentHashSalt,
3497
+ exportsConvention: options.exportsConvention,
3498
+ exportsOnly: options.exportsOnly,
3499
+ esModule: options.esModule
3500
+ };
3501
+ }
3502
+ class ExternalsPlugin extends RspackBuiltinPlugin {
3503
+ type;
3504
+ externals;
3505
+ placeInInitial;
3506
+ fallbackType;
3507
+ name = binding_namespaceObject.BuiltinPluginName.ExternalsPlugin;
3508
+ #resolveRequestCache = new Map();
3509
+ constructor(type, externals, placeInInitial, fallbackType){
3510
+ super(), this.type = type, this.externals = externals, this.placeInInitial = placeInInitial, this.fallbackType = fallbackType;
3425
3511
  }
3426
- update(data, inputEncoding) {
3427
- return Buffer.isBuffer(data) ? this.wasmHash.update(data) : this.wasmHash.update(data, inputEncoding), this;
3512
+ raw() {
3513
+ let type = this.type, externals = this.externals, raw = {
3514
+ type,
3515
+ fallbackType: this.fallbackType,
3516
+ externals: (Array.isArray(externals) ? externals : [
3517
+ externals
3518
+ ]).filter(Boolean).map((item)=>this.#getRawExternalItem(item)),
3519
+ placeInInitial: this.placeInInitial ?? !1
3520
+ };
3521
+ return createBuiltinPlugin(this.name, raw);
3428
3522
  }
3429
- digest(encoding) {
3430
- return encoding ? this.wasmHash.digest(encoding) : this.wasmHash.digest();
3523
+ #processResolveResult = (text)=>{
3524
+ if (!text) return;
3525
+ let resolveRequest = this.#resolveRequestCache.get(text);
3526
+ return resolveRequest || (resolveRequest = JSON.parse(text), this.#resolveRequestCache.set(text, resolveRequest)), Object.assign({}, resolveRequest);
3527
+ };
3528
+ #processRequest(req) {
3529
+ return `${req.path.replace(/#/g, '\u200b#')}${req.query.replace(/#/g, '\u200b#')}${req.fragment}`;
3431
3530
  }
3432
- }
3433
- let createHash_createHash = (algorithm)=>{
3434
- if ('function' == typeof algorithm) return new BulkUpdateDecorator(()=>new algorithm());
3435
- switch(algorithm){
3436
- case 'xxhash64':
3437
- return new WasmHashAdapter((()=>{
3438
- if (!createXxhash64) {
3439
- let xxhash64 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL', 'base64'));
3440
- createXxhash64 = wasm_hash.bind(null, xxhash64, [], 32, 16);
3441
- }
3442
- return createXxhash64();
3443
- })());
3444
- case 'md4':
3445
- return new WasmHashAdapter((()=>{
3446
- if (!createMd4) {
3447
- let md4 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=', 'base64'));
3448
- createMd4 = wasm_hash.bind(null, md4, [], 64, 32);
3449
- }
3450
- return createMd4();
3451
- })());
3452
- case 'native-md4':
3453
- return new BulkUpdateDecorator(()=>{
3454
- let { createHash } = createHash_require('node:crypto');
3455
- return createHash('md4');
3456
- }, 'md4');
3457
- default:
3458
- return new BulkUpdateDecorator(()=>{
3459
- let { createHash } = createHash_require('node:crypto');
3460
- return createHash(algorithm);
3461
- }, algorithm);
3531
+ #getRawExternalItem = (item)=>{
3532
+ if ('string' == typeof item || item instanceof RegExp) return item;
3533
+ if ('function' == typeof item) {
3534
+ let processResolveResult = this.#processResolveResult;
3535
+ return async (ctx)=>new Promise((resolve, reject)=>{
3536
+ let data = ctx.data(), promise = item({
3537
+ request: data.request,
3538
+ dependencyType: data.dependencyType,
3539
+ context: data.context,
3540
+ contextInfo: {
3541
+ issuer: data.contextInfo.issuer,
3542
+ issuerLayer: data.contextInfo.issuerLayer ?? null
3543
+ },
3544
+ getResolve: (options)=>{
3545
+ let rawResolve = options ? getRawResolve(options) : void 0, resolve = ctx.getResolve(rawResolve);
3546
+ return (context, request, callback)=>{
3547
+ if (!callback) return new Promise((promiseResolve, promiseReject)=>{
3548
+ resolve(context, request, (error, text)=>{
3549
+ if (error) promiseReject(error);
3550
+ else {
3551
+ let req = processResolveResult(text);
3552
+ promiseResolve(req ? this.#processRequest(req) : void 0);
3553
+ }
3554
+ });
3555
+ });
3556
+ resolve(context, request, (error, text)=>{
3557
+ if (error) callback(error);
3558
+ else {
3559
+ let req = processResolveResult(text);
3560
+ callback(null, !!req && this.#processRequest(req), req);
3561
+ }
3562
+ });
3563
+ };
3564
+ }
3565
+ }, (err, result, type)=>{
3566
+ err && reject(err), resolve({
3567
+ result: getRawExternalItemValueFormFnResult(result),
3568
+ externalType: type
3569
+ });
3570
+ });
3571
+ promise?.then ? promise.then((result)=>resolve({
3572
+ result: getRawExternalItemValueFormFnResult(result),
3573
+ externalType: void 0
3574
+ }), (e)=>reject(e)) : 1 === item.length && resolve({
3575
+ result: getRawExternalItemValueFormFnResult(promise),
3576
+ externalType: void 0
3577
+ });
3578
+ });
3579
+ }
3580
+ if ('object' == typeof item) return Object.fromEntries(Object.entries(item).map(([k, v])=>[
3581
+ k,
3582
+ getRawExternalItemValue(v)
3583
+ ]));
3584
+ throw TypeError(`Unexpected type of external item: ${typeof item}`);
3585
+ };
3586
+ }
3587
+ function getRawExternalItemValueFormFnResult(result) {
3588
+ return void 0 === result ? result : getRawExternalItemValue(result);
3589
+ }
3590
+ function getRawExternalItemValue(value) {
3591
+ return value && 'object' == typeof value && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).map(([k, v])=>[
3592
+ k,
3593
+ Array.isArray(v) ? v : [
3594
+ v
3595
+ ]
3596
+ ])) : value;
3597
+ }
3598
+ let FetchCompileAsyncWasmPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FetchCompileAsyncWasmPlugin, ()=>{}, 'thisCompilation'), FileUriPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FileUriPlugin, ()=>{}, 'compilation'), FlagDependencyExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FlagDependencyExportsPlugin, ()=>{}, 'compilation');
3599
+ class FlagDependencyUsagePlugin extends RspackBuiltinPlugin {
3600
+ global;
3601
+ name = binding_namespaceObject.BuiltinPluginName.FlagDependencyUsagePlugin;
3602
+ affectedHooks = 'compilation';
3603
+ constructor(global){
3604
+ super(), this.global = global;
3605
+ }
3606
+ raw() {
3607
+ return createBuiltinPlugin(this.name, this.global);
3608
+ }
3609
+ }
3610
+ let HashedModuleIdsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HashedModuleIdsPlugin, (options)=>({
3611
+ ...options
3612
+ }), 'compilation');
3613
+ class HotModuleReplacementPlugin extends RspackBuiltinPlugin {
3614
+ name = binding_namespaceObject.BuiltinPluginName.HotModuleReplacementPlugin;
3615
+ raw(compiler) {
3616
+ return void 0 === compiler.options.output.strictModuleErrorHandling && (compiler.options.output.strictModuleErrorHandling = !0), createBuiltinPlugin(this.name, void 0);
3462
3617
  }
3463
- }, memoize = (fn)=>{
3618
+ }
3619
+ let HttpExternalsRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HttpExternalsRspackPlugin, (webAsync)=>({
3620
+ webAsync
3621
+ })), memoize = (fn)=>{
3464
3622
  let result, cache = !1, callback = fn;
3465
3623
  return ()=>(cache || (result = callback(), cache = !0, callback = void 0), result);
3466
3624
  }, memoizeFn = (fn)=>{
3467
3625
  let cache = null;
3468
3626
  return (...args)=>(cache || (cache = fn()), cache(...args));
3469
- }, ModuleError_createMessage = (err, type, from)=>{
3470
- let message = `Module ${type}${from ? ` (from ${from}):\n` : ': '}`;
3471
- return err && 'object' == typeof err && err.message ? message += err.message : err && (message += err), message;
3472
- }, getErrorDetails = (err)=>{
3473
- var stack, name, message, stack1, name1, message1;
3474
- let details, nextLine;
3475
- return err && 'object' == typeof err && err.stack ? (stack = err.stack, name = err.name, message = err.message, cutOffLoaderExecution(stack), stack1 = stack, name1 = name, message1 = message, details = -1 === (nextLine = stack1.indexOf('\n')) ? stack1 === message1 ? '' : stack1 : stack1.slice(0, nextLine) === `${name1}: ${message1}` ? stack1.slice(nextLine + 1) : stack1) : void 0;
3627
+ }, HttpUriPlugin_require = createRequire(import.meta.url), getHttp = memoize(()=>HttpUriPlugin_require('node:http')), getHttps = memoize(()=>HttpUriPlugin_require('node:https')), defaultHttpClientForNode = async (url, headers)=>{
3628
+ let { res, body } = await function(url, options) {
3629
+ let send = 'https:' === new URL(url).protocol ? getHttps() : getHttp(), { createBrotliDecompress, createGunzip, createInflate } = HttpUriPlugin_require('node:zlib');
3630
+ return new Promise((resolve, reject)=>{
3631
+ send.get(url, options, (res)=>{
3632
+ let contentEncoding = res.headers['content-encoding'], stream = res;
3633
+ 'gzip' === contentEncoding ? stream = stream.pipe(createGunzip()) : 'br' === contentEncoding ? stream = stream.pipe(createBrotliDecompress()) : 'deflate' === contentEncoding && (stream = stream.pipe(createInflate()));
3634
+ let chunks = [];
3635
+ stream.on('data', (chunk)=>{
3636
+ chunks.push(chunk);
3637
+ }), stream.on('end', ()=>{
3638
+ let bodyBuffer = Buffer.concat(chunks);
3639
+ res.complete ? resolve({
3640
+ res,
3641
+ body: bodyBuffer
3642
+ }) : reject(Error(`${url} request was terminated early`));
3643
+ });
3644
+ }).on('error', reject);
3645
+ });
3646
+ }(url, {
3647
+ headers
3648
+ }), responseHeaders = {};
3649
+ for (let [key, value] of Object.entries(res.headers))Array.isArray(value) ? responseHeaders[key] = value.join(', ') : responseHeaders[key] = value;
3650
+ return {
3651
+ status: res.statusCode,
3652
+ headers: responseHeaders,
3653
+ body: Buffer.from(body)
3654
+ };
3476
3655
  };
3477
- class ModuleError extends lib_WebpackError {
3478
- error;
3479
- constructor(err, { from } = {}){
3480
- super(ModuleError_createMessage(err, 'Error', from)), this.name = 'ModuleError', this.error = err, this.details = getErrorDetails(err);
3656
+ class HttpUriPlugin extends RspackBuiltinPlugin {
3657
+ options;
3658
+ name = binding_namespaceObject.BuiltinPluginName.HttpUriPlugin;
3659
+ affectedHooks = 'compilation';
3660
+ constructor(options){
3661
+ super(), this.options = options;
3481
3662
  }
3482
- }
3483
- class ModuleWarning extends lib_WebpackError {
3484
- error;
3485
- constructor(err, { from } = {}){
3486
- super(ModuleError_createMessage(err, 'Warning', from)), this.name = 'ModuleWarning', this.error = err, this.details = getErrorDetails(err);
3663
+ raw(compiler) {
3664
+ let options = this.options, lockfileLocation = options.lockfileLocation ?? node_path.join(compiler.context, compiler.name ? `${compiler.name}.rspack.lock` : 'rspack.lock'), cacheLocation = !1 === options.cacheLocation ? void 0 : options.cacheLocation ?? `${lockfileLocation}.data`, raw = {
3665
+ allowedUris: options.allowedUris,
3666
+ lockfileLocation,
3667
+ cacheLocation,
3668
+ upgrade: options.upgrade ?? !1,
3669
+ httpClient: options.httpClient ?? defaultHttpClientForNode
3670
+ };
3671
+ return createBuiltinPlugin(this.name, raw);
3487
3672
  }
3488
3673
  }
3489
- let service_require = createRequire(import.meta.url), ensureLoaderWorkerPool = async (workerOptions)=>service_pool || (service_pool = import("../compiled/tinypool/dist/index.js").then(({ Tinypool })=>{
3490
- let availableThreads = Math.max(service_require('node:os').cpus().length - 1, 1), maxWorkers = workerOptions?.maxWorkers ? Math.max(workerOptions.maxWorkers, 1) : void 0, maxWorkersFromEnv = parseInt(process.env.RSPACK_LOADER_WORKER_THREADS || '', 10);
3491
- return new Tinypool({
3492
- filename: node_path.resolve(import.meta.dirname, 'worker.js'),
3493
- useAtomics: !1,
3494
- maxThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
3495
- minThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
3496
- concurrentTasksPerWorker: 1
3497
- });
3498
- }));
3499
- function serializeError(error) {
3500
- if (error instanceof Error || error && 'object' == typeof error && 'message' in error) return {
3501
- ...error,
3502
- name: error.name,
3503
- stack: error.stack,
3504
- message: error.message
3505
- };
3506
- if ('string' == typeof error) return {
3507
- name: 'Error',
3508
- message: error
3509
- };
3510
- throw Error('Failed to serialize error, only string, Error instances and objects with a message property are supported');
3511
- }
3512
- let service_run = async (loaderName, task, options, workerOptions)=>ensureLoaderWorkerPool(workerOptions).then(async (pool)=>{
3513
- let { MessageChannel } = await import("node:worker_threads"), { port1: mainPort, port2: workerPort } = new MessageChannel(), { port1: mainSyncPort, port2: workerSyncPort } = new MessageChannel();
3514
- return new Promise((resolve, reject)=>{
3515
- let handleError = (error)=>{
3516
- mainPort.close(), mainSyncPort.close(), reject(error);
3517
- }, pendingRequests = new Map();
3518
- mainPort.on('message', (message)=>{
3519
- 'done' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
3520
- mainPort.close(), mainSyncPort.close(), resolve(message.data);
3521
- }) : 'done-error' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
3522
- mainPort.close(), mainSyncPort.close(), reject(message.error);
3523
- }) : 'request' === message.type && pendingRequests.set(message.id, Promise.resolve().then(()=>options.handleIncomingRequest(message.requestType, ...message.data)).then((result)=>(mainPort.postMessage({
3524
- type: 'response',
3525
- id: message.id,
3526
- data: result
3527
- }), result)).catch((error)=>{
3528
- mainPort.postMessage({
3529
- type: 'response-error',
3530
- id: message.id,
3531
- error: serializeError(error)
3532
- });
3533
- }));
3534
- }), mainPort.on('messageerror', handleError), mainSyncPort.on('message', async (message)=>{
3535
- let result, { sharedBuffer } = message, sharedBufferView = new Int32Array(sharedBuffer);
3536
- try {
3537
- if ("WaitForPendingRequest" === message.requestType) {
3538
- let pendingRequestId = message.data[0], isArray = Array.isArray(pendingRequestId), ids = isArray ? pendingRequestId : [
3539
- pendingRequestId
3540
- ];
3541
- result = await Promise.all(ids.map((id)=>pendingRequests.get(id))), isArray || (result = result[0]);
3542
- } else throw Error(`Unknown request type: ${message.requestType}`);
3543
- mainSyncPort.postMessage({
3544
- type: 'response',
3545
- id: message.id,
3546
- data: result
3547
- });
3548
- } catch (e) {
3549
- mainSyncPort.postMessage({
3550
- type: 'response-error',
3551
- id: message.id,
3552
- error: serializeError(e)
3553
- });
3554
- }
3555
- Atomics.add(sharedBufferView, 0, 1), Atomics.notify(sharedBufferView, 0, 1 / 0);
3556
- }), mainSyncPort.on('messageerror', handleError);
3557
- let errors = [];
3558
- for (let key of Object.keys(task))try {
3559
- structuredClone(task[key]);
3560
- } catch (e) {
3561
- errors.push({
3562
- key,
3563
- type: typeof task[key],
3564
- reason: e.message
3565
- });
3566
- }
3567
- if (errors.length > 0) {
3568
- let errorMsg = errors.map((err)=>`option "${err.key}" (type: ${err.type}) is not cloneable: ${err.reason}`).join('\n');
3569
- throw Error(`The options for ${loaderName} are not cloneable, which is not supported by parallelLoader. Consider disabling parallel for this loader or removing the non-cloneable properties from the options:\n${errorMsg}`);
3570
- }
3571
- pool.run({
3572
- ...task,
3573
- workerData: {
3574
- workerPort,
3575
- workerSyncPort
3576
- }
3577
- }, {
3578
- ...options,
3579
- transferList: [
3580
- ...options?.transferList || [],
3581
- workerPort,
3582
- workerSyncPort
3583
- ]
3584
- }).catch(handleError);
3585
- });
3586
- }), LoaderLoadingError = class extends Error {
3587
- constructor(message){
3588
- super(message), this.name = 'LoaderRunnerError', Error.captureStackTrace(this, this.constructor);
3589
- }
3590
- }, loadLoader_require = createRequire(import.meta.url);
3591
- function loadLoader(loader, compiler, callback) {
3592
- if ('module' === loader.type) try {
3593
- void 0 === loadLoader_url && (loadLoader_url = loadLoader_require('node:url')), import(loadLoader_url.pathToFileURL(loader.path).toString()).then((module)=>{
3594
- handleResult(loader, module, callback);
3595
- }, callback);
3596
- return;
3597
- } catch (e) {
3598
- callback(e);
3599
- }
3600
- else {
3601
- let module;
3602
- try {
3603
- module = loadLoader_require(loader.path);
3604
- } catch (e) {
3605
- if (e instanceof Error && 'EMFILE' === e.code) return void setImmediate(loadLoader.bind(null, loader, compiler, callback));
3606
- return callback(e);
3607
- }
3608
- return handleResult(loader, module, callback);
3674
+ let compilationOptionsMap = new WeakMap(), hooks_compilationHooksMap = new WeakMap(), plugin_require = createRequire(import.meta.url), HTML_PLUGIN_UID = 0, HtmlRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HtmlRspackPlugin, function(c = {}) {
3675
+ let templateFn, templateParameters, filenames, uid = HTML_PLUGIN_UID++, meta = {};
3676
+ for(let key in c.meta){
3677
+ let value = c.meta[key];
3678
+ 'string' == typeof value ? meta[key] = {
3679
+ name: key,
3680
+ content: value
3681
+ } : meta[key] = {
3682
+ name: key,
3683
+ ...value
3684
+ };
3609
3685
  }
3610
- }
3611
- function handleResult(loader, module, callback) {
3612
- return 'function' != typeof module && 'object' != typeof module ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (export function or es6 module)`)) : (loader.normal = 'function' == typeof module ? module : module.default, loader.pitch = module.pitch, loader.raw = module.raw, loader.pitch || (loader.noPitch = !0), 'function' != typeof loader.normal && 'function' != typeof loader.pitch) ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (must have normal or pitch function)`)) : void callback();
3613
- }
3614
- let decoder = new TextDecoder(), utils_loadLoader = promisify(loadLoader), utils_runSyncOrAsync = promisify(function(fn, context, args, callback) {
3615
- let isSync = !0, isDone = !1, isError = !1, reportedError = !1;
3616
- context.async = function() {
3617
- if (isDone) {
3618
- if (reportedError) return;
3619
- throw Error('async(): The callback was already called.');
3686
+ let scriptLoading = c.scriptLoading ?? 'defer', configInject = c.inject ?? !0, base = 'string' == typeof c.base ? {
3687
+ href: c.base
3688
+ } : c.base, chunksSortMode = c.chunksSortMode ?? 'auto', compilation = null;
3689
+ function generateRenderData(data) {
3690
+ let json = JSON.parse(data);
3691
+ 'function' != typeof c.templateParameters && (json.compilation = compilation);
3692
+ let renderTag = function() {
3693
+ var tag;
3694
+ let attributes;
3695
+ return tag = this, attributes = Object.keys(tag.attributes || {}).filter((attributeName)=>'' === tag.attributes[attributeName] || tag.attributes[attributeName]).map((attributeName)=>'true' === tag.attributes[attributeName] ? attributeName : `${attributeName}="${tag.attributes[attributeName]}"`), `<${[
3696
+ tag.tagName
3697
+ ].concat(attributes).join(' ')}${tag.voidTag && !tag.innerHTML ? '/' : ''}>${tag.innerHTML || ''}${tag.voidTag && !tag.innerHTML ? '' : `</${tag.tagName}>`}`;
3698
+ }, renderTagList = function() {
3699
+ return this.join('');
3700
+ };
3701
+ if (Array.isArray(json.htmlRspackPlugin?.tags?.headTags)) {
3702
+ for (let tag of json.htmlRspackPlugin.tags.headTags)tag.toString = renderTag;
3703
+ json.htmlRspackPlugin.tags.headTags.toString = renderTagList;
3620
3704
  }
3621
- return isSync = !1, innerCallback;
3622
- };
3623
- let innerCallback = (err, ...args)=>{
3624
- if (isDone) {
3625
- if (reportedError) return;
3626
- throw Error('callback(): The callback was already called.');
3705
+ if (Array.isArray(json.htmlRspackPlugin?.tags?.bodyTags)) {
3706
+ for (let tag of json.htmlRspackPlugin.tags.bodyTags)tag.toString = renderTag;
3707
+ json.htmlRspackPlugin.tags.bodyTags.toString = renderTagList;
3627
3708
  }
3628
- isDone = !0, isSync = !1;
3709
+ return json;
3710
+ }
3711
+ this.hooks.compilation.tap('HtmlRspackPlugin', (compilationInstance)=>{
3712
+ var compilation1;
3713
+ let optionsMap;
3714
+ compilation1 = compilation = compilationInstance, (optionsMap = compilationOptionsMap.get(compilation1) || {})[uid] = c, compilationOptionsMap.set(compilation1, optionsMap);
3715
+ }), this.hooks.done.tap('HtmlRspackPlugin', (stats)=>{
3716
+ var compilation, compilation1;
3717
+ let optionsMap;
3718
+ compilation = stats.compilation, hooks_compilationHooksMap.delete(compilation), compilation1 = stats.compilation, optionsMap = compilationOptionsMap.get(compilation1) || {}, delete optionsMap[uid], 0 === Object.keys(optionsMap).length ? compilationOptionsMap.delete(compilation1) : compilationOptionsMap.set(compilation1, optionsMap);
3719
+ });
3720
+ let templateContent = c.templateContent;
3721
+ if ('function' == typeof templateContent) templateFn = async (data)=>{
3629
3722
  try {
3630
- callback(err, args);
3723
+ let renderer = c.templateContent;
3724
+ if (!1 === c.templateParameters) return await renderer({});
3725
+ return await renderer(generateRenderData(data));
3631
3726
  } catch (e) {
3632
- throw isError = !0, e;
3633
- }
3634
- };
3635
- context.callback = innerCallback;
3636
- try {
3637
- let result = fn.apply(context, args);
3638
- if (isSync) {
3639
- if (isDone = !0, void 0 === result) return void callback(null, []);
3640
- if (result && 'object' == typeof result && 'function' == typeof result.then) return void result.then((r)=>{
3641
- callback(null, [
3642
- r
3643
- ]);
3644
- }, callback);
3645
- callback(null, [
3646
- result
3647
- ]);
3648
- return;
3727
+ let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
3728
+ throw error.stack = e.stack, error;
3649
3729
  }
3650
- } catch (e) {
3651
- if ('hideStack' in e && e.hideStack && (e.hideStack = 'true'), isError) throw e;
3652
- if (isDone) return void (e instanceof Error ? console.error(e.stack) : console.error(e));
3653
- isDone = !0, reportedError = !0, callback(e, []);
3654
- }
3655
- }), LOADER_PROCESS_NAME = 'Loader Analysis';
3656
- class LoaderObject {
3657
- request;
3658
- path;
3659
- query;
3660
- fragment;
3661
- options;
3662
- ident;
3663
- normal;
3664
- pitch;
3665
- raw;
3666
- type;
3667
- parallel;
3668
- loaderItem;
3669
- constructor(loaderItem, compiler){
3670
- let obj, { request, path, query, fragment, options, ident, normal, pitch, raw, type } = (Object.defineProperty(obj = {
3671
- path: null,
3672
- query: null,
3673
- fragment: null,
3674
- options: null,
3675
- ident: null,
3676
- normal: null,
3677
- pitch: null,
3678
- raw: null,
3679
- data: null,
3680
- pitchExecuted: !1,
3681
- normalExecuted: !1
3682
- }, 'request', {
3683
- enumerable: !0,
3684
- get: ()=>obj.path.replace(/#/g, '\u200b#') + obj.query.replace(/#/g, '\u200b#') + obj.fragment,
3685
- set: (value)=>{
3686
- let splittedRequest = parseResourceWithoutFragment(value.loader);
3687
- if (obj.path = splittedRequest.path, obj.query = splittedRequest.query, obj.fragment = '', obj.options = null === obj.options ? splittedRequest.query ? splittedRequest.query.slice(1) : void 0 : obj.options, 'string' == typeof obj.options && '?' === obj.options[0]) {
3688
- let ident = obj.options.slice(1);
3689
- if ('[[missing ident]]' === ident) throw Error("No ident is provided by referenced loader. When using a function for Rule.use in config you need to provide an 'ident' property for referenced loader options.");
3690
- if (obj.options = compiler.__internal__ruleSet.references.get(ident), void 0 === obj.options) throw Error('Invalid ident is provided by referenced loader');
3691
- obj.ident = ident;
3692
- }
3693
- obj.type = '' === value.type ? void 0 : value.type, null === obj.options || void 0 === obj.options ? obj.query = '' : 'string' == typeof obj.options ? obj.query = `?${obj.options}` : obj.ident ? obj.query = `??${obj.ident}` : 'object' == typeof obj.options && obj.options.ident ? obj.query = `??${obj.options.ident}` : obj.query = `?${JSON.stringify(obj.options)}`;
3730
+ }, templateContent = '';
3731
+ else if (c.template) {
3732
+ let filename = c.template.split('?')[0];
3733
+ [
3734
+ '.js',
3735
+ '.cjs'
3736
+ ].includes(node_path.extname(filename)) && (templateFn = async (data)=>{
3737
+ let context = this.options.context || process.cwd(), templateFilePath = node_path.resolve(context, filename);
3738
+ if (!node_fs.existsSync(templateFilePath)) throw Error(`HtmlRspackPlugin: could not load file \`${filename}\` from \`${context}\``);
3739
+ try {
3740
+ let renderer = plugin_require(templateFilePath);
3741
+ if (!1 === c.templateParameters) return await renderer({});
3742
+ return await renderer(generateRenderData(data));
3743
+ } catch (e) {
3744
+ let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
3745
+ throw error.stack = e.stack, error;
3694
3746
  }
3695
- }), obj.request = loaderItem, Object.preventExtensions && Object.preventExtensions(obj), obj);
3696
- this.request = request, this.path = path, this.query = query, this.fragment = fragment, this.options = options, this.ident = ident, this.normal = normal, this.pitch = pitch, this.raw = raw, this.type = type, this.parallel = !!ident && compiler.__internal__ruleSet.references.get(`${ident}$$parallelism`), this.loaderItem = loaderItem, this.loaderItem.data = this.loaderItem.data ?? {};
3747
+ });
3697
3748
  }
3698
- get pitchExecuted() {
3699
- return this.loaderItem.pitchExecuted;
3749
+ let rawTemplateParameters = c.templateParameters;
3750
+ if (templateParameters = 'function' == typeof rawTemplateParameters ? async (data)=>JSON.stringify(await rawTemplateParameters(JSON.parse(data))) : rawTemplateParameters, 'string' == typeof c.filename) if (filenames = new Set(), c.filename.includes('[name]')) if ('object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename.replace(/\[name\]/g, entryName));
3751
+ else throw Error('HtmlRspackPlugin: filename with `[name]` does not support function entry');
3752
+ else filenames.add(c.filename);
3753
+ else if ('function' == typeof c.filename) if (filenames = new Set(), 'object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename(entryName));
3754
+ else throw Error('HtmlRspackPlugin: function filename does not support function entry');
3755
+ return {
3756
+ filename: filenames ? Array.from(filenames) : void 0,
3757
+ template: c.template,
3758
+ hash: c.hash,
3759
+ title: c.title,
3760
+ favicon: c.favicon,
3761
+ publicPath: c.publicPath,
3762
+ chunks: c.chunks,
3763
+ excludeChunks: c.excludeChunks,
3764
+ chunksSortMode,
3765
+ minify: c.minify,
3766
+ meta,
3767
+ scriptLoading,
3768
+ inject: !0 === configInject ? 'blocking' === scriptLoading ? 'body' : 'head' : !1 === configInject ? 'false' : configInject,
3769
+ base,
3770
+ templateFn,
3771
+ templateContent,
3772
+ templateParameters,
3773
+ uid
3774
+ };
3775
+ }), voidTags = [
3776
+ 'area',
3777
+ 'base',
3778
+ 'br',
3779
+ 'col',
3780
+ 'embed',
3781
+ 'hr',
3782
+ 'img',
3783
+ 'input',
3784
+ 'keygen',
3785
+ 'link',
3786
+ 'meta',
3787
+ 'param',
3788
+ 'source',
3789
+ 'track',
3790
+ 'wbr'
3791
+ ];
3792
+ HtmlRspackPlugin.createHtmlTagObject = (tagName, attributes, innerHTML)=>({
3793
+ tagName,
3794
+ voidTag: voidTags.includes(tagName),
3795
+ attributes: attributes || {},
3796
+ innerHTML
3797
+ }), HtmlRspackPlugin.getCompilationHooks = (compilation)=>{
3798
+ checkCompilation(compilation);
3799
+ let hooks = hooks_compilationHooksMap.get(compilation);
3800
+ return void 0 === hooks && (hooks = {
3801
+ beforeAssetTagGeneration: new AsyncSeriesWaterfallHook([
3802
+ 'data'
3803
+ ]),
3804
+ alterAssetTags: new AsyncSeriesWaterfallHook([
3805
+ 'data'
3806
+ ]),
3807
+ alterAssetTagGroups: new AsyncSeriesWaterfallHook([
3808
+ 'data'
3809
+ ]),
3810
+ afterTemplateExecution: new AsyncSeriesWaterfallHook([
3811
+ 'data'
3812
+ ]),
3813
+ beforeEmit: new AsyncSeriesWaterfallHook([
3814
+ 'data'
3815
+ ]),
3816
+ afterEmit: new AsyncSeriesWaterfallHook([
3817
+ 'data'
3818
+ ])
3819
+ }, hooks_compilationHooksMap.set(compilation, hooks)), hooks;
3820
+ }, HtmlRspackPlugin.version = 5;
3821
+ let IgnorePlugin = base_create(binding_namespaceObject.BuiltinPluginName.IgnorePlugin, (options)=>options), InferAsyncModulesPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InferAsyncModulesPlugin, ()=>{}, 'compilation'), InlineExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InlineExportsPlugin, ()=>{}, 'compilation'), JavascriptModulesPlugin_compilationHooksMap = new WeakMap();
3822
+ class JavascriptModulesPlugin extends RspackBuiltinPlugin {
3823
+ name = binding_namespaceObject.BuiltinPluginName.JavascriptModulesPlugin;
3824
+ affectedHooks = 'compilation';
3825
+ raw() {
3826
+ return createBuiltinPlugin(this.name, void 0);
3700
3827
  }
3701
- set pitchExecuted(value) {
3702
- if (!value) throw Error('pitchExecuted should be true');
3703
- this.loaderItem.pitchExecuted = !0;
3828
+ static getCompilationHooks(compilation) {
3829
+ checkCompilation(compilation);
3830
+ let hooks = JavascriptModulesPlugin_compilationHooksMap.get(compilation);
3831
+ return void 0 === hooks && (hooks = {
3832
+ chunkHash: new SyncHook([
3833
+ 'chunk',
3834
+ 'hash'
3835
+ ])
3836
+ }, JavascriptModulesPlugin_compilationHooksMap.set(compilation, hooks)), hooks;
3704
3837
  }
3705
- get normalExecuted() {
3706
- return this.loaderItem.normalExecuted;
3838
+ }
3839
+ let $assets = Symbol('assets');
3840
+ Object.defineProperty(binding_default().KnownBuildInfo.prototype, node_util.inspect.custom, {
3841
+ enumerable: !0,
3842
+ configurable: !0,
3843
+ value () {
3844
+ return {
3845
+ ...this,
3846
+ assets: this.assets,
3847
+ fileDependencies: this.fileDependencies,
3848
+ contextDependencies: this.contextDependencies,
3849
+ missingDependencies: this.missingDependencies,
3850
+ buildDependencies: this.buildDependencies
3851
+ };
3707
3852
  }
3708
- set normalExecuted(value) {
3709
- if (!value) throw Error('normalExecuted should be true');
3710
- this.loaderItem.normalExecuted = !0;
3853
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'assets', {
3854
+ enumerable: !0,
3855
+ configurable: !0,
3856
+ get () {
3857
+ if (this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets]) return this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets];
3858
+ let assets = new Proxy(Object.create(null), {
3859
+ ownKeys: ()=>this[binding_default().BUILD_INFO_ASSETS_SYMBOL].keys(),
3860
+ getOwnPropertyDescriptor: ()=>({
3861
+ enumerable: !0,
3862
+ configurable: !0
3863
+ })
3864
+ });
3865
+ return Object.defineProperty(this[binding_default().BUILD_INFO_ASSETS_SYMBOL], $assets, {
3866
+ enumerable: !1,
3867
+ configurable: !0,
3868
+ value: assets
3869
+ }), assets;
3711
3870
  }
3712
- set noPitch(value) {
3713
- if (!value) throw Error('noPitch should be true');
3714
- this.loaderItem.noPitch = !0;
3871
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'fileDependencies', {
3872
+ enumerable: !0,
3873
+ configurable: !0,
3874
+ get () {
3875
+ return new Set(this[binding_default().BUILD_INFO_FILE_DEPENDENCIES_SYMBOL]);
3715
3876
  }
3716
- shouldYield() {
3717
- return this.request.startsWith(BUILTIN_LOADER_PREFIX);
3877
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'contextDependencies', {
3878
+ enumerable: !0,
3879
+ configurable: !0,
3880
+ get () {
3881
+ return new Set(this[binding_default().BUILD_INFO_CONTEXT_DEPENDENCIES_SYMBOL]);
3718
3882
  }
3719
- static __from_binding(loaderItem, compiler) {
3720
- return new this(loaderItem, compiler);
3883
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'missingDependencies', {
3884
+ enumerable: !0,
3885
+ configurable: !0,
3886
+ get () {
3887
+ return new Set(this[binding_default().BUILD_INFO_MISSING_DEPENDENCIES_SYMBOL]);
3721
3888
  }
3722
- static __to_binding(loader) {
3723
- return loader.loaderItem;
3889
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'buildDependencies', {
3890
+ enumerable: !0,
3891
+ configurable: !0,
3892
+ get () {
3893
+ return new Set(this[binding_default().BUILD_INFO_BUILD_DEPENDENCIES_SYMBOL]);
3724
3894
  }
3725
- }
3726
- class JsSourceMap {
3727
- static __from_binding(map) {
3728
- return isNil(map) ? void 0 : ((input)=>{
3729
- let s;
3730
- if (Buffer.isBuffer(input)) s = input.toString('utf8');
3731
- else if (input && 'object' == typeof input) return input;
3732
- else if ('string' == typeof input) s = input;
3733
- else throw Error('Buffer or string or object expected');
3734
- return JSON.parse(s);
3735
- })(map);
3895
+ });
3896
+ let knownBuildInfoFields = new Set([
3897
+ 'assets',
3898
+ 'fileDependencies',
3899
+ 'contextDependencies',
3900
+ 'missingDependencies',
3901
+ 'buildDependencies'
3902
+ ]);
3903
+ Object.defineProperty(binding_default().NormalModule.prototype, 'identifier', {
3904
+ enumerable: !0,
3905
+ configurable: !0,
3906
+ value () {
3907
+ return this[binding_default().MODULE_IDENTIFIER_SYMBOL];
3736
3908
  }
3737
- static __to_binding(map) {
3738
- return serializeObject(map);
3909
+ }), Object.defineProperty(binding_default().NormalModule.prototype, 'originalSource', {
3910
+ enumerable: !0,
3911
+ configurable: !0,
3912
+ value () {
3913
+ let originalSource = this._originalSource();
3914
+ return originalSource ? SourceAdapter.fromBinding(originalSource) : null;
3915
+ }
3916
+ }), Object.defineProperty(binding_default().NormalModule.prototype, 'emitFile', {
3917
+ enumerable: !0,
3918
+ configurable: !0,
3919
+ value (filename, source, assetInfo) {
3920
+ return this._emitFile(filename, SourceAdapter.toBinding(source), assetInfo);
3921
+ }
3922
+ }), Object.defineProperty(binding_default().NormalModule, 'getCompilationHooks', {
3923
+ enumerable: !0,
3924
+ configurable: !0,
3925
+ value (compilation) {
3926
+ if (!(binding_default().COMPILATION_HOOKS_MAP_SYMBOL in compilation)) throw TypeError("The 'compilation' argument must be an instance of Compilation");
3927
+ let compilationHooksMap = compilation[binding_default().COMPILATION_HOOKS_MAP_SYMBOL], hooks = compilationHooksMap.get(compilation);
3928
+ return void 0 === hooks && (hooks = {
3929
+ loader: new SyncHook([
3930
+ 'loaderContext',
3931
+ 'module'
3932
+ ]),
3933
+ readResource: new HookMap(()=>new AsyncSeriesBailHook([
3934
+ 'loaderContext'
3935
+ ]))
3936
+ }, compilationHooksMap.set(compilation, hooks)), hooks;
3937
+ }
3938
+ });
3939
+ class NonErrorEmittedError extends Error {
3940
+ constructor(error){
3941
+ super(), this.name = 'NonErrorEmittedError', this.message = `(Emitted value instead of an instance of Error) ${error}`;
3739
3942
  }
3740
3943
  }
3741
- function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
3742
- return loaderContext.loaders?.length && index < loaderContext.loaders.length && index >= 0 && loaderContext.loaders[index] ? loaderContext.loaders[index] : null;
3944
+ class DeadlockRiskError extends Error {
3945
+ constructor(message){
3946
+ super(message), this.name = 'DeadlockRiskError', this.stack = '';
3947
+ }
3743
3948
  }
3744
- async function runLoaders(compiler, context) {
3745
- var buildInfo;
3746
- let loaderState = context.loaderState, pitch = loaderState === binding_namespaceObject.JsLoaderState.Pitching, { resource } = context, uuid = JavaScriptTracer.uuid();
3747
- JavaScriptTracer.startAsync({
3748
- name: 'run_js_loaders',
3749
- processName: LOADER_PROCESS_NAME,
3750
- uuid,
3751
- ph: 'b',
3752
- args: {
3753
- is_pitch: pitch,
3754
- resource: resource
3755
- }
3756
- });
3757
- let splittedResource = resource && parsePathQueryFragment(resource), resourcePath = splittedResource ? splittedResource.path : void 0, resourceQuery = splittedResource ? splittedResource.query : void 0, resourceFragment = splittedResource ? splittedResource.fragment : void 0, contextDirectory = resourcePath ? function(path) {
3758
- if ('/' === path) return '/';
3759
- let i = path.lastIndexOf('/'), j = path.lastIndexOf('\\'), i2 = path.indexOf('/'), j2 = path.indexOf('\\'), idx = i > j ? i : j, idx2 = i > j ? i2 : j2;
3760
- return idx < 0 ? path : idx === idx2 ? path.slice(0, idx + 1) : path.slice(0, idx);
3761
- }(resourcePath) : null, fileDependencies = context.fileDependencies, contextDependencies = context.contextDependencies, missingDependencies = context.missingDependencies, buildDependencies = context.buildDependencies, loaderContext = {};
3762
- loaderContext.loaders = context.loaderItems.map((item)=>LoaderObject.__from_binding(item, compiler)), loaderContext.hot = context.hot, loaderContext.context = contextDirectory, loaderContext.resourcePath = resourcePath, loaderContext.resourceQuery = resourceQuery, loaderContext.resourceFragment = resourceFragment, loaderContext.dependency = loaderContext.addDependency = function(file) {
3763
- fileDependencies.push(file);
3764
- }, loaderContext.addContextDependency = function(context) {
3765
- contextDependencies.push(context);
3766
- }, loaderContext.addMissingDependency = function(context) {
3767
- missingDependencies.push(context);
3768
- }, loaderContext.addBuildDependency = function(file) {
3769
- buildDependencies.push(file);
3770
- }, loaderContext.getDependencies = function() {
3771
- return fileDependencies.slice();
3772
- }, loaderContext.getContextDependencies = function() {
3773
- return contextDependencies.slice();
3774
- }, loaderContext.getMissingDependencies = function() {
3775
- return missingDependencies.slice();
3776
- }, loaderContext.clearDependencies = function() {
3777
- fileDependencies.length = 0, contextDependencies.length = 0, missingDependencies.length = 0, context.cacheable = !0;
3778
- }, loaderContext.importModule = function(request, userOptions, callback) {
3779
- JavaScriptTracer.startAsync({
3780
- name: 'importModule',
3781
- processName: LOADER_PROCESS_NAME,
3782
- uuid,
3783
- args: {
3784
- is_pitch: pitch,
3785
- resource: resource
3786
- }
3787
- });
3788
- let options = userOptions || {};
3789
- function finalCallback(onError, onDone) {
3790
- return function(err, res) {
3791
- if (err) JavaScriptTracer.endAsync({
3792
- name: 'importModule',
3793
- processName: LOADER_PROCESS_NAME,
3949
+ class ValidationError extends Error {
3950
+ constructor(message){
3951
+ super(message), this.name = 'ValidationError';
3952
+ }
3953
+ }
3954
+ class JavaScriptTracer {
3955
+ static state = 'uninitialized';
3956
+ static startTime;
3957
+ static events;
3958
+ static layer;
3959
+ static output;
3960
+ static session;
3961
+ static counter = 10000;
3962
+ static async initJavaScriptTrace(layer, output) {
3963
+ let { Session } = await import("node:inspector");
3964
+ this.session = new Session(), this.layer = layer, this.output = output, this.events = [], this.state = 'on', this.startTime = process.hrtime.bigint();
3965
+ }
3966
+ static uuid() {
3967
+ return this.counter++;
3968
+ }
3969
+ static isEnabled() {
3970
+ return 'on' === this.state;
3971
+ }
3972
+ static initCpuProfiler() {
3973
+ this.isEnabled() && (this.session.connect(), this.session.post('Profiler.enable'), this.session.post('Profiler.start'));
3974
+ }
3975
+ static async cleanupJavaScriptTrace() {
3976
+ if ('uninitialized' === this.state) throw Error('JavaScriptTracer is not initialized, please call initJavaScriptTrace first');
3977
+ if (!this.isEnabled()) return;
3978
+ let profileHandler = (err, param)=>{
3979
+ let cpu_profile;
3980
+ if (err ? console.error('Error stopping profiler:', err) : cpu_profile = param.profile, cpu_profile) {
3981
+ let uuid = this.uuid();
3982
+ this.pushEvent({
3983
+ name: 'Profile',
3984
+ ph: 'P',
3985
+ trackName: 'JavaScript CPU Profiler',
3986
+ processName: 'JavaScript CPU',
3794
3987
  uuid,
3988
+ ...this.getCommonEv(),
3989
+ categories: [
3990
+ 'disabled-by-default-v8.cpu_profiler'
3991
+ ],
3795
3992
  args: {
3796
- is_pitch: pitch,
3797
- resource: resource
3993
+ data: {
3994
+ startTime: 0
3995
+ }
3798
3996
  }
3799
- }), onError(err);
3800
- else {
3801
- for (let dep of res.buildDependencies)loaderContext.addBuildDependency(dep);
3802
- for (let dep of res.contextDependencies)loaderContext.addContextDependency(dep);
3803
- for (let dep of res.missingDependencies)loaderContext.addMissingDependency(dep);
3804
- for (let dep of res.fileDependencies)loaderContext.addDependency(dep);
3805
- !1 === res.cacheable && loaderContext.cacheable(!1), JavaScriptTracer.endAsync({
3806
- name: 'importModule',
3807
- processName: LOADER_PROCESS_NAME,
3808
- uuid,
3809
- args: {
3810
- is_pitch: pitch,
3811
- resource: resource
3997
+ }), this.pushEvent({
3998
+ name: 'ProfileChunk',
3999
+ ph: 'P',
4000
+ trackName: 'JavaScript CPU Profiler',
4001
+ processName: 'JavaScript CPU',
4002
+ ...this.getCommonEv(),
4003
+ categories: [
4004
+ 'disabled-by-default-v8.cpu_profiler'
4005
+ ],
4006
+ uuid,
4007
+ args: {
4008
+ data: {
4009
+ cpuProfile: cpu_profile,
4010
+ timeDeltas: cpu_profile.timeDeltas
3812
4011
  }
3813
- }), res.error ? onError(compiler.__internal__takeModuleExecutionResult(res.id) ?? Error(res.error)) : onDone(compiler.__internal__takeModuleExecutionResult(res.id));
4012
+ }
4013
+ });
4014
+ }
4015
+ };
4016
+ await new Promise((resolve, reject)=>{
4017
+ this.session.post('Profiler.stop', (err, params)=>{
4018
+ if (err) reject(err);
4019
+ else try {
4020
+ profileHandler(err, params), resolve();
4021
+ } catch (err) {
4022
+ reject(err);
3814
4023
  }
3815
- };
3816
- }
3817
- return callback ? compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback((err)=>callback(err), (res)=>callback(void 0, res))) : new Promise((resolve, reject)=>{
3818
- compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback(reject, resolve));
3819
- });
3820
- }, Object.defineProperty(loaderContext, 'resource', {
3821
- enumerable: !0,
3822
- get: ()=>{
3823
- if (void 0 !== loaderContext.resourcePath) return loaderContext.resourcePath.replace(/#/g, '\u200b#') + loaderContext.resourceQuery.replace(/#/g, '\u200b#') + loaderContext.resourceFragment;
3824
- },
3825
- set: (value)=>{
3826
- let splittedResource = value && parsePathQueryFragment(value);
3827
- loaderContext.resourcePath = splittedResource ? splittedResource.path : void 0, loaderContext.resourceQuery = splittedResource ? splittedResource.query : void 0, loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : void 0;
3828
- }
3829
- }), Object.defineProperty(loaderContext, 'request', {
3830
- enumerable: !0,
3831
- get: ()=>loaderContext.loaders.map((o)=>o.request).concat(loaderContext.resource || '').join('!')
3832
- }), Object.defineProperty(loaderContext, 'remainingRequest', {
3833
- enumerable: !0,
3834
- get: ()=>loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource ? '' : loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
3835
- }), Object.defineProperty(loaderContext, 'currentRequest', {
3836
- enumerable: !0,
3837
- get: ()=>loaderContext.loaders.slice(loaderContext.loaderIndex).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
3838
- }), Object.defineProperty(loaderContext, 'previousRequest', {
3839
- enumerable: !0,
3840
- get: ()=>loaderContext.loaders.slice(0, loaderContext.loaderIndex).map((o)=>o.request).join('!')
3841
- }), Object.defineProperty(loaderContext, 'query', {
3842
- enumerable: !0,
3843
- get: ()=>{
3844
- let entry = loaderContext.loaders[loaderContext.loaderIndex];
3845
- return entry.options && 'object' == typeof entry.options ? entry.options : entry.query;
3846
- }
3847
- }), loaderContext.version = 2, loaderContext.sourceMap = compiler.options.devtool ? isUseSourceMap(compiler.options.devtool) : context._module.useSourceMap ?? !1, loaderContext.mode = compiler.options.mode, Object.assign(loaderContext, compiler.options.loader);
3848
- let getResolveContext = ()=>({
3849
- fileDependencies: {
3850
- add: (d)=>{
3851
- loaderContext.addDependency(d);
3852
- }
3853
- },
3854
- contextDependencies: {
3855
- add: (d)=>{
3856
- loaderContext.addContextDependency(d);
3857
- }
3858
- },
3859
- missingDependencies: {
3860
- add: (d)=>{
3861
- loaderContext.addMissingDependency(d);
3862
- }
3863
- }
3864
- }), getResolver = memoize(()=>compiler._lastCompilation.resolverFactory.get('normal'));
3865
- loaderContext.resolve = function(context, request, callback) {
3866
- getResolver().resolve({}, context, request, getResolveContext(), callback);
3867
- }, loaderContext.getResolve = function(options) {
3868
- let resolver = getResolver(), child = options ? resolver.withOptions(options) : resolver;
3869
- return (context, request, callback)=>callback ? void child.resolve({}, context, request, getResolveContext(), callback) : new Promise((resolve, reject)=>{
3870
- child.resolve({}, context, request, getResolveContext(), (err, result)=>{
3871
- err ? reject(err) : resolve(result);
3872
- });
3873
4024
  });
3874
- }, loaderContext.getLogger = function(name) {
3875
- return compiler._lastCompilation.getLogger([
3876
- name,
3877
- resource
3878
- ].filter(Boolean).join('|'));
3879
- }, loaderContext.rootContext = compiler.context, loaderContext.emitError = function(e) {
3880
- e instanceof Error || (e = new NonErrorEmittedError(e));
3881
- let error = new ModuleError(e, {
3882
- from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
3883
- });
3884
- error.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
3885
- error,
3886
- severity: binding_namespaceObject.JsRspackSeverity.Error
4025
+ }), this.state = 'off';
4026
+ }
4027
+ static getTs() {
4028
+ return process.hrtime.bigint() - this.startTime;
4029
+ }
4030
+ static getCommonEv() {
4031
+ return {
4032
+ ts: this.getTs(),
4033
+ cat: 'rspack'
4034
+ };
4035
+ }
4036
+ static pushEvent(event) {
4037
+ let stringifiedArgs = Object.keys(event.args || {}).reduce((acc, key)=>(acc[key] = JSON.stringify(event.args[key]), acc), {});
4038
+ this.events.push({
4039
+ ...event,
4040
+ args: stringifiedArgs
3887
4041
  });
3888
- }, loaderContext.emitWarning = function(e) {
3889
- e instanceof Error || (e = new NonErrorEmittedError(e));
3890
- let warning = new ModuleWarning(e, {
3891
- from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
4042
+ }
4043
+ static startAsync(events) {
4044
+ this.isEnabled() && this.pushEvent({
4045
+ ...this.getCommonEv(),
4046
+ ...events,
4047
+ ph: 'b'
3892
4048
  });
3893
- warning.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
3894
- error: warning,
3895
- severity: binding_namespaceObject.JsRspackSeverity.Warn
4049
+ }
4050
+ static endAsync(events) {
4051
+ this.isEnabled() && this.pushEvent({
4052
+ ...this.getCommonEv(),
4053
+ ...events,
4054
+ ph: 'e'
3896
4055
  });
3897
- }, loaderContext.emitFile = function(name, content, sourceMap, assetInfo) {
3898
- var devtool;
3899
- let source;
3900
- sourceMap ? ('string' == typeof sourceMap && (loaderContext.sourceMap || compiler.options.devtool && (devtool = compiler.options.devtool) && devtool.includes('source-map') && !isUseSourceMap(devtool)) && (source = new index_js_namespaceObject.OriginalSource(content, makePathsRelative(contextDirectory, sourceMap, compiler))), loaderContext.sourceMap && (source = new index_js_namespaceObject.SourceMapSource(content, name, makePathsRelative(contextDirectory, sourceMap, compiler)))) : source = new index_js_namespaceObject.RawSource(content), loaderContext._module.emitFile(name, source, assetInfo);
3901
- }, loaderContext.fs = compiler.inputFileSystem, loaderContext.experiments = {
3902
- emitDiagnostic: (diagnostic)=>{
3903
- let d = Object.assign({}, diagnostic, {
3904
- message: 'warning' === diagnostic.severity ? `ModuleWarning: ${diagnostic.message}` : `ModuleError: ${diagnostic.message}`,
3905
- moduleIdentifier: context._module.identifier()
3906
- });
3907
- compiler._lastCompilation.__internal__pushDiagnostic((0, binding_namespaceObject.formatDiagnostic)(d));
3908
- }
3909
- };
3910
- let getAbsolutify = memoize(()=>absolutify.bindCache(compiler.root)), getAbsolutifyInContext = memoize(()=>absolutify.bindContextCache(contextDirectory, compiler.root)), getContextify = memoize(()=>contextify.bindCache(compiler.root)), getContextifyInContext = memoize(()=>contextify.bindContextCache(contextDirectory, compiler.root));
3911
- loaderContext.utils = {
3912
- absolutify: (context, request)=>context === contextDirectory ? getAbsolutifyInContext()(request) : getAbsolutify()(context, request),
3913
- contextify: (context, request)=>context === contextDirectory ? getContextifyInContext()(request) : getContextify()(context, request),
3914
- createHash: (type)=>createHash_createHash(type || compiler._lastCompilation.outputOptions.hashFunction)
3915
- }, loaderContext._compiler = compiler, loaderContext._compilation = compiler._lastCompilation, loaderContext._module = context._module, loaderContext.getOptions = ()=>{
3916
- let loader = getCurrentLoader(loaderContext), options = loader?.options;
3917
- if ('string' == typeof options) if (options.startsWith('{') && options.endsWith('}')) try {
3918
- options = JSON.parse(options);
3919
- } catch (e) {
3920
- throw Error(`JSON parsing failed for loader's string options: ${e.message}`);
4056
+ }
4057
+ }
4058
+ let CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
4059
+ function createMessage(method) {
4060
+ return `Abstract method${method ? ` ${method}` : ''}. Must be overridden.`;
4061
+ }
4062
+ class Message extends Error {
4063
+ constructor(){
4064
+ super(), this.stack = void 0, Error.captureStackTrace(this);
4065
+ let match = this.stack.split('\n')[3].match(CURRENT_METHOD_REGEXP);
4066
+ this.message = match?.[1] ? createMessage(match[1]) : createMessage();
4067
+ }
4068
+ }
4069
+ class AbstractMethodError extends lib_WebpackError {
4070
+ constructor(){
4071
+ super(new Message().message), this.name = 'AbstractMethodError';
4072
+ }
4073
+ }
4074
+ class Hash {
4075
+ update() {
4076
+ throw new AbstractMethodError();
4077
+ }
4078
+ digest() {
4079
+ throw new AbstractMethodError();
4080
+ }
4081
+ }
4082
+ let MAX_SHORT_STRING = -4 & Math.floor(16368);
4083
+ class WasmHash {
4084
+ exports;
4085
+ instancesPool;
4086
+ buffered;
4087
+ mem;
4088
+ chunkSize;
4089
+ digestSize;
4090
+ constructor(instance, instancesPool, chunkSize, digestSize){
4091
+ let exports = instance.exports;
4092
+ exports.init(), this.exports = exports, this.mem = Buffer.from(exports.memory.buffer, 0, 65536), this.buffered = 0, this.instancesPool = instancesPool, this.chunkSize = chunkSize, this.digestSize = digestSize;
4093
+ }
4094
+ reset() {
4095
+ this.buffered = 0, this.exports.init();
4096
+ }
4097
+ update(data, encoding) {
4098
+ if ('string' == typeof data) {
4099
+ let normalizedData = data;
4100
+ for(; normalizedData.length > MAX_SHORT_STRING;)this._updateWithShortString(normalizedData.slice(0, MAX_SHORT_STRING), encoding), normalizedData = normalizedData.slice(MAX_SHORT_STRING);
4101
+ return this._updateWithShortString(normalizedData, encoding), this;
3921
4102
  }
3922
- else options = node_querystring.parse(options);
3923
- return null == options && (options = {}), options;
3924
- };
3925
- let compilation = compiler._lastCompilation, step = 0;
3926
- for(; compilation;)if (binding_namespaceObject.NormalModule.getCompilationHooks(compilation).loader.call(loaderContext, loaderContext._module), compilation = compilation.compiler.parentCompilation, ++step > 1000) throw Error('Too many nested child compiler, exceeded max limitation 1000');
3927
- Object.defineProperty(loaderContext, 'loaderIndex', {
3928
- enumerable: !0,
3929
- get: ()=>context.loaderIndex,
3930
- set: (loaderIndex)=>context.loaderIndex = loaderIndex
3931
- }), Object.defineProperty(loaderContext, 'cacheable', {
3932
- enumerable: !0,
3933
- get: ()=>(cacheable)=>{
3934
- !1 === cacheable && (context.cacheable = cacheable);
3935
- }
3936
- }), Object.defineProperty(loaderContext, 'data', {
3937
- enumerable: !0,
3938
- get: ()=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data,
3939
- set: (data)=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data = data
3940
- }), loaderContext.__internal__setParseMeta = (key, value)=>{
3941
- context.__internal__parseMeta[key] = value;
3942
- };
3943
- let enableParallelism = (currentLoaderObject)=>currentLoaderObject?.parallel, isomorphoicRun = async (fn, args)=>{
3944
- let result, currentLoaderObject = getCurrentLoader(loaderContext), parallelism = enableParallelism(currentLoaderObject), pitch = loaderState === binding_namespaceObject.JsLoaderState.Pitching, loaderName = function(loaderPath, cwd = '') {
3945
- let res = loaderPath.replace(cwd, '');
3946
- if (!node_path.isAbsolute(res)) return res;
3947
- let nms = '/node_modules/', idx = res.lastIndexOf(nms);
3948
- if (-1 !== idx) {
3949
- res = res.slice(idx + nms.length);
3950
- let ln = 'loader', lnIdx = res.lastIndexOf(ln);
3951
- lnIdx > -1 && (res = res.slice(0, lnIdx + ln.length));
4103
+ return this._updateWithBuffer(data), this;
4104
+ }
4105
+ _updateWithShortString(data, encoding) {
4106
+ let endPos, { exports, buffered, mem, chunkSize } = this;
4107
+ if (data.length < 70) if (encoding && 'utf-8' !== encoding && 'utf8' !== encoding) if ('latin1' === encoding) {
4108
+ endPos = buffered;
4109
+ for(let i = 0; i < data.length; i++){
4110
+ let cc = data.charCodeAt(i);
4111
+ mem[endPos++] = cc;
3952
4112
  }
3953
- return res;
3954
- }(currentLoaderObject.request);
3955
- if (JavaScriptTracer.startAsync({
3956
- name: loaderName,
3957
- trackName: loaderName,
3958
- processName: LOADER_PROCESS_NAME,
3959
- uuid,
3960
- args: {
3961
- is_pitch: pitch,
3962
- resource: resource
4113
+ } else endPos = buffered + mem.write(data, buffered, encoding);
4114
+ else {
4115
+ endPos = buffered;
4116
+ for(let i = 0; i < data.length; i++){
4117
+ let cc = data.charCodeAt(i);
4118
+ if (cc < 0x80) mem[endPos++] = cc;
4119
+ else if (cc < 0x800) mem[endPos] = cc >> 6 | 0xc0, mem[endPos + 1] = 0x3f & cc | 0x80, endPos += 2;
4120
+ else {
4121
+ endPos += mem.write(data.slice(i), endPos, encoding);
4122
+ break;
4123
+ }
3963
4124
  }
3964
- }), parallelism) {
3965
- let normalModule, workerLoaderContext;
3966
- result = await service_run(loaderName, {
3967
- loaderContext: (normalModule = loaderContext._module instanceof binding_namespaceObject.NormalModule ? loaderContext._module : void 0, Object.assign(workerLoaderContext = {
3968
- hot: loaderContext.hot,
3969
- context: loaderContext.context,
3970
- resourcePath: loaderContext.resourcePath,
3971
- resourceQuery: loaderContext.resourceQuery,
3972
- resourceFragment: loaderContext.resourceFragment,
3973
- resource: loaderContext.resource,
3974
- mode: loaderContext.mode,
3975
- sourceMap: loaderContext.sourceMap,
3976
- rootContext: loaderContext.rootContext,
3977
- loaderIndex: loaderContext.loaderIndex,
3978
- loaders: loaderContext.loaders.map((item)=>{
3979
- let options = item.options;
3980
- return (!item.parallel || item.request.startsWith(BUILTIN_LOADER_PREFIX)) && (options = void 0), {
3981
- ...item,
3982
- options,
3983
- pitch: void 0,
3984
- normal: void 0,
3985
- normalExecuted: item.normalExecuted,
3986
- pitchExecuted: item.pitchExecuted
3987
- };
3988
- }),
3989
- __internal__workerInfo: {
3990
- hashFunction: compiler._lastCompilation.outputOptions.hashFunction
3991
- },
3992
- _compiler: {
3993
- options: {
3994
- experiments: {
3995
- css: !0
3996
- }
3997
- }
3998
- },
3999
- _compilation: {
4000
- options: {
4001
- output: {
4002
- environment: compiler._lastCompilation.outputOptions.environment
4003
- }
4004
- },
4005
- outputOptions: {
4006
- hashSalt: compiler._lastCompilation.outputOptions.hashSalt,
4007
- hashFunction: compiler._lastCompilation.outputOptions.hashFunction,
4008
- hashDigest: compiler._lastCompilation.outputOptions.hashDigest,
4009
- hashDigestLength: compiler._lastCompilation.outputOptions.hashDigestLength
4010
- }
4011
- },
4012
- _module: {
4013
- type: loaderContext._module.type,
4014
- identifier: loaderContext._module.identifier(),
4015
- matchResource: normalModule?.matchResource,
4016
- request: normalModule?.request,
4017
- userRequest: normalModule?.userRequest,
4018
- rawRequest: normalModule?.rawRequest
4019
- }
4020
- }, compiler.options.loader), workerLoaderContext),
4021
- loaderState,
4022
- args
4023
- }, {
4024
- handleIncomingRequest (requestType, ...args) {
4025
- switch(requestType){
4026
- case "AddDependency":
4027
- loaderContext.addDependency(args[0]);
4028
- break;
4029
- case "AddContextDependency":
4030
- loaderContext.addContextDependency(args[0]);
4031
- break;
4032
- case "AddMissingDependency":
4033
- loaderContext.addMissingDependency(args[0]);
4034
- break;
4035
- case "AddBuildDependency":
4036
- loaderContext.addBuildDependency(args[0]);
4037
- break;
4038
- case "GetDependencies":
4039
- return loaderContext.getDependencies();
4040
- case "GetContextDependencies":
4041
- return loaderContext.getContextDependencies();
4042
- case "GetMissingDependencies":
4043
- return loaderContext.getMissingDependencies();
4044
- case "ClearDependencies":
4045
- loaderContext.clearDependencies();
4046
- break;
4047
- case "Resolve":
4048
- return new Promise((resolve, reject)=>{
4049
- loaderContext.resolve(args[0], args[1], (err, result)=>{
4050
- err ? reject(err) : resolve(result);
4051
- });
4052
- });
4053
- case "GetResolve":
4054
- return new Promise((resolve, reject)=>{
4055
- loaderContext.getResolve(args[0])(args[1], args[2], (err, result)=>{
4056
- err ? reject(err) : resolve(result);
4057
- });
4058
- });
4059
- case "GetLogger":
4060
- {
4061
- let [type, name, arg] = args;
4062
- loaderContext.getLogger(name)[type](...arg);
4063
- break;
4064
- }
4065
- case "EmitError":
4066
- {
4067
- let workerError = args[0], error = Error(workerError.message);
4068
- error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitError(error);
4069
- break;
4070
- }
4071
- case "EmitWarning":
4072
- {
4073
- let workerError = args[0], error = Error(workerError.message);
4074
- error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitWarning(error);
4075
- break;
4076
- }
4077
- case "EmitFile":
4078
- {
4079
- let [name, content, sourceMap, assetInfo] = args;
4080
- loaderContext.emitFile(name, content, sourceMap, assetInfo);
4081
- break;
4082
- }
4083
- case "EmitDiagnostic":
4084
- {
4085
- let diagnostic = args[0];
4086
- loaderContext.experiments.emitDiagnostic(diagnostic);
4087
- break;
4088
- }
4089
- case "SetCacheable":
4090
- {
4091
- let cacheable = args[0];
4092
- loaderContext.cacheable(cacheable);
4093
- break;
4094
- }
4095
- case "ImportModule":
4096
- return loaderContext.importModule(args[0], args[1]);
4097
- case "UpdateLoaderObjects":
4098
- {
4099
- let updates = args[0];
4100
- loaderContext.loaders = loaderContext.loaders.map((item, index)=>{
4101
- let update = updates[index];
4102
- return item.loaderItem.data = update.data, update.pitchExecuted && (item.pitchExecuted = !0), update.normalExecuted && (item.normalExecuted = !0), item;
4103
- });
4104
- break;
4105
- }
4106
- case "CompilationGetPath":
4107
- {
4108
- let filename = args[0], data = args[1];
4109
- return compiler._lastCompilation.getPath(filename, data);
4110
- }
4111
- case "CompilationGetPathWithInfo":
4112
- {
4113
- let filename = args[0], data = args[1];
4114
- return compiler._lastCompilation.getPathWithInfo(filename, data);
4115
- }
4116
- case "CompilationGetAssetPath":
4117
- {
4118
- let filename = args[0], data = args[1];
4119
- return compiler._lastCompilation.getAssetPath(filename, data);
4120
- }
4121
- case "CompilationGetAssetPathWithInfo":
4122
- {
4123
- let filename = args[0], data = args[1];
4124
- return compiler._lastCompilation.getAssetPathWithInfo(filename, data);
4125
- }
4126
- default:
4127
- throw Error(`Unknown request type: ${requestType}`);
4128
- }
4129
- }
4130
- }, 'object' == typeof currentLoaderObject?.parallel ? currentLoaderObject.parallel : void 0) || [];
4131
- } else loaderState === binding_namespaceObject.JsLoaderState.Normal && function(args, raw) {
4132
- if (!raw && args[0] instanceof Uint8Array) {
4133
- var buf;
4134
- let isShared, str;
4135
- args[0] = (isShared = (buf = args[0]).buffer instanceof SharedArrayBuffer || buf.buffer.constructor?.name === 'SharedArrayBuffer', 0xfeff === (str = decoder.decode(isShared ? Buffer.from(buf) : buf)).charCodeAt(0) ? str.slice(1) : str);
4136
- } else raw && 'string' == typeof args[0] && (args[0] = Buffer.from(args[0], 'utf-8'));
4137
- raw && args[0] instanceof Uint8Array && !Buffer.isBuffer(args[0]) && (args[0] = Buffer.from(args[0].buffer));
4138
- }(args, !!currentLoaderObject?.raw), result = await utils_runSyncOrAsync(fn, loaderContext, args) || [];
4139
- return JavaScriptTracer.endAsync({
4140
- name: loaderName,
4141
- trackName: loaderName,
4142
- processName: LOADER_PROCESS_NAME,
4143
- uuid,
4144
- args: {
4145
- is_pitch: pitch,
4146
- resource: resource
4147
- }
4148
- }), result;
4149
- };
4150
- try {
4151
- switch(loaderState){
4152
- case binding_namespaceObject.JsLoaderState.Pitching:
4153
- for(; loaderContext.loaderIndex < loaderContext.loaders.length;){
4154
- let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4155
- if (currentLoaderObject.shouldYield()) break;
4156
- if (currentLoaderObject.pitchExecuted) {
4157
- loaderContext.loaderIndex += 1;
4158
- continue;
4159
- }
4160
- await utils_loadLoader(currentLoaderObject, compiler);
4161
- let fn = currentLoaderObject.pitch;
4162
- if (parallelism && fn || (currentLoaderObject.pitchExecuted = !0), !fn) continue;
4163
- let args = await isomorphoicRun(fn, [
4164
- loaderContext.remainingRequest,
4165
- loaderContext.previousRequest,
4166
- currentLoaderObject.loaderItem.data
4167
- ]);
4168
- if (args.some((value)=>void 0 !== value)) {
4169
- let [content, sourceMap, additionalData] = args;
4170
- context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = serializeObject(sourceMap), context.additionalData = additionalData || void 0;
4171
- break;
4172
- }
4173
- }
4174
- break;
4175
- case binding_namespaceObject.JsLoaderState.Normal:
4176
- {
4177
- let content = context.content, sourceMap = JsSourceMap.__from_binding(context.sourceMap), additionalData = context.additionalData;
4178
- for(; loaderContext.loaderIndex >= 0;){
4179
- let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4180
- if (currentLoaderObject.shouldYield()) break;
4181
- if (currentLoaderObject.normalExecuted) {
4182
- loaderContext.loaderIndex--;
4183
- continue;
4184
- }
4185
- await utils_loadLoader(currentLoaderObject, compiler);
4186
- let fn = currentLoaderObject.normal;
4187
- parallelism && fn || (currentLoaderObject.normalExecuted = !0), fn && ([content, sourceMap, additionalData] = await isomorphoicRun(fn, [
4188
- content,
4189
- sourceMap,
4190
- additionalData
4191
- ]));
4192
- }
4193
- context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = JsSourceMap.__to_binding(sourceMap), context.additionalData = additionalData || void 0, context.__internal__utf8Hint = 'string' == typeof content;
4194
- break;
4195
- }
4196
- default:
4197
- throw Error(`Unexpected loader runner state: ${loaderState}`);
4198
4125
  }
4199
- context.loaderItems = loaderContext.loaders.map((item)=>LoaderObject.__to_binding(item));
4200
- } catch (e) {
4201
- if ('object' != typeof e || null === e) {
4202
- let error = Error(`(Emitted value instead of an instance of Error) ${e}`);
4203
- error.name = 'NonErrorEmittedError', context.__internal__error = error;
4204
- } else context.__internal__error = e;
4205
- }
4206
- return JavaScriptTracer.endAsync({
4207
- name: 'run_js_loaders',
4208
- uuid,
4209
- args: {
4210
- is_pitch: pitch,
4211
- resource: resource
4212
- }
4213
- }), compiler.options?.cache && Object.keys(buildInfo = context._module.buildInfo).some((key)=>!knownBuildInfoFields.has(key)) && buildInfo[binding_default().COMMIT_CUSTOM_FIELDS_SYMBOL](), context;
4214
- }
4215
- let loader_runner_PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
4216
- function parsePathQueryFragment(str) {
4217
- let match = loader_runner_PATH_QUERY_FRAGMENT_REGEXP.exec(str);
4218
- return {
4219
- path: match?.[1].replace(/\u200b(.)/g, '$1') || '',
4220
- query: match?.[2] ? match[2].replace(/\u200b(.)/g, '$1') : '',
4221
- fragment: match?.[3] || ''
4222
- };
4223
- }
4224
- let BUILTIN_LOADER_PREFIX = 'builtin:';
4225
- function createRawModuleRuleUses(uses, path, options) {
4226
- var uses1, path1, options1;
4227
- let normalizeRuleSetUseItem = (item)=>'string' == typeof item ? {
4228
- loader: item
4229
- } : item;
4230
- return uses1 = Array.isArray(uses) ? [
4231
- ...uses
4232
- ].map(normalizeRuleSetUseItem) : [
4233
- normalizeRuleSetUseItem(uses)
4234
- ], path1 = path, options1 = options, uses1.length ? uses1.filter(Boolean).map((use, index)=>{
4235
- let o, isBuiltin = !1;
4236
- if (use.loader.startsWith(BUILTIN_LOADER_PREFIX)) {
4237
- let temp = function(identifier, o, options) {
4238
- if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}swc-loader`)) return ((o, composeOptions)=>{
4239
- let options = o ?? {};
4240
- if ('object' == typeof options) {
4241
- var options1;
4242
- if (options.jsc ??= {}, options.jsc.experimental ??= {}, options.jsc.experimental.disableAllLints ??= !0, options.env?.targets === void 0 && options.jsc?.target === void 0) {
4243
- if (composeOptions.compiler.target?.targets) options.env ??= {}, options.env.targets ??= function(targets) {
4244
- let REMAP = {
4245
- and_chr: 'chrome',
4246
- and_ff: 'firefox',
4247
- ie_mob: 'ie',
4248
- ios_saf: 'ios',
4249
- op_mob: 'opera',
4250
- and_qq: null,
4251
- and_uc: null,
4252
- baidu: null,
4253
- bb: null,
4254
- kaios: null,
4255
- op_mini: null
4256
- }, result = {};
4257
- for (let [k, version] of Object.entries(targets)){
4258
- let remap = REMAP[k];
4259
- null !== remap && (result[remap || k] = version);
4260
- }
4261
- return result;
4262
- }(composeOptions.compiler.target.targets);
4263
- else if (composeOptions.compiler.target?.esVersion) {
4264
- let { esVersion } = composeOptions.compiler.target;
4265
- options.jsc.target ??= esVersion >= 2015 ? `es${esVersion}` : 'es5';
4266
- }
4267
- }
4268
- options.collectTypeScriptInfo && (options.collectTypeScriptInfo = {
4269
- typeExports: (options1 = options.collectTypeScriptInfo).typeExports,
4270
- exportedEnum: !0 === options1.exportedEnum ? 'all' : !1 === options1.exportedEnum || void 0 === options1.exportedEnum ? 'none' : 'const-only'
4271
- }), options.transformImport && (options.transformImport = resolvePluginImport(options.transformImport));
4272
- let { rspackExperiments } = options;
4273
- rspackExperiments && (rspackExperiments.import || rspackExperiments.pluginImport) && (rspackExperiments.import = resolvePluginImport(rspackExperiments.import || rspackExperiments.pluginImport));
4274
- }
4275
- return options;
4276
- })(o, options);
4277
- if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}lightningcss-loader`)) {
4278
- let options1;
4279
- return 'object' == typeof (options1 = o ?? {}) && ('string' == typeof options1.targets ? options1.targets = [
4280
- options1.targets
4281
- ] : 'object' != typeof options1.targets || Array.isArray(options1.targets) ? void 0 === options1.targets && options.compiler.target?.targets && (options1.targets = defaultTargetsFromRspackTargets(options.compiler.target.targets)) : options1.targets = encodeTargets(options1.targets), options1.include && 'object' == typeof options1.include && (options1.include = toFeatures(options1.include)), options1.exclude && 'object' == typeof options1.exclude && (options1.exclude = toFeatures(options1.exclude))), options1;
4282
- }
4283
- return o;
4284
- }(use.loader, use.options, options1);
4285
- o = isNil(temp) ? void 0 : 'string' == typeof temp ? temp : JSON.stringify(temp, null, 2), isBuiltin = !0;
4126
+ else endPos = buffered + mem.write(data, buffered, encoding);
4127
+ if (endPos < chunkSize) this.buffered = endPos;
4128
+ else {
4129
+ let l = endPos & ~(this.chunkSize - 1);
4130
+ exports.update(l);
4131
+ let newBuffered = endPos - l;
4132
+ this.buffered = newBuffered, newBuffered > 0 && mem.copyWithin(0, l, endPos);
4286
4133
  }
4287
- return {
4288
- loader: function(use, path, compiler, isBuiltin) {
4289
- let obj = parsePathQueryFragment(use.loader), ident = use.ident;
4290
- null === use.options || void 0 === use.options || ('string' == typeof use.options ? obj.query = `?${use.options}` : use.ident ? obj.query = `??${ident = use.ident}` : 'object' == typeof use.options && use.options.ident ? obj.query = `??${ident = use.options.ident}` : 'object' == typeof use.options ? obj.query = `??${ident = path}` : obj.query = `?${JSON.stringify(use.options)}`);
4291
- let parallelism = use.parallel;
4292
- if (parallelism && (!use.options || 'object' != typeof use.options)) throw Error(`\`Rule.use.parallel\` requires \`Rule.use.options\` to be an object.\nHowever the received value is \`${use.options}\` under option path \`${path}\`\nInternally, parallelism is provided by passing \`Rule.use.ident\` to the loader as an identifier to ident the parallelism option\nYou can either replace the \`Rule.use.loader\` with \`Rule.use.options = {}\` or remove \`Rule.use.parallel\`.`);
4293
- return use.options && 'object' == typeof use.options && (ident || (ident = '[[missing ident]]'), compiler.__internal__ruleSet.references.set(ident, use.options), compiler.__internal__ruleSet.references.set(`${ident}$$parallelism`, parallelism), isBuiltin && compiler.__internal__ruleSet.builtinReferences.set(ident, use.options)), obj.path + obj.query + obj.fragment;
4294
- }(use, `${path1}[${index}]`, options1.compiler, isBuiltin),
4295
- options: o
4296
- };
4297
- }) : [];
4298
- }
4299
- function isUseSourceMap(devtool) {
4300
- return !!devtool && devtool.includes('source-map') && (devtool.includes('module') || !devtool.includes('cheap'));
4301
- }
4302
- function getRawAlias(alias = {}) {
4303
- return !('object' != typeof alias || null === alias || Array.isArray(alias)) && Object.entries(alias).map(([key, value])=>({
4304
- path: key,
4305
- redirect: Array.isArray(value) ? value : [
4306
- value
4307
- ]
4308
- }));
4309
- }
4310
- function getRawResolve(resolve) {
4311
- var byDependency;
4312
- return {
4313
- ...resolve,
4314
- alias: getRawAlias(resolve.alias),
4315
- fallback: getRawAlias(resolve.fallback),
4316
- extensionAlias: function(alias = {}) {
4317
- if ('object' == typeof alias && null !== alias) return Object.fromEntries(Object.entries(alias).map(([key, value])=>Array.isArray(value) ? [
4318
- key,
4319
- value
4320
- ] : [
4321
- key,
4322
- [
4323
- value
4324
- ]
4325
- ]));
4326
- }(resolve.extensionAlias),
4327
- tsconfig: function(tsConfig) {
4328
- if ('string' == typeof tsConfig) throw Error('should resolve string tsConfig in normalization');
4329
- if (void 0 === tsConfig) return tsConfig;
4330
- let { configFile, references } = tsConfig;
4331
- return {
4332
- configFile,
4333
- referencesType: 'auto' === references ? 'auto' : references ? 'manual' : 'disabled',
4334
- references: 'auto' === references ? void 0 : references
4335
- };
4336
- }(resolve.tsConfig),
4337
- byDependency: void 0 === (byDependency = resolve.byDependency) ? byDependency : Object.fromEntries(Object.entries(byDependency).map(([k, v])=>[
4338
- k,
4339
- getRawResolve(v)
4340
- ]))
4341
- };
4342
- }
4343
- function tryMatch(payload, condition) {
4344
- if ('string' == typeof condition) return payload.startsWith(condition);
4345
- if (condition instanceof RegExp) return condition.test(payload);
4346
- if ('function' == typeof condition) return condition(payload);
4347
- if (Array.isArray(condition)) return condition.some((c)=>tryMatch(payload, c));
4348
- if (condition && 'object' == typeof condition) {
4349
- if (condition.and) return condition.and.every((c)=>tryMatch(payload, c));
4350
- if (condition.or) return condition.or.some((c)=>tryMatch(payload, c));
4351
- if (condition.not) return !tryMatch(payload, condition.not);
4352
4134
  }
4353
- return !1;
4354
- }
4355
- let getRawModuleRule = (rule, path, options, upperType)=>{
4356
- let funcUse, normalizedUse = rule.loader ? [
4357
- {
4358
- loader: rule.loader,
4359
- options: rule.options
4360
- }
4361
- ] : rule.use;
4362
- 'function' == typeof normalizedUse && (funcUse = (rawContext)=>createRawModuleRuleUses(normalizedUse({
4363
- ...rawContext,
4364
- compiler: options.compiler
4365
- }) ?? [], `${path}.use`, options));
4366
- let rawModuleRule = {
4367
- test: rule.test ? getRawRuleSetCondition(rule.test) : void 0,
4368
- include: rule.include ? getRawRuleSetCondition(rule.include) : void 0,
4369
- exclude: rule.exclude ? getRawRuleSetCondition(rule.exclude) : void 0,
4370
- issuer: rule.issuer ? getRawRuleSetCondition(rule.issuer) : void 0,
4371
- issuerLayer: rule.issuerLayer ? getRawRuleSetCondition(rule.issuerLayer) : void 0,
4372
- dependency: rule.dependency ? getRawRuleSetCondition(rule.dependency) : void 0,
4373
- phase: rule.phase ? getRawRuleSetCondition(rule.phase) : void 0,
4374
- descriptionData: rule.descriptionData ? Object.fromEntries(Object.entries(rule.descriptionData).map(([k, v])=>[
4375
- k,
4376
- getRawRuleSetCondition(v)
4377
- ])) : void 0,
4378
- with: rule.with ? Object.fromEntries(Object.entries(rule.with).map(([k, v])=>[
4379
- k,
4380
- getRawRuleSetCondition(v)
4381
- ])) : void 0,
4382
- resource: rule.resource ? getRawRuleSetCondition(rule.resource) : void 0,
4383
- resourceQuery: rule.resourceQuery ? getRawRuleSetCondition(rule.resourceQuery) : void 0,
4384
- resourceFragment: rule.resourceFragment ? getRawRuleSetCondition(rule.resourceFragment) : void 0,
4385
- scheme: rule.scheme ? getRawRuleSetCondition(rule.scheme) : void 0,
4386
- mimetype: rule.mimetype ? getRawRuleSetCondition(rule.mimetype) : void 0,
4387
- sideEffects: rule.sideEffects,
4388
- use: 'function' == typeof normalizedUse ? funcUse : createRawModuleRuleUses(normalizedUse ?? [], `${path}.use`, options),
4389
- type: rule.type,
4390
- layer: rule.layer,
4391
- parser: rule.parser ? getRawParserOptions(rule.parser, rule.type ?? upperType) : void 0,
4392
- generator: rule.generator ? getRawGeneratorOptions(rule.generator, rule.type ?? upperType) : void 0,
4393
- resolve: rule.resolve ? getRawResolve(rule.resolve) : void 0,
4394
- oneOf: rule.oneOf ? rule.oneOf.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.oneOf[${index}]`, options, rule.type ?? upperType)) : void 0,
4395
- rules: rule.rules ? rule.rules.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.rules[${index}]`, options, rule.type ?? upperType)) : void 0,
4396
- enforce: rule.enforce,
4397
- extractSourceMap: rule.extractSourceMap
4398
- };
4399
- return ('function' == typeof rule.test || 'function' == typeof rule.resource || 'function' == typeof rule.resourceQuery || 'function' == typeof rule.resourceFragment) && (delete rawModuleRule.test, delete rawModuleRule.resource, delete rawModuleRule.resourceQuery, delete rawModuleRule.resourceFragment, rawModuleRule.rspackResource = getRawRuleSetCondition((resourceQueryFragment)=>{
4400
- let { path, query, fragment } = parseResource(resourceQueryFragment);
4401
- return (!rule.test || !!tryMatch(path, rule.test)) && (!rule.resource || !!tryMatch(path, rule.resource)) && (!rule.resourceQuery || !!tryMatch(query, rule.resourceQuery)) && (!rule.resourceFragment || !!tryMatch(fragment, rule.resourceFragment));
4402
- })), rawModuleRule;
4403
- };
4404
- function getRawRuleSetCondition(condition) {
4405
- if ('string' == typeof condition) return {
4406
- type: binding_namespaceObject.RawRuleSetConditionType.string,
4407
- string: condition
4408
- };
4409
- if (condition instanceof RegExp) return {
4410
- type: binding_namespaceObject.RawRuleSetConditionType.regexp,
4411
- regexp: condition
4412
- };
4413
- if ('function' == typeof condition) return {
4414
- type: binding_namespaceObject.RawRuleSetConditionType.func,
4415
- func: condition
4416
- };
4417
- if (Array.isArray(condition)) return {
4418
- type: binding_namespaceObject.RawRuleSetConditionType.array,
4419
- array: condition.map((i)=>getRawRuleSetCondition(i))
4420
- };
4421
- if ('object' == typeof condition && null !== condition) {
4422
- var logical;
4423
- return {
4424
- type: binding_namespaceObject.RawRuleSetConditionType.logical,
4425
- logical: [
4426
- {
4427
- and: (logical = condition).and ? logical.and.map((i)=>getRawRuleSetCondition(i)) : void 0,
4428
- or: logical.or ? logical.or.map((i)=>getRawRuleSetCondition(i)) : void 0,
4429
- not: logical.not ? getRawRuleSetCondition(logical.not) : void 0
4430
- }
4431
- ]
4432
- };
4135
+ _updateWithBuffer(data) {
4136
+ let { exports, buffered, mem } = this, length = data.length;
4137
+ if (buffered + length < this.chunkSize) data.copy(mem, buffered, 0, length), this.buffered += length;
4138
+ else {
4139
+ let l = buffered + length & ~(this.chunkSize - 1);
4140
+ if (l > 65536) {
4141
+ let i = 65536 - buffered;
4142
+ data.copy(mem, buffered, 0, i), exports.update(65536);
4143
+ let stop = l - buffered - 65536;
4144
+ for(; i < stop;)data.copy(mem, 0, i, i + 65536), exports.update(65536), i += 65536;
4145
+ data.copy(mem, 0, i, l - buffered), exports.update(l - buffered - i);
4146
+ } else data.copy(mem, buffered, 0, l - buffered), exports.update(l);
4147
+ let newBuffered = length + buffered - l;
4148
+ this.buffered = newBuffered, newBuffered > 0 && data.copy(mem, 0, length - newBuffered, length);
4149
+ }
4150
+ }
4151
+ digest(type) {
4152
+ let { exports, buffered, mem, digestSize } = this;
4153
+ exports.final(buffered), this.instancesPool.push(this);
4154
+ let hex = mem.toString('latin1', 0, digestSize);
4155
+ return 'hex' === type ? hex : 'binary' !== type && type ? Buffer.from(hex, 'hex').toString(type) : Buffer.from(hex, 'hex');
4433
4156
  }
4434
- throw Error('unreachable: condition should be one of string, RegExp, Array, Object');
4435
4157
  }
4436
- function getRawParserOptions(parser, type) {
4437
- var parser1, parser2, parser3;
4438
- if ('asset' === type) {
4439
- return {
4440
- type: 'asset',
4441
- asset: {
4442
- dataUrlCondition: (parser1 = parser).dataUrlCondition ? function(dataUrlCondition) {
4443
- if ('object' == typeof dataUrlCondition && null !== dataUrlCondition) return {
4444
- type: 'options',
4445
- options: {
4446
- maxSize: dataUrlCondition.maxSize
4447
- }
4448
- };
4449
- throw Error(`unreachable: AssetParserDataUrl type should be one of "options", but got ${dataUrlCondition}`);
4450
- }(parser1.dataUrlCondition) : void 0
4451
- }
4452
- };
4158
+ let wasm_hash = (wasmModule, instancesPool, chunkSize, digestSize)=>{
4159
+ if (instancesPool.length > 0) {
4160
+ let old = instancesPool.pop();
4161
+ return old.reset(), old;
4453
4162
  }
4454
- if ("javascript" === type) return {
4455
- type: "javascript",
4456
- javascript: getRawJavascriptParserOptions(parser)
4457
- };
4458
- if ("javascript/auto" === type) return {
4459
- type: "javascript/auto",
4460
- javascript: getRawJavascriptParserOptions(parser)
4461
- };
4462
- if ("javascript/dynamic" === type) return {
4463
- type: "javascript/dynamic",
4464
- javascript: getRawJavascriptParserOptions(parser)
4465
- };
4466
- if ("javascript/esm" === type) return {
4467
- type: "javascript/esm",
4468
- javascript: getRawJavascriptParserOptions(parser)
4469
- };
4470
- if ('css' === type) {
4471
- return {
4472
- type: 'css',
4473
- css: {
4474
- namedExports: (parser2 = parser).namedExports,
4475
- url: parser2.url,
4476
- import: parser2.import,
4477
- resolveImport: parser2.resolveImport
4478
- }
4479
- };
4163
+ return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
4164
+ }, createHash_require = createRequire(import.meta.url), digestCaches = {};
4165
+ class BulkUpdateDecorator extends Hash {
4166
+ hash;
4167
+ hashFactory;
4168
+ hashKey;
4169
+ buffer;
4170
+ constructor(hashOrFactory, hashKey){
4171
+ super(), this.hashKey = hashKey, 'function' == typeof hashOrFactory ? (this.hashFactory = hashOrFactory, this.hash = void 0) : (this.hashFactory = void 0, this.hash = hashOrFactory), this.buffer = '';
4480
4172
  }
4481
- if ('css/auto' === type) return {
4482
- type: 'css/auto',
4483
- cssAuto: getRawCssAutoOrModuleParserOptions(parser)
4484
- };
4485
- if ('css/global' === type) return {
4486
- type: 'css/global',
4487
- cssGlobal: getRawCssModuleParserOptions(parser)
4488
- };
4489
- if ('css/module' === type) return {
4490
- type: 'css/module',
4491
- cssModule: getRawCssAutoOrModuleParserOptions(parser)
4492
- };
4493
- if ('json' === type) {
4494
- return {
4495
- type: 'json',
4496
- json: {
4497
- exportsDepth: (parser3 = parser).exportsDepth,
4498
- parse: 'function' == typeof parser3.parse ? (str)=>JSON.stringify(parser3.parse(str)) : void 0
4499
- }
4500
- };
4173
+ update(data, inputEncoding) {
4174
+ return void 0 !== inputEncoding || 'string' != typeof data || data.length > 2000 ? (void 0 === this.hash && (this.hash = this.hashFactory()), this.buffer.length > 0 && (this.hash.update(Buffer.from(this.buffer)), this.buffer = ''), Buffer.isBuffer(data) ? this.hash.update(data) : this.hash.update(data, inputEncoding)) : (this.buffer += data, this.buffer.length > 2000 && (void 0 === this.hash && (this.hash = this.hashFactory()), this.hash.update(Buffer.from(this.buffer)), this.buffer = '')), this;
4175
+ }
4176
+ digest(encoding) {
4177
+ let digestCache, buffer = this.buffer;
4178
+ if (void 0 === this.hash) {
4179
+ let cacheKey = `${this.hashKey}-${encoding}`;
4180
+ void 0 === (digestCache = digestCaches[cacheKey]) && (digestCache = digestCaches[cacheKey] = new Map());
4181
+ let cacheEntry = digestCache.get(buffer);
4182
+ if (void 0 !== cacheEntry) return encoding ? cacheEntry : Buffer.from(cacheEntry, 'hex');
4183
+ this.hash = this.hashFactory();
4184
+ }
4185
+ buffer.length > 0 && this.hash.update(Buffer.from(buffer));
4186
+ let result = encoding ? this.hash.digest(encoding) : this.hash.digest();
4187
+ return void 0 !== digestCache && 'string' == typeof result && digestCache.set(buffer, result), result;
4501
4188
  }
4502
- throw Error(`unreachable: unknown module type: ${type}`);
4503
- }
4504
- function getRawJavascriptParserOptions(parser) {
4505
- return {
4506
- dynamicImportMode: parser.dynamicImportMode,
4507
- dynamicImportPreload: parser.dynamicImportPreload?.toString(),
4508
- dynamicImportPrefetch: parser.dynamicImportPrefetch?.toString(),
4509
- dynamicImportFetchPriority: parser.dynamicImportFetchPriority,
4510
- importMeta: 'boolean' == typeof parser.importMeta ? String(parser.importMeta) : parser.importMeta,
4511
- url: parser.url?.toString(),
4512
- exprContextCritical: parser.exprContextCritical,
4513
- unknownContextCritical: parser.unknownContextCritical,
4514
- wrappedContextCritical: parser.wrappedContextCritical,
4515
- strictThisContextOnImports: parser.strictThisContextOnImports,
4516
- wrappedContextRegExp: parser.wrappedContextRegExp,
4517
- exportsPresence: !1 === parser.exportsPresence ? 'false' : parser.exportsPresence,
4518
- importExportsPresence: !1 === parser.importExportsPresence ? 'false' : parser.importExportsPresence,
4519
- reexportExportsPresence: !1 === parser.reexportExportsPresence ? 'false' : parser.reexportExportsPresence,
4520
- worker: 'boolean' == typeof parser.worker ? parser.worker ? [
4521
- '...'
4522
- ] : [] : parser.worker,
4523
- overrideStrict: parser.overrideStrict,
4524
- requireAsExpression: parser.requireAsExpression,
4525
- requireAlias: parser.requireAlias,
4526
- requireDynamic: parser.requireDynamic,
4527
- requireResolve: parser.requireResolve,
4528
- commonjs: parser.commonjs,
4529
- importDynamic: parser.importDynamic,
4530
- commonjsMagicComments: parser.commonjsMagicComments,
4531
- typeReexportsPresence: parser.typeReexportsPresence,
4532
- jsx: parser.jsx,
4533
- deferImport: parser.deferImport,
4534
- sourceImport: parser.sourceImport,
4535
- importMetaResolve: parser.importMetaResolve,
4536
- pureFunctions: parser.pureFunctions
4537
- };
4538
- }
4539
- function getRawCssModuleParserOptions(parser) {
4540
- return {
4541
- namedExports: parser.namedExports,
4542
- url: parser.url,
4543
- import: parser.import,
4544
- resolveImport: parser.resolveImport,
4545
- animation: parser.animation,
4546
- container: parser.container,
4547
- customIdents: parser.customIdents,
4548
- dashedIdents: parser.dashedIdents,
4549
- function: parser.function,
4550
- grid: parser.grid
4551
- };
4552
- }
4553
- function getRawCssAutoOrModuleParserOptions(parser) {
4554
- return {
4555
- ...getRawCssModuleParserOptions(parser),
4556
- pure: parser.pure
4557
- };
4558
4189
  }
4559
- function getRawGeneratorOptions(generator, type) {
4560
- var options, options1;
4561
- if ('asset' === type) {
4562
- return {
4563
- type: 'asset',
4564
- asset: generator ? {
4565
- ...getRawAssetInlineGeneratorOptions(options = generator),
4566
- ...getRawAssetResourceGeneratorOptions(options)
4567
- } : void 0
4568
- };
4190
+ class WasmHashAdapter extends Hash {
4191
+ wasmHash;
4192
+ constructor(wasmHash){
4193
+ super(), this.wasmHash = wasmHash;
4569
4194
  }
4570
- if ('asset/inline' === type) return {
4571
- type: 'asset/inline',
4572
- assetInline: generator ? getRawAssetInlineGeneratorOptions(generator) : void 0
4573
- };
4574
- if ('asset/resource' === type) return {
4575
- type: 'asset/resource',
4576
- assetResource: generator ? getRawAssetResourceGeneratorOptions(generator) : void 0
4577
- };
4578
- if ('css' === type) {
4579
- return {
4580
- type: 'css',
4581
- css: {
4582
- exportsOnly: (options1 = generator).exportsOnly,
4583
- esModule: options1.esModule
4584
- }
4585
- };
4195
+ update(data, inputEncoding) {
4196
+ return Buffer.isBuffer(data) ? this.wasmHash.update(data) : this.wasmHash.update(data, inputEncoding), this;
4197
+ }
4198
+ digest(encoding) {
4199
+ return encoding ? this.wasmHash.digest(encoding) : this.wasmHash.digest();
4200
+ }
4201
+ }
4202
+ let createHash_createHash = (algorithm)=>{
4203
+ if ('function' == typeof algorithm) return new BulkUpdateDecorator(()=>new algorithm());
4204
+ switch(algorithm){
4205
+ case 'xxhash64':
4206
+ return new WasmHashAdapter((()=>{
4207
+ if (!createXxhash64) {
4208
+ let xxhash64 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL', 'base64'));
4209
+ createXxhash64 = wasm_hash.bind(null, xxhash64, [], 32, 16);
4210
+ }
4211
+ return createXxhash64();
4212
+ })());
4213
+ case 'md4':
4214
+ return new WasmHashAdapter((()=>{
4215
+ if (!createMd4) {
4216
+ let md4 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=', 'base64'));
4217
+ createMd4 = wasm_hash.bind(null, md4, [], 64, 32);
4218
+ }
4219
+ return createMd4();
4220
+ })());
4221
+ case 'native-md4':
4222
+ return new BulkUpdateDecorator(()=>{
4223
+ let { createHash } = createHash_require('node:crypto');
4224
+ return createHash('md4');
4225
+ }, 'md4');
4226
+ default:
4227
+ return new BulkUpdateDecorator(()=>{
4228
+ let { createHash } = createHash_require('node:crypto');
4229
+ return createHash(algorithm);
4230
+ }, algorithm);
4231
+ }
4232
+ }, ModuleError_createMessage = (err, type, from)=>{
4233
+ let message = `Module ${type}${from ? ` (from ${from}):\n` : ': '}`;
4234
+ return err && 'object' == typeof err && err.message ? message += err.message : err && (message += err), message;
4235
+ }, getErrorDetails = (err)=>{
4236
+ var stack, name, message, stack1, name1, message1;
4237
+ let details, nextLine;
4238
+ return err && 'object' == typeof err && err.stack ? (stack = err.stack, name = err.name, message = err.message, cutOffLoaderExecution(stack), stack1 = stack, name1 = name, message1 = message, details = -1 === (nextLine = stack1.indexOf('\n')) ? stack1 === message1 ? '' : stack1 : stack1.slice(0, nextLine) === `${name1}: ${message1}` ? stack1.slice(nextLine + 1) : stack1) : void 0;
4239
+ };
4240
+ class ModuleError extends lib_WebpackError {
4241
+ error;
4242
+ constructor(err, { from } = {}){
4243
+ super(ModuleError_createMessage(err, 'Error', from)), this.name = 'ModuleError', this.error = err, this.details = getErrorDetails(err);
4586
4244
  }
4587
- if ('css/auto' === type) return {
4588
- type: 'css/auto',
4589
- cssAuto: getRawCssAutoOrModuleGeneratorOptions(generator)
4590
- };
4591
- if ('css/global' === type) return {
4592
- type: 'css/global',
4593
- cssGlobal: getRawCssAutoOrModuleGeneratorOptions(generator)
4594
- };
4595
- if ('css/module' === type) return {
4596
- type: 'css/module',
4597
- cssModule: getRawCssAutoOrModuleGeneratorOptions(generator)
4598
- };
4599
- if ('json' === type) return {
4600
- type: 'json',
4601
- json: {
4602
- JSONParse: generator.JSONParse
4603
- }
4604
- };
4605
- if (![
4606
- 'asset/source',
4607
- 'asset/bytes',
4608
- "javascript",
4609
- "javascript/auto",
4610
- "javascript/dynamic",
4611
- "javascript/esm"
4612
- ].includes(type)) throw Error(`unreachable: unknown module type: ${type}`);
4613
4245
  }
4614
- function getRawAssetInlineGeneratorOptions(options) {
4615
- return {
4616
- dataUrl: options.dataUrl ? function(dataUrl) {
4617
- if ('object' == typeof dataUrl && null !== dataUrl) return {
4618
- encoding: !1 === dataUrl.encoding ? 'false' : dataUrl.encoding,
4619
- mimetype: dataUrl.mimetype
4620
- };
4621
- if ('function' == typeof dataUrl && null !== dataUrl) return (source, context)=>dataUrl(source, context);
4622
- throw Error(`unreachable: AssetGeneratorDataUrl type should be one of "options", "function", but got ${dataUrl}`);
4623
- }(options.dataUrl) : void 0,
4624
- binary: options.binary
4625
- };
4246
+ class ModuleWarning extends lib_WebpackError {
4247
+ error;
4248
+ constructor(err, { from } = {}){
4249
+ super(ModuleError_createMessage(err, 'Warning', from)), this.name = 'ModuleWarning', this.error = err, this.details = getErrorDetails(err);
4250
+ }
4626
4251
  }
4627
- function getRawAssetResourceGeneratorOptions(options) {
4628
- return {
4629
- emit: options.emit,
4630
- filename: options.filename,
4631
- outputPath: options.outputPath,
4632
- publicPath: options.publicPath,
4633
- importMode: options.importMode,
4634
- binary: options.binary
4252
+ let service_require = createRequire(import.meta.url), ensureLoaderWorkerPool = async (workerOptions)=>service_pool || (service_pool = import("../compiled/tinypool/dist/index.js").then(({ Tinypool })=>{
4253
+ let availableThreads = Math.max(service_require('node:os').cpus().length - 1, 1), maxWorkers = workerOptions?.maxWorkers ? Math.max(workerOptions.maxWorkers, 1) : void 0, maxWorkersFromEnv = parseInt(process.env.RSPACK_LOADER_WORKER_THREADS || '', 10);
4254
+ return new Tinypool({
4255
+ filename: node_path.resolve(import.meta.dirname, 'worker.js'),
4256
+ useAtomics: !1,
4257
+ maxThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
4258
+ minThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
4259
+ concurrentTasksPerWorker: 1
4260
+ });
4261
+ }));
4262
+ function serializeError(error) {
4263
+ if (error instanceof Error || error && 'object' == typeof error && 'message' in error) return {
4264
+ ...error,
4265
+ name: error.name,
4266
+ stack: error.stack,
4267
+ message: error.message
4635
4268
  };
4636
- }
4637
- function getRawCssAutoOrModuleGeneratorOptions(options) {
4638
- return {
4639
- localIdentName: options.localIdentName,
4640
- localIdentHashDigest: options.localIdentHashDigest,
4641
- localIdentHashDigestLength: options.localIdentHashDigestLength,
4642
- localIdentHashFunction: options.localIdentHashFunction,
4643
- localIdentHashSalt: options.localIdentHashSalt,
4644
- exportsConvention: options.exportsConvention,
4645
- exportsOnly: options.exportsOnly,
4646
- esModule: options.esModule
4269
+ if ('string' == typeof error) return {
4270
+ name: 'Error',
4271
+ message: error
4647
4272
  };
4273
+ throw Error('Failed to serialize error, only string, Error instances and objects with a message property are supported');
4648
4274
  }
4649
- class ExternalsPlugin extends RspackBuiltinPlugin {
4650
- type;
4651
- externals;
4652
- placeInInitial;
4653
- fallbackType;
4654
- name = binding_namespaceObject.BuiltinPluginName.ExternalsPlugin;
4655
- #resolveRequestCache = new Map();
4656
- constructor(type, externals, placeInInitial, fallbackType){
4657
- super(), this.type = type, this.externals = externals, this.placeInInitial = placeInInitial, this.fallbackType = fallbackType;
4658
- }
4659
- raw() {
4660
- let type = this.type, externals = this.externals, raw = {
4661
- type,
4662
- fallbackType: this.fallbackType,
4663
- externals: (Array.isArray(externals) ? externals : [
4664
- externals
4665
- ]).filter(Boolean).map((item)=>this.#getRawExternalItem(item)),
4666
- placeInInitial: this.placeInInitial ?? !1
4667
- };
4668
- return createBuiltinPlugin(this.name, raw);
4669
- }
4670
- #processResolveResult = (text)=>{
4671
- if (!text) return;
4672
- let resolveRequest = this.#resolveRequestCache.get(text);
4673
- return resolveRequest || (resolveRequest = JSON.parse(text), this.#resolveRequestCache.set(text, resolveRequest)), Object.assign({}, resolveRequest);
4674
- };
4675
- #processRequest(req) {
4676
- return `${req.path.replace(/#/g, '\u200b#')}${req.query.replace(/#/g, '\u200b#')}${req.fragment}`;
4677
- }
4678
- #getRawExternalItem = (item)=>{
4679
- if ('string' == typeof item || item instanceof RegExp) return item;
4680
- if ('function' == typeof item) {
4681
- let processResolveResult = this.#processResolveResult;
4682
- return async (ctx)=>new Promise((resolve, reject)=>{
4683
- let data = ctx.data(), promise = item({
4684
- request: data.request,
4685
- dependencyType: data.dependencyType,
4686
- context: data.context,
4687
- contextInfo: {
4688
- issuer: data.contextInfo.issuer,
4689
- issuerLayer: data.contextInfo.issuerLayer ?? null
4690
- },
4691
- getResolve: (options)=>{
4692
- let rawResolve = options ? getRawResolve(options) : void 0, resolve = ctx.getResolve(rawResolve);
4693
- return (context, request, callback)=>{
4694
- if (!callback) return new Promise((promiseResolve, promiseReject)=>{
4695
- resolve(context, request, (error, text)=>{
4696
- if (error) promiseReject(error);
4697
- else {
4698
- let req = processResolveResult(text);
4699
- promiseResolve(req ? this.#processRequest(req) : void 0);
4700
- }
4701
- });
4702
- });
4703
- resolve(context, request, (error, text)=>{
4704
- if (error) callback(error);
4705
- else {
4706
- let req = processResolveResult(text);
4707
- callback(null, !!req && this.#processRequest(req), req);
4708
- }
4709
- });
4710
- };
4711
- }
4712
- }, (err, result, type)=>{
4713
- err && reject(err), resolve({
4714
- result: getRawExternalItemValueFormFnResult(result),
4715
- externalType: type
4716
- });
4275
+ let service_run = async (loaderName, task, options, workerOptions)=>ensureLoaderWorkerPool(workerOptions).then(async (pool)=>{
4276
+ let { MessageChannel } = await import("node:worker_threads"), { port1: mainPort, port2: workerPort } = new MessageChannel(), { port1: mainSyncPort, port2: workerSyncPort } = new MessageChannel();
4277
+ return new Promise((resolve, reject)=>{
4278
+ let handleError = (error)=>{
4279
+ mainPort.close(), mainSyncPort.close(), reject(error);
4280
+ }, pendingRequests = new Map();
4281
+ mainPort.on('message', (message)=>{
4282
+ 'done' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
4283
+ mainPort.close(), mainSyncPort.close(), resolve(message.data);
4284
+ }) : 'done-error' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
4285
+ mainPort.close(), mainSyncPort.close(), reject(message.error);
4286
+ }) : 'request' === message.type && pendingRequests.set(message.id, Promise.resolve().then(()=>options.handleIncomingRequest(message.requestType, ...message.data)).then((result)=>(mainPort.postMessage({
4287
+ type: 'response',
4288
+ id: message.id,
4289
+ data: result
4290
+ }), result)).catch((error)=>{
4291
+ mainPort.postMessage({
4292
+ type: 'response-error',
4293
+ id: message.id,
4294
+ error: serializeError(error)
4717
4295
  });
4718
- promise?.then ? promise.then((result)=>resolve({
4719
- result: getRawExternalItemValueFormFnResult(result),
4720
- externalType: void 0
4721
- }), (e)=>reject(e)) : 1 === item.length && resolve({
4722
- result: getRawExternalItemValueFormFnResult(promise),
4723
- externalType: void 0
4296
+ }));
4297
+ }), mainPort.on('messageerror', handleError), mainSyncPort.on('message', async (message)=>{
4298
+ let result, { sharedBuffer } = message, sharedBufferView = new Int32Array(sharedBuffer);
4299
+ try {
4300
+ if ("WaitForPendingRequest" === message.requestType) {
4301
+ let pendingRequestId = message.data[0], isArray = Array.isArray(pendingRequestId), ids = isArray ? pendingRequestId : [
4302
+ pendingRequestId
4303
+ ];
4304
+ result = await Promise.all(ids.map((id)=>pendingRequests.get(id))), isArray || (result = result[0]);
4305
+ } else throw Error(`Unknown request type: ${message.requestType}`);
4306
+ mainSyncPort.postMessage({
4307
+ type: 'response',
4308
+ id: message.id,
4309
+ data: result
4310
+ });
4311
+ } catch (e) {
4312
+ mainSyncPort.postMessage({
4313
+ type: 'response-error',
4314
+ id: message.id,
4315
+ error: serializeError(e)
4724
4316
  });
4317
+ }
4318
+ Atomics.add(sharedBufferView, 0, 1), Atomics.notify(sharedBufferView, 0, 1 / 0);
4319
+ }), mainSyncPort.on('messageerror', handleError);
4320
+ let errors = [];
4321
+ for (let key of Object.keys(task))try {
4322
+ structuredClone(task[key]);
4323
+ } catch (e) {
4324
+ errors.push({
4325
+ key,
4326
+ type: typeof task[key],
4327
+ reason: e.message
4725
4328
  });
4726
- }
4727
- if ('object' == typeof item) return Object.fromEntries(Object.entries(item).map(([k, v])=>[
4728
- k,
4729
- getRawExternalItemValue(v)
4730
- ]));
4731
- throw TypeError(`Unexpected type of external item: ${typeof item}`);
4732
- };
4733
- }
4734
- function getRawExternalItemValueFormFnResult(result) {
4735
- return void 0 === result ? result : getRawExternalItemValue(result);
4736
- }
4737
- function getRawExternalItemValue(value) {
4738
- return value && 'object' == typeof value && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).map(([k, v])=>[
4739
- k,
4740
- Array.isArray(v) ? v : [
4741
- v
4742
- ]
4743
- ])) : value;
4744
- }
4745
- let FetchCompileAsyncWasmPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FetchCompileAsyncWasmPlugin, ()=>{}, 'thisCompilation'), FileUriPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FileUriPlugin, ()=>{}, 'compilation'), FlagDependencyExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FlagDependencyExportsPlugin, ()=>{}, 'compilation');
4746
- class FlagDependencyUsagePlugin extends RspackBuiltinPlugin {
4747
- global;
4748
- name = binding_namespaceObject.BuiltinPluginName.FlagDependencyUsagePlugin;
4749
- affectedHooks = 'compilation';
4750
- constructor(global){
4751
- super(), this.global = global;
4329
+ }
4330
+ if (errors.length > 0) {
4331
+ let errorMsg = errors.map((err)=>`option "${err.key}" (type: ${err.type}) is not cloneable: ${err.reason}`).join('\n');
4332
+ throw Error(`The options for ${loaderName} are not cloneable, which is not supported by parallelLoader. Consider disabling parallel for this loader or removing the non-cloneable properties from the options:\n${errorMsg}`);
4333
+ }
4334
+ pool.run({
4335
+ ...task,
4336
+ workerData: {
4337
+ workerPort,
4338
+ workerSyncPort
4339
+ }
4340
+ }, {
4341
+ ...options,
4342
+ transferList: [
4343
+ ...options?.transferList || [],
4344
+ workerPort,
4345
+ workerSyncPort
4346
+ ]
4347
+ }).catch(handleError);
4348
+ });
4349
+ }), LoaderLoadingError = class extends Error {
4350
+ constructor(message){
4351
+ super(message), this.name = 'LoaderRunnerError', Error.captureStackTrace(this, this.constructor);
4752
4352
  }
4753
- raw() {
4754
- return createBuiltinPlugin(this.name, this.global);
4353
+ }, loadLoader_require = createRequire(import.meta.url), loadLoader_moduleCache = new Map(), modulePromiseCache = new Map(), loaderUrlCache = new Map();
4354
+ function loadLoader(loader, compiler, callback) {
4355
+ let cacheKey = `${loader.type ?? 'commonjs'}\0${loader.path}`, cachedModule = loadLoader_moduleCache.get(cacheKey);
4356
+ if (void 0 !== cachedModule) return handleResult(loader, cachedModule, callback);
4357
+ if ('module' === loader.type) try {
4358
+ let modulePromise = modulePromiseCache.get(cacheKey);
4359
+ if (void 0 === modulePromise) {
4360
+ void 0 === loadLoader_url && (loadLoader_url = loadLoader_require('node:url'));
4361
+ let loaderUrl = loaderUrlCache.get(loader.path);
4362
+ void 0 === loaderUrl && (loaderUrl = loadLoader_url.pathToFileURL(loader.path).toString(), loaderUrlCache.set(loader.path, loaderUrl)), modulePromise = import(loaderUrl).then((module)=>(loadLoader_moduleCache.set(cacheKey, module), modulePromiseCache.delete(cacheKey), module), (err)=>{
4363
+ throw modulePromiseCache.delete(cacheKey), err;
4364
+ }), modulePromiseCache.set(cacheKey, modulePromise);
4365
+ }
4366
+ modulePromise.then((module)=>{
4367
+ handleResult(loader, module, callback);
4368
+ }, callback);
4369
+ return;
4370
+ } catch (e) {
4371
+ callback(e);
4372
+ }
4373
+ else {
4374
+ let module;
4375
+ try {
4376
+ module = loadLoader_require(loader.path);
4377
+ } catch (e) {
4378
+ if (e instanceof Error && 'EMFILE' === e.code) return void setImmediate(loadLoader.bind(null, loader, compiler, callback));
4379
+ return callback(e);
4380
+ }
4381
+ return handleResult(loader, module, callback);
4755
4382
  }
4756
4383
  }
4757
- let HashedModuleIdsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HashedModuleIdsPlugin, (options)=>({
4758
- ...options
4759
- }), 'compilation');
4760
- class HotModuleReplacementPlugin extends RspackBuiltinPlugin {
4761
- name = binding_namespaceObject.BuiltinPluginName.HotModuleReplacementPlugin;
4762
- raw(compiler) {
4763
- return void 0 === compiler.options.output.strictModuleErrorHandling && (compiler.options.output.strictModuleErrorHandling = !0), createBuiltinPlugin(this.name, void 0);
4764
- }
4384
+ function handleResult(loader, module, callback) {
4385
+ return 'function' != typeof module && 'object' != typeof module ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (export function or es6 module)`)) : (loader.normal = 'function' == typeof module ? module : module.default, loader.pitch = module.pitch, loader.raw = module.raw, loader.pitch || (loader.noPitch = !0), 'function' != typeof loader.normal && 'function' != typeof loader.pitch) ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (must have normal or pitch function)`)) : void callback();
4765
4386
  }
4766
- let HttpExternalsRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HttpExternalsRspackPlugin, (webAsync)=>({
4767
- webAsync
4768
- })), HttpUriPlugin_require = createRequire(import.meta.url), getHttp = memoize(()=>HttpUriPlugin_require('node:http')), getHttps = memoize(()=>HttpUriPlugin_require('node:https')), defaultHttpClientForNode = async (url, headers)=>{
4769
- let { res, body } = await function(url, options) {
4770
- let send = 'https:' === new URL(url).protocol ? getHttps() : getHttp(), { createBrotliDecompress, createGunzip, createInflate } = HttpUriPlugin_require('node:zlib');
4771
- return new Promise((resolve, reject)=>{
4772
- send.get(url, options, (res)=>{
4773
- let contentEncoding = res.headers['content-encoding'], stream = res;
4774
- 'gzip' === contentEncoding ? stream = stream.pipe(createGunzip()) : 'br' === contentEncoding ? stream = stream.pipe(createBrotliDecompress()) : 'deflate' === contentEncoding && (stream = stream.pipe(createInflate()));
4775
- let chunks = [];
4776
- stream.on('data', (chunk)=>{
4777
- chunks.push(chunk);
4778
- }), stream.on('end', ()=>{
4779
- let bodyBuffer = Buffer.concat(chunks);
4780
- res.complete ? resolve({
4781
- res,
4782
- body: bodyBuffer
4783
- }) : reject(Error(`${url} request was terminated early`));
4784
- });
4785
- }).on('error', reject);
4786
- });
4787
- }(url, {
4788
- headers
4789
- }), responseHeaders = {};
4790
- for (let [key, value] of Object.entries(res.headers))Array.isArray(value) ? responseHeaders[key] = value.join(', ') : responseHeaders[key] = value;
4791
- return {
4792
- status: res.statusCode,
4793
- headers: responseHeaders,
4794
- body: Buffer.from(body)
4387
+ let decoder = new TextDecoder(), utils_loadLoader = promisify(loadLoader), utils_runSyncOrAsync = promisify(function(fn, context, args, callback) {
4388
+ let isSync = !0, isDone = !1, isError = !1, reportedError = !1;
4389
+ context.async = function() {
4390
+ if (isDone) {
4391
+ if (reportedError) return;
4392
+ throw Error('async(): The callback was already called.');
4393
+ }
4394
+ return isSync = !1, innerCallback;
4795
4395
  };
4796
- };
4797
- class HttpUriPlugin extends RspackBuiltinPlugin {
4396
+ let innerCallback = (err, ...args)=>{
4397
+ if (isDone) {
4398
+ if (reportedError) return;
4399
+ throw Error('callback(): The callback was already called.');
4400
+ }
4401
+ isDone = !0, isSync = !1;
4402
+ try {
4403
+ callback(err, args);
4404
+ } catch (e) {
4405
+ throw isError = !0, e;
4406
+ }
4407
+ };
4408
+ context.callback = innerCallback;
4409
+ try {
4410
+ let result = fn.apply(context, args);
4411
+ if (isSync) {
4412
+ if (isDone = !0, void 0 === result) return void callback(null, []);
4413
+ if (result && 'object' == typeof result && 'function' == typeof result.then) return void result.then((r)=>{
4414
+ callback(null, [
4415
+ r
4416
+ ]);
4417
+ }, callback);
4418
+ callback(null, [
4419
+ result
4420
+ ]);
4421
+ return;
4422
+ }
4423
+ } catch (e) {
4424
+ if ('hideStack' in e && e.hideStack && (e.hideStack = 'true'), isError) throw e;
4425
+ if (isDone) return void (e instanceof Error ? console.error(e.stack) : console.error(e));
4426
+ isDone = !0, reportedError = !0, callback(e, []);
4427
+ }
4428
+ }), LOADER_PROCESS_NAME = 'Loader Analysis';
4429
+ class LoaderObject {
4430
+ request;
4431
+ path;
4432
+ query;
4433
+ fragment;
4798
4434
  options;
4799
- name = binding_namespaceObject.BuiltinPluginName.HttpUriPlugin;
4800
- affectedHooks = 'compilation';
4801
- constructor(options){
4802
- super(), this.options = options;
4435
+ ident;
4436
+ normal;
4437
+ pitch;
4438
+ raw;
4439
+ type;
4440
+ parallel;
4441
+ loaderItem;
4442
+ constructor(loaderItem, compiler){
4443
+ var path, query, fragment;
4444
+ let splittedRequest = parseResourceWithoutFragment(loaderItem.loader);
4445
+ if (this.path = splittedRequest.path, this.fragment = '', this.options = splittedRequest.query ? splittedRequest.query.slice(1) : void 0, this.ident = null, this.normal = null, this.pitch = null, this.raw = null, 'string' == typeof this.options && '?' === this.options[0]) {
4446
+ let ident = this.options.slice(1);
4447
+ if ('[[missing ident]]' === ident) throw Error("No ident is provided by referenced loader. When using a function for Rule.use in config you need to provide an 'ident' property for referenced loader options.");
4448
+ if (this.options = compiler.__internal__ruleSet.references.get(ident), void 0 === this.options) throw Error('Invalid ident is provided by referenced loader');
4449
+ this.ident = ident;
4450
+ }
4451
+ this.type = '' === loaderItem.type ? void 0 : loaderItem.type, null === this.options || void 0 === this.options ? this.query = '' : 'string' == typeof this.options ? this.query = `?${this.options}` : this.ident ? this.query = `??${this.ident}` : this.options.ident ? this.query = `??${this.options.ident}` : this.query = `?${JSON.stringify(this.options)}`, this.request = (path = this.path, query = this.query, fragment = this.fragment, path.replace(/#/g, '\u200b#') + query.replace(/#/g, '\u200b#') + fragment), this.parallel = !!this.ident && compiler.__internal__ruleSet.references.get(`${this.ident}$$parallelism`), this.loaderItem = loaderItem, this.loaderItem.data = this.loaderItem.data ?? {};
4803
4452
  }
4804
- raw(compiler) {
4805
- let options = this.options, lockfileLocation = options.lockfileLocation ?? node_path.join(compiler.context, compiler.name ? `${compiler.name}.rspack.lock` : 'rspack.lock'), cacheLocation = !1 === options.cacheLocation ? void 0 : options.cacheLocation ?? `${lockfileLocation}.data`, raw = {
4806
- allowedUris: options.allowedUris,
4807
- lockfileLocation,
4808
- cacheLocation,
4809
- upgrade: options.upgrade ?? !1,
4810
- httpClient: options.httpClient ?? defaultHttpClientForNode
4811
- };
4812
- return createBuiltinPlugin(this.name, raw);
4453
+ get pitchExecuted() {
4454
+ return this.loaderItem.pitchExecuted;
4455
+ }
4456
+ set pitchExecuted(value) {
4457
+ if (!value) throw Error('pitchExecuted should be true');
4458
+ this.loaderItem.pitchExecuted = !0;
4459
+ }
4460
+ get normalExecuted() {
4461
+ return this.loaderItem.normalExecuted;
4462
+ }
4463
+ set normalExecuted(value) {
4464
+ if (!value) throw Error('normalExecuted should be true');
4465
+ this.loaderItem.normalExecuted = !0;
4466
+ }
4467
+ set noPitch(value) {
4468
+ if (!value) throw Error('noPitch should be true');
4469
+ this.loaderItem.noPitch = !0;
4470
+ }
4471
+ shouldYield() {
4472
+ return this.request.startsWith(BUILTIN_LOADER_PREFIX);
4473
+ }
4474
+ static __from_binding(loaderItem, compiler) {
4475
+ return new this(loaderItem, compiler);
4476
+ }
4477
+ static __to_binding(loader) {
4478
+ return loader.loaderItem;
4813
4479
  }
4814
4480
  }
4815
- let compilationOptionsMap = new WeakMap(), hooks_compilationHooksMap = new WeakMap(), plugin_require = createRequire(import.meta.url), HTML_PLUGIN_UID = 0, HtmlRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HtmlRspackPlugin, function(c = {}) {
4816
- let templateFn, templateParameters, filenames, uid = HTML_PLUGIN_UID++, meta = {};
4817
- for(let key in c.meta){
4818
- let value = c.meta[key];
4819
- 'string' == typeof value ? meta[key] = {
4820
- name: key,
4821
- content: value
4822
- } : meta[key] = {
4823
- name: key,
4824
- ...value
4825
- };
4481
+ class JsSourceMap {
4482
+ static __from_binding(map) {
4483
+ return isNil(map) ? void 0 : ((input)=>{
4484
+ let s;
4485
+ if (Buffer.isBuffer(input)) s = input.toString('utf8');
4486
+ else if (input && 'object' == typeof input) return input;
4487
+ else if ('string' == typeof input) s = input;
4488
+ else throw Error('Buffer or string or object expected');
4489
+ return JSON.parse(s);
4490
+ })(map);
4826
4491
  }
4827
- let scriptLoading = c.scriptLoading ?? 'defer', configInject = c.inject ?? !0, base = 'string' == typeof c.base ? {
4828
- href: c.base
4829
- } : c.base, chunksSortMode = c.chunksSortMode ?? 'auto', compilation = null;
4830
- function generateRenderData(data) {
4831
- let json = JSON.parse(data);
4832
- 'function' != typeof c.templateParameters && (json.compilation = compilation);
4833
- let renderTag = function() {
4834
- var tag;
4835
- let attributes;
4836
- return tag = this, attributes = Object.keys(tag.attributes || {}).filter((attributeName)=>'' === tag.attributes[attributeName] || tag.attributes[attributeName]).map((attributeName)=>'true' === tag.attributes[attributeName] ? attributeName : `${attributeName}="${tag.attributes[attributeName]}"`), `<${[
4837
- tag.tagName
4838
- ].concat(attributes).join(' ')}${tag.voidTag && !tag.innerHTML ? '/' : ''}>${tag.innerHTML || ''}${tag.voidTag && !tag.innerHTML ? '' : `</${tag.tagName}>`}`;
4839
- }, renderTagList = function() {
4840
- return this.join('');
4841
- };
4842
- if (Array.isArray(json.htmlRspackPlugin?.tags?.headTags)) {
4843
- for (let tag of json.htmlRspackPlugin.tags.headTags)tag.toString = renderTag;
4844
- json.htmlRspackPlugin.tags.headTags.toString = renderTagList;
4492
+ static __to_binding(map) {
4493
+ return serializeObject(map);
4494
+ }
4495
+ }
4496
+ function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
4497
+ return loaderContext.loaders?.length && index < loaderContext.loaders.length && index >= 0 && loaderContext.loaders[index] ? loaderContext.loaders[index] : null;
4498
+ }
4499
+ async function runLoaders(compiler, context) {
4500
+ var buildInfo;
4501
+ let loaderState = context.loaderState, pitch = loaderState === binding_namespaceObject.JsLoaderState.Pitching, { resource } = context, traceData = JavaScriptTracer.isEnabled() ? {
4502
+ uuid: JavaScriptTracer.uuid(),
4503
+ args: {
4504
+ is_pitch: pitch,
4505
+ resource: resource
4506
+ }
4507
+ } : void 0;
4508
+ traceData && JavaScriptTracer.startAsync({
4509
+ name: 'run_js_loaders',
4510
+ processName: LOADER_PROCESS_NAME,
4511
+ uuid: traceData.uuid,
4512
+ ph: 'b',
4513
+ args: traceData.args
4514
+ });
4515
+ let splittedResource = resource && parseResource(resource), resourcePath = splittedResource ? splittedResource.path : void 0, resourceQuery = splittedResource ? splittedResource.query : void 0, resourceFragment = splittedResource ? splittedResource.fragment : void 0, contextDirectory = resourcePath ? function(path) {
4516
+ if ('/' === path) return '/';
4517
+ let i = path.lastIndexOf('/'), j = path.lastIndexOf('\\'), i2 = path.indexOf('/'), j2 = path.indexOf('\\'), idx = i > j ? i : j, idx2 = i > j ? i2 : j2;
4518
+ return idx < 0 ? path : idx === idx2 ? path.slice(0, idx + 1) : path.slice(0, idx);
4519
+ }(resourcePath) : null, fileDependencies = context.fileDependencies, contextDependencies = context.contextDependencies, missingDependencies = context.missingDependencies, buildDependencies = context.buildDependencies, loaderContext = {};
4520
+ loaderContext.loaders = context.loaderItems.map((item)=>LoaderObject.__from_binding(item, compiler)), loaderContext.hot = context.hot, loaderContext.context = contextDirectory, loaderContext.resourcePath = resourcePath, loaderContext.resourceQuery = resourceQuery, loaderContext.resourceFragment = resourceFragment, loaderContext.dependency = loaderContext.addDependency = function(file) {
4521
+ fileDependencies.push(file);
4522
+ }, loaderContext.addContextDependency = function(context) {
4523
+ contextDependencies.push(context);
4524
+ }, loaderContext.addMissingDependency = function(context) {
4525
+ missingDependencies.push(context);
4526
+ }, loaderContext.addBuildDependency = function(file) {
4527
+ buildDependencies.push(file);
4528
+ }, loaderContext.getDependencies = function() {
4529
+ return fileDependencies.slice();
4530
+ }, loaderContext.getContextDependencies = function() {
4531
+ return contextDependencies.slice();
4532
+ }, loaderContext.getMissingDependencies = function() {
4533
+ return missingDependencies.slice();
4534
+ }, loaderContext.clearDependencies = function() {
4535
+ fileDependencies.length = 0, contextDependencies.length = 0, missingDependencies.length = 0, context.cacheable = !0;
4536
+ }, loaderContext.importModule = function(request, userOptions, callback) {
4537
+ traceData && JavaScriptTracer.startAsync({
4538
+ name: 'importModule',
4539
+ processName: LOADER_PROCESS_NAME,
4540
+ uuid: traceData.uuid,
4541
+ args: traceData.args
4542
+ });
4543
+ let options = userOptions || {};
4544
+ function finalCallback(onError, onDone) {
4545
+ return function(err, res) {
4546
+ if (err) traceData && JavaScriptTracer.endAsync({
4547
+ name: 'importModule',
4548
+ processName: LOADER_PROCESS_NAME,
4549
+ uuid: traceData.uuid,
4550
+ args: traceData.args
4551
+ }), onError(err);
4552
+ else {
4553
+ for (let dep of res.buildDependencies)loaderContext.addBuildDependency(dep);
4554
+ for (let dep of res.contextDependencies)loaderContext.addContextDependency(dep);
4555
+ for (let dep of res.missingDependencies)loaderContext.addMissingDependency(dep);
4556
+ for (let dep of res.fileDependencies)loaderContext.addDependency(dep);
4557
+ !1 === res.cacheable && loaderContext.cacheable(!1), traceData && JavaScriptTracer.endAsync({
4558
+ name: 'importModule',
4559
+ processName: LOADER_PROCESS_NAME,
4560
+ uuid: traceData.uuid,
4561
+ args: traceData.args
4562
+ }), res.error ? onError(compiler.__internal__takeModuleExecutionResult(res.id) ?? Error(res.error)) : onDone(compiler.__internal__takeModuleExecutionResult(res.id));
4563
+ }
4564
+ };
4565
+ }
4566
+ return callback ? compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback((err)=>callback(err), (res)=>callback(void 0, res))) : new Promise((resolve, reject)=>{
4567
+ compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback(reject, resolve));
4568
+ });
4569
+ }, Object.defineProperty(loaderContext, 'resource', {
4570
+ enumerable: !0,
4571
+ get: ()=>{
4572
+ if (void 0 !== loaderContext.resourcePath) return loaderContext.resourcePath.replace(/#/g, '\u200b#') + loaderContext.resourceQuery.replace(/#/g, '\u200b#') + loaderContext.resourceFragment;
4573
+ },
4574
+ set: (value)=>{
4575
+ let splittedResource = value && parseResource(value);
4576
+ loaderContext.resourcePath = splittedResource ? splittedResource.path : void 0, loaderContext.resourceQuery = splittedResource ? splittedResource.query : void 0, loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : void 0;
4577
+ }
4578
+ }), Object.defineProperty(loaderContext, 'request', {
4579
+ enumerable: !0,
4580
+ get: ()=>loaderContext.loaders.map((o)=>o.request).concat(loaderContext.resource || '').join('!')
4581
+ }), Object.defineProperty(loaderContext, 'remainingRequest', {
4582
+ enumerable: !0,
4583
+ get: ()=>loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource ? '' : loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
4584
+ }), Object.defineProperty(loaderContext, 'currentRequest', {
4585
+ enumerable: !0,
4586
+ get: ()=>loaderContext.loaders.slice(loaderContext.loaderIndex).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
4587
+ }), Object.defineProperty(loaderContext, 'previousRequest', {
4588
+ enumerable: !0,
4589
+ get: ()=>loaderContext.loaders.slice(0, loaderContext.loaderIndex).map((o)=>o.request).join('!')
4590
+ }), Object.defineProperty(loaderContext, 'query', {
4591
+ enumerable: !0,
4592
+ get: ()=>{
4593
+ let entry = loaderContext.loaders[loaderContext.loaderIndex];
4594
+ return entry.options && 'object' == typeof entry.options ? entry.options : entry.query;
4845
4595
  }
4846
- if (Array.isArray(json.htmlRspackPlugin?.tags?.bodyTags)) {
4847
- for (let tag of json.htmlRspackPlugin.tags.bodyTags)tag.toString = renderTag;
4848
- json.htmlRspackPlugin.tags.bodyTags.toString = renderTagList;
4596
+ }), loaderContext.version = 2, loaderContext.sourceMap = compiler.options.devtool ? isUseSourceMap(compiler.options.devtool) : context._module.useSourceMap ?? !1, loaderContext.mode = compiler.options.mode, Object.assign(loaderContext, compiler.options.loader);
4597
+ let getResolveContext = ()=>({
4598
+ fileDependencies: {
4599
+ add: (d)=>{
4600
+ loaderContext.addDependency(d);
4601
+ }
4602
+ },
4603
+ contextDependencies: {
4604
+ add: (d)=>{
4605
+ loaderContext.addContextDependency(d);
4606
+ }
4607
+ },
4608
+ missingDependencies: {
4609
+ add: (d)=>{
4610
+ loaderContext.addMissingDependency(d);
4611
+ }
4612
+ }
4613
+ }), getResolver = memoize(()=>compiler._lastCompilation.resolverFactory.get('normal'));
4614
+ loaderContext.resolve = function(context, request, callback) {
4615
+ getResolver().resolve({}, context, request, getResolveContext(), callback);
4616
+ }, loaderContext.getResolve = function(options) {
4617
+ let resolver = getResolver(), child = options ? resolver.withOptions(options) : resolver;
4618
+ return (context, request, callback)=>callback ? void child.resolve({}, context, request, getResolveContext(), callback) : new Promise((resolve, reject)=>{
4619
+ child.resolve({}, context, request, getResolveContext(), (err, result)=>{
4620
+ err ? reject(err) : resolve(result);
4621
+ });
4622
+ });
4623
+ }, loaderContext.getLogger = function(name) {
4624
+ return compiler._lastCompilation.getLogger([
4625
+ name,
4626
+ resource
4627
+ ].filter(Boolean).join('|'));
4628
+ }, loaderContext.rootContext = compiler.context, loaderContext.emitError = function(e) {
4629
+ e instanceof Error || (e = new NonErrorEmittedError(e));
4630
+ let error = new ModuleError(e, {
4631
+ from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
4632
+ });
4633
+ error.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
4634
+ error,
4635
+ severity: binding_namespaceObject.JsRspackSeverity.Error
4636
+ });
4637
+ }, loaderContext.emitWarning = function(e) {
4638
+ e instanceof Error || (e = new NonErrorEmittedError(e));
4639
+ let warning = new ModuleWarning(e, {
4640
+ from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
4641
+ });
4642
+ warning.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
4643
+ error: warning,
4644
+ severity: binding_namespaceObject.JsRspackSeverity.Warn
4645
+ });
4646
+ }, loaderContext.emitFile = function(name, content, sourceMap, assetInfo) {
4647
+ let source;
4648
+ if (sourceMap) {
4649
+ var devtool;
4650
+ 'string' == typeof sourceMap && (loaderContext.sourceMap || compiler.options.devtool && (devtool = compiler.options.devtool) && devtool.includes('source-map') && !isUseSourceMap(devtool)) && (source = new index_js_namespaceObject.OriginalSource(content, makePathsRelative(contextDirectory, sourceMap, compiler))), loaderContext.sourceMap && (source = new index_js_namespaceObject.SourceMapSource(content, name, makePathsRelative(contextDirectory, sourceMap, compiler)));
4651
+ } else source = new index_js_namespaceObject.RawSource(content);
4652
+ loaderContext._module.emitFile(name, source, assetInfo);
4653
+ }, loaderContext.fs = compiler.inputFileSystem, loaderContext.experiments = {
4654
+ emitDiagnostic: (diagnostic)=>{
4655
+ let d = Object.assign({}, diagnostic, {
4656
+ message: 'warning' === diagnostic.severity ? `ModuleWarning: ${diagnostic.message}` : `ModuleError: ${diagnostic.message}`,
4657
+ moduleIdentifier: context._module.identifier()
4658
+ });
4659
+ compiler._lastCompilation.__internal__pushDiagnostic((0, binding_namespaceObject.formatDiagnostic)(d));
4849
4660
  }
4850
- return json;
4851
- }
4852
- this.hooks.compilation.tap('HtmlRspackPlugin', (compilationInstance)=>{
4853
- var compilation1;
4854
- let optionsMap;
4855
- compilation1 = compilation = compilationInstance, (optionsMap = compilationOptionsMap.get(compilation1) || {})[uid] = c, compilationOptionsMap.set(compilation1, optionsMap);
4856
- }), this.hooks.done.tap('HtmlRspackPlugin', (stats)=>{
4857
- var compilation, compilation1;
4858
- let optionsMap;
4859
- compilation = stats.compilation, hooks_compilationHooksMap.delete(compilation), compilation1 = stats.compilation, optionsMap = compilationOptionsMap.get(compilation1) || {}, delete optionsMap[uid], 0 === Object.keys(optionsMap).length ? compilationOptionsMap.delete(compilation1) : compilationOptionsMap.set(compilation1, optionsMap);
4860
- });
4861
- let templateContent = c.templateContent;
4862
- if ('function' == typeof templateContent) templateFn = async (data)=>{
4863
- try {
4864
- let renderer = c.templateContent;
4865
- if (!1 === c.templateParameters) return await renderer({});
4866
- return await renderer(generateRenderData(data));
4661
+ };
4662
+ let getAbsolutify = memoize(()=>absolutify.bindCache(compiler.root)), getAbsolutifyInContext = memoize(()=>absolutify.bindContextCache(contextDirectory, compiler.root)), getContextify = memoize(()=>contextify.bindCache(compiler.root)), getContextifyInContext = memoize(()=>contextify.bindContextCache(contextDirectory, compiler.root));
4663
+ loaderContext.utils = {
4664
+ absolutify: (context, request)=>context === contextDirectory ? getAbsolutifyInContext()(request) : getAbsolutify()(context, request),
4665
+ contextify: (context, request)=>context === contextDirectory ? getContextifyInContext()(request) : getContextify()(context, request),
4666
+ createHash: (type)=>createHash_createHash(type || compiler._lastCompilation.outputOptions.hashFunction)
4667
+ }, loaderContext._compiler = compiler, loaderContext._compilation = compiler._lastCompilation, loaderContext._module = context._module, loaderContext.getOptions = ()=>{
4668
+ let loader = getCurrentLoader(loaderContext), options = loader?.options;
4669
+ if ('string' == typeof options) if (options.startsWith('{') && options.endsWith('}')) try {
4670
+ options = JSON.parse(options);
4867
4671
  } catch (e) {
4868
- let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
4869
- throw error.stack = e.stack, error;
4672
+ throw Error(`JSON parsing failed for loader's string options: ${e.message}`);
4870
4673
  }
4871
- }, templateContent = '';
4872
- else if (c.template) {
4873
- let filename = c.template.split('?')[0];
4874
- [
4875
- '.js',
4876
- '.cjs'
4877
- ].includes(node_path.extname(filename)) && (templateFn = async (data)=>{
4878
- let context = this.options.context || process.cwd(), templateFilePath = node_path.resolve(context, filename);
4879
- if (!node_fs.existsSync(templateFilePath)) throw Error(`HtmlRspackPlugin: could not load file \`${filename}\` from \`${context}\``);
4880
- try {
4881
- let renderer = plugin_require(templateFilePath);
4882
- if (!1 === c.templateParameters) return await renderer({});
4883
- return await renderer(generateRenderData(data));
4884
- } catch (e) {
4885
- let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
4886
- throw error.stack = e.stack, error;
4674
+ else options = node_querystring.parse(options);
4675
+ return null == options && (options = {}), options;
4676
+ };
4677
+ let compilation = compiler._lastCompilation, step = 0;
4678
+ for(; compilation;)if (binding_namespaceObject.NormalModule.getCompilationHooks(compilation).loader.call(loaderContext, loaderContext._module), compilation = compilation.compiler.parentCompilation, ++step > 1000) throw Error('Too many nested child compiler, exceeded max limitation 1000');
4679
+ Object.defineProperty(loaderContext, 'loaderIndex', {
4680
+ enumerable: !0,
4681
+ get: ()=>context.loaderIndex,
4682
+ set: (loaderIndex)=>context.loaderIndex = loaderIndex
4683
+ }), Object.defineProperty(loaderContext, 'cacheable', {
4684
+ enumerable: !0,
4685
+ get: ()=>(cacheable)=>{
4686
+ !1 === cacheable && (context.cacheable = cacheable);
4887
4687
  }
4888
- });
4889
- }
4890
- let rawTemplateParameters = c.templateParameters;
4891
- if (templateParameters = 'function' == typeof rawTemplateParameters ? async (data)=>JSON.stringify(await rawTemplateParameters(JSON.parse(data))) : rawTemplateParameters, 'string' == typeof c.filename) if (filenames = new Set(), c.filename.includes('[name]')) if ('object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename.replace(/\[name\]/g, entryName));
4892
- else throw Error('HtmlRspackPlugin: filename with `[name]` does not support function entry');
4893
- else filenames.add(c.filename);
4894
- else if ('function' == typeof c.filename) if (filenames = new Set(), 'object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename(entryName));
4895
- else throw Error('HtmlRspackPlugin: function filename does not support function entry');
4896
- return {
4897
- filename: filenames ? Array.from(filenames) : void 0,
4898
- template: c.template,
4899
- hash: c.hash,
4900
- title: c.title,
4901
- favicon: c.favicon,
4902
- publicPath: c.publicPath,
4903
- chunks: c.chunks,
4904
- excludeChunks: c.excludeChunks,
4905
- chunksSortMode,
4906
- minify: c.minify,
4907
- meta,
4908
- scriptLoading,
4909
- inject: !0 === configInject ? 'blocking' === scriptLoading ? 'body' : 'head' : !1 === configInject ? 'false' : configInject,
4910
- base,
4911
- templateFn,
4912
- templateContent,
4913
- templateParameters,
4914
- uid
4688
+ }), Object.defineProperty(loaderContext, 'data', {
4689
+ enumerable: !0,
4690
+ get: ()=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data,
4691
+ set: (data)=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data = data
4692
+ }), loaderContext.__internal__setParseMeta = (key, value)=>{
4693
+ context.__internal__parseMeta[key] = value;
4694
+ };
4695
+ let enableParallelism = (currentLoaderObject)=>currentLoaderObject?.parallel, isomorphoicRun = async (fn, args)=>{
4696
+ let loaderName, result, currentLoaderObject = getCurrentLoader(loaderContext), parallelism = enableParallelism(currentLoaderObject);
4697
+ if ((traceData || parallelism) && (loaderName = function(loaderPath, cwd = '') {
4698
+ let res = loaderPath.replace(cwd, '');
4699
+ if (!node_path.isAbsolute(res)) return res;
4700
+ let nms = '/node_modules/', idx = res.lastIndexOf(nms);
4701
+ if (-1 !== idx) {
4702
+ res = res.slice(idx + nms.length);
4703
+ let ln = 'loader', lnIdx = res.lastIndexOf(ln);
4704
+ lnIdx > -1 && (res = res.slice(0, lnIdx + ln.length));
4705
+ }
4706
+ return res;
4707
+ }(currentLoaderObject.request)), traceData && JavaScriptTracer.startAsync({
4708
+ name: loaderName,
4709
+ trackName: loaderName,
4710
+ processName: LOADER_PROCESS_NAME,
4711
+ uuid: traceData.uuid,
4712
+ args: traceData.args
4713
+ }), parallelism) {
4714
+ let normalModule, workerLoaderContext;
4715
+ result = await service_run(loaderName, {
4716
+ loaderContext: (normalModule = loaderContext._module instanceof binding_namespaceObject.NormalModule ? loaderContext._module : void 0, Object.assign(workerLoaderContext = {
4717
+ hot: loaderContext.hot,
4718
+ context: loaderContext.context,
4719
+ resourcePath: loaderContext.resourcePath,
4720
+ resourceQuery: loaderContext.resourceQuery,
4721
+ resourceFragment: loaderContext.resourceFragment,
4722
+ resource: loaderContext.resource,
4723
+ mode: loaderContext.mode,
4724
+ sourceMap: loaderContext.sourceMap,
4725
+ rootContext: loaderContext.rootContext,
4726
+ loaderIndex: loaderContext.loaderIndex,
4727
+ loaders: loaderContext.loaders.map((item)=>{
4728
+ let options = item.options;
4729
+ return (!item.parallel || item.request.startsWith(BUILTIN_LOADER_PREFIX)) && (options = void 0), {
4730
+ ...item,
4731
+ options,
4732
+ pitch: void 0,
4733
+ normal: void 0,
4734
+ normalExecuted: item.normalExecuted,
4735
+ pitchExecuted: item.pitchExecuted
4736
+ };
4737
+ }),
4738
+ __internal__workerInfo: {
4739
+ hashFunction: compiler._lastCompilation.outputOptions.hashFunction
4740
+ },
4741
+ _compiler: {
4742
+ options: {
4743
+ experiments: {
4744
+ css: !0
4745
+ }
4746
+ }
4747
+ },
4748
+ _compilation: {
4749
+ options: {
4750
+ output: {
4751
+ environment: compiler._lastCompilation.outputOptions.environment
4752
+ }
4753
+ },
4754
+ outputOptions: {
4755
+ hashSalt: compiler._lastCompilation.outputOptions.hashSalt,
4756
+ hashFunction: compiler._lastCompilation.outputOptions.hashFunction,
4757
+ hashDigest: compiler._lastCompilation.outputOptions.hashDigest,
4758
+ hashDigestLength: compiler._lastCompilation.outputOptions.hashDigestLength
4759
+ }
4760
+ },
4761
+ _module: {
4762
+ type: loaderContext._module.type,
4763
+ identifier: loaderContext._module.identifier(),
4764
+ matchResource: normalModule?.matchResource,
4765
+ request: normalModule?.request,
4766
+ userRequest: normalModule?.userRequest,
4767
+ rawRequest: normalModule?.rawRequest
4768
+ }
4769
+ }, compiler.options.loader), workerLoaderContext),
4770
+ loaderState,
4771
+ args
4772
+ }, {
4773
+ handleIncomingRequest (requestType, ...args) {
4774
+ switch(requestType){
4775
+ case "AddDependency":
4776
+ loaderContext.addDependency(args[0]);
4777
+ break;
4778
+ case "AddContextDependency":
4779
+ loaderContext.addContextDependency(args[0]);
4780
+ break;
4781
+ case "AddMissingDependency":
4782
+ loaderContext.addMissingDependency(args[0]);
4783
+ break;
4784
+ case "AddBuildDependency":
4785
+ loaderContext.addBuildDependency(args[0]);
4786
+ break;
4787
+ case "GetDependencies":
4788
+ return loaderContext.getDependencies();
4789
+ case "GetContextDependencies":
4790
+ return loaderContext.getContextDependencies();
4791
+ case "GetMissingDependencies":
4792
+ return loaderContext.getMissingDependencies();
4793
+ case "ClearDependencies":
4794
+ loaderContext.clearDependencies();
4795
+ break;
4796
+ case "Resolve":
4797
+ return new Promise((resolve, reject)=>{
4798
+ loaderContext.resolve(args[0], args[1], (err, result)=>{
4799
+ err ? reject(err) : resolve(result);
4800
+ });
4801
+ });
4802
+ case "GetResolve":
4803
+ return new Promise((resolve, reject)=>{
4804
+ loaderContext.getResolve(args[0])(args[1], args[2], (err, result)=>{
4805
+ err ? reject(err) : resolve(result);
4806
+ });
4807
+ });
4808
+ case "GetLogger":
4809
+ {
4810
+ let [type, name, arg] = args;
4811
+ loaderContext.getLogger(name)[type](...arg);
4812
+ break;
4813
+ }
4814
+ case "EmitError":
4815
+ {
4816
+ let workerError = args[0], error = Error(workerError.message);
4817
+ error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitError(error);
4818
+ break;
4819
+ }
4820
+ case "EmitWarning":
4821
+ {
4822
+ let workerError = args[0], error = Error(workerError.message);
4823
+ error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitWarning(error);
4824
+ break;
4825
+ }
4826
+ case "EmitFile":
4827
+ {
4828
+ let [name, content, sourceMap, assetInfo] = args;
4829
+ loaderContext.emitFile(name, content, sourceMap, assetInfo);
4830
+ break;
4831
+ }
4832
+ case "EmitDiagnostic":
4833
+ {
4834
+ let diagnostic = args[0];
4835
+ loaderContext.experiments.emitDiagnostic(diagnostic);
4836
+ break;
4837
+ }
4838
+ case "SetCacheable":
4839
+ {
4840
+ let cacheable = args[0];
4841
+ loaderContext.cacheable(cacheable);
4842
+ break;
4843
+ }
4844
+ case "ImportModule":
4845
+ return loaderContext.importModule(args[0], args[1]);
4846
+ case "UpdateLoaderObjects":
4847
+ {
4848
+ let updates = args[0];
4849
+ loaderContext.loaders = loaderContext.loaders.map((item, index)=>{
4850
+ let update = updates[index];
4851
+ return item.loaderItem.data = update.data, update.pitchExecuted && (item.pitchExecuted = !0), update.normalExecuted && (item.normalExecuted = !0), item;
4852
+ });
4853
+ break;
4854
+ }
4855
+ case "CompilationGetPath":
4856
+ {
4857
+ let filename = args[0], data = args[1];
4858
+ return compiler._lastCompilation.getPath(filename, data);
4859
+ }
4860
+ case "CompilationGetPathWithInfo":
4861
+ {
4862
+ let filename = args[0], data = args[1];
4863
+ return compiler._lastCompilation.getPathWithInfo(filename, data);
4864
+ }
4865
+ case "CompilationGetAssetPath":
4866
+ {
4867
+ let filename = args[0], data = args[1];
4868
+ return compiler._lastCompilation.getAssetPath(filename, data);
4869
+ }
4870
+ case "CompilationGetAssetPathWithInfo":
4871
+ {
4872
+ let filename = args[0], data = args[1];
4873
+ return compiler._lastCompilation.getAssetPathWithInfo(filename, data);
4874
+ }
4875
+ default:
4876
+ throw Error(`Unknown request type: ${requestType}`);
4877
+ }
4878
+ }
4879
+ }, 'object' == typeof currentLoaderObject?.parallel ? currentLoaderObject.parallel : void 0) || [];
4880
+ } else loaderState === binding_namespaceObject.JsLoaderState.Normal && function(args, raw) {
4881
+ if (!raw && args[0] instanceof Uint8Array) {
4882
+ var buf;
4883
+ let isShared, str;
4884
+ args[0] = (isShared = (buf = args[0]).buffer instanceof SharedArrayBuffer || buf.buffer.constructor?.name === 'SharedArrayBuffer', 0xfeff === (str = decoder.decode(isShared ? Buffer.from(buf) : buf)).charCodeAt(0) ? str.slice(1) : str);
4885
+ } else raw && 'string' == typeof args[0] && (args[0] = Buffer.from(args[0], 'utf-8'));
4886
+ raw && args[0] instanceof Uint8Array && !Buffer.isBuffer(args[0]) && (args[0] = Buffer.from(args[0].buffer));
4887
+ }(args, !!currentLoaderObject?.raw), result = await utils_runSyncOrAsync(fn, loaderContext, args) || [];
4888
+ return traceData && JavaScriptTracer.endAsync({
4889
+ name: loaderName,
4890
+ trackName: loaderName,
4891
+ processName: LOADER_PROCESS_NAME,
4892
+ uuid: traceData.uuid,
4893
+ args: traceData.args
4894
+ }), result;
4915
4895
  };
4916
- }), voidTags = [
4917
- 'area',
4918
- 'base',
4919
- 'br',
4920
- 'col',
4921
- 'embed',
4922
- 'hr',
4923
- 'img',
4924
- 'input',
4925
- 'keygen',
4926
- 'link',
4927
- 'meta',
4928
- 'param',
4929
- 'source',
4930
- 'track',
4931
- 'wbr'
4932
- ];
4933
- HtmlRspackPlugin.createHtmlTagObject = (tagName, attributes, innerHTML)=>({
4934
- tagName,
4935
- voidTag: voidTags.includes(tagName),
4936
- attributes: attributes || {},
4937
- innerHTML
4938
- }), HtmlRspackPlugin.getCompilationHooks = (compilation)=>{
4939
- checkCompilation(compilation);
4940
- let hooks = hooks_compilationHooksMap.get(compilation);
4941
- return void 0 === hooks && (hooks = {
4942
- beforeAssetTagGeneration: new AsyncSeriesWaterfallHook([
4943
- 'data'
4944
- ]),
4945
- alterAssetTags: new AsyncSeriesWaterfallHook([
4946
- 'data'
4947
- ]),
4948
- alterAssetTagGroups: new AsyncSeriesWaterfallHook([
4949
- 'data'
4950
- ]),
4951
- afterTemplateExecution: new AsyncSeriesWaterfallHook([
4952
- 'data'
4953
- ]),
4954
- beforeEmit: new AsyncSeriesWaterfallHook([
4955
- 'data'
4956
- ]),
4957
- afterEmit: new AsyncSeriesWaterfallHook([
4958
- 'data'
4959
- ])
4960
- }, hooks_compilationHooksMap.set(compilation, hooks)), hooks;
4961
- }, HtmlRspackPlugin.version = 5;
4962
- let IgnorePlugin = base_create(binding_namespaceObject.BuiltinPluginName.IgnorePlugin, (options)=>options), InferAsyncModulesPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InferAsyncModulesPlugin, ()=>{}, 'compilation'), InlineExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InlineExportsPlugin, ()=>{}, 'compilation'), JavascriptModulesPlugin_compilationHooksMap = new WeakMap();
4963
- class JavascriptModulesPlugin extends RspackBuiltinPlugin {
4964
- name = binding_namespaceObject.BuiltinPluginName.JavascriptModulesPlugin;
4965
- affectedHooks = 'compilation';
4966
- raw() {
4967
- return createBuiltinPlugin(this.name, void 0);
4968
- }
4969
- static getCompilationHooks(compilation) {
4970
- checkCompilation(compilation);
4971
- let hooks = JavascriptModulesPlugin_compilationHooksMap.get(compilation);
4972
- return void 0 === hooks && (hooks = {
4973
- chunkHash: new SyncHook([
4974
- 'chunk',
4975
- 'hash'
4976
- ])
4977
- }, JavascriptModulesPlugin_compilationHooksMap.set(compilation, hooks)), hooks;
4896
+ try {
4897
+ switch(loaderState){
4898
+ case binding_namespaceObject.JsLoaderState.Pitching:
4899
+ for(; loaderContext.loaderIndex < loaderContext.loaders.length;){
4900
+ let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4901
+ if (currentLoaderObject.shouldYield()) break;
4902
+ if (currentLoaderObject.pitchExecuted) {
4903
+ loaderContext.loaderIndex += 1;
4904
+ continue;
4905
+ }
4906
+ await utils_loadLoader(currentLoaderObject, compiler);
4907
+ let fn = currentLoaderObject.pitch;
4908
+ if (parallelism && fn || (currentLoaderObject.pitchExecuted = !0), !fn) continue;
4909
+ let args = await isomorphoicRun(fn, [
4910
+ loaderContext.remainingRequest,
4911
+ loaderContext.previousRequest,
4912
+ currentLoaderObject.loaderItem.data
4913
+ ]);
4914
+ if (args.some((value)=>void 0 !== value)) {
4915
+ let [content, sourceMap, additionalData] = args;
4916
+ context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = serializeObject(sourceMap), context.additionalData = additionalData || void 0;
4917
+ break;
4918
+ }
4919
+ }
4920
+ break;
4921
+ case binding_namespaceObject.JsLoaderState.Normal:
4922
+ {
4923
+ let content = context.content, sourceMap = JsSourceMap.__from_binding(context.sourceMap), additionalData = context.additionalData;
4924
+ for(; loaderContext.loaderIndex >= 0;){
4925
+ let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4926
+ if (currentLoaderObject.shouldYield()) break;
4927
+ if (currentLoaderObject.normalExecuted) {
4928
+ loaderContext.loaderIndex--;
4929
+ continue;
4930
+ }
4931
+ await utils_loadLoader(currentLoaderObject, compiler);
4932
+ let fn = currentLoaderObject.normal;
4933
+ parallelism && fn || (currentLoaderObject.normalExecuted = !0), fn && ([content, sourceMap, additionalData] = await isomorphoicRun(fn, [
4934
+ content,
4935
+ sourceMap,
4936
+ additionalData
4937
+ ]));
4938
+ }
4939
+ context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = JsSourceMap.__to_binding(sourceMap), context.additionalData = additionalData || void 0, context.__internal__utf8Hint = 'string' == typeof content;
4940
+ break;
4941
+ }
4942
+ default:
4943
+ throw Error(`Unexpected loader runner state: ${loaderState}`);
4944
+ }
4945
+ context.loaderItems = loaderContext.loaders.map((item)=>LoaderObject.__to_binding(item));
4946
+ } catch (e) {
4947
+ if ('object' != typeof e || null === e) {
4948
+ let error = Error(`(Emitted value instead of an instance of Error) ${e}`);
4949
+ error.name = 'NonErrorEmittedError', context.__internal__error = error;
4950
+ } else context.__internal__error = e;
4978
4951
  }
4952
+ return traceData && JavaScriptTracer.endAsync({
4953
+ name: 'run_js_loaders',
4954
+ uuid: traceData.uuid,
4955
+ args: traceData.args
4956
+ }), compiler.options?.cache && Object.keys(buildInfo = context._module.buildInfo).some((key)=>!knownBuildInfoFields.has(key)) && buildInfo[binding_default().COMMIT_CUSTOM_FIELDS_SYMBOL](), context;
4979
4957
  }
4980
4958
  let JsLoaderRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.JsLoaderRspackPlugin, (compiler)=>runLoaders.bind(null, compiler), 'thisCompilation'), JsonModulesPlugin = base_create(binding_namespaceObject.BuiltinPluginName.JsonModulesPlugin, ()=>{}, 'compilation'), LibManifestPlugin = base_create(binding_namespaceObject.BuiltinPluginName.LibManifestPlugin, (options)=>{
4981
4959
  let { context, entryOnly, format, name, path, type } = options;
@@ -5166,7 +5144,8 @@ let NodeTargetPlugin = base_create(binding_namespaceObject.BuiltinPluginName.Nod
5166
5144
  return {
5167
5145
  moduleGraphFeatures: c.moduleGraphFeatures ?? !0,
5168
5146
  chunkGraphFeatures: c.chunkGraphFeatures ?? !0,
5169
- sourceMapFeatures: c.sourceMapFeatures
5147
+ sourceMapFeatures: c.sourceMapFeatures,
5148
+ exportUsageGraph: c.exportUsageGraph
5170
5149
  };
5171
5150
  }), RsdoctorPlugin_compilationHooksMap = new WeakMap();
5172
5151
  RsdoctorPluginImpl.getCompilationHooks = (compilation)=>{
@@ -6666,7 +6645,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6666
6645
  (hasTrue || hasFalse) && (result[key] = hasFalse && hasTrue ? null : hasTrue);
6667
6646
  }
6668
6647
  return result;
6669
- })(targets.map((t)=>getTargetProperties(t, context))), applyRspackOptionsDefaults = (options)=>{
6648
+ })(targets.map((t)=>getTargetProperties(t, context))), applyRspackOptionsDefaults = (options, compilerIndex)=>{
6670
6649
  F(options, 'context', ()=>process.cwd()), F(options, 'target', ()=>hasBrowserslistConfig(options.context) ? 'browserslist' : 'web');
6671
6650
  let { mode, target } = options;
6672
6651
  if (isNil(target)) throw Error('target should not be nil after defaults');
@@ -6674,11 +6653,18 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6674
6653
  if ('function' != typeof options.entry) for (let key of Object.keys(options.entry))F(options.entry[key], 'import', ()=>[
6675
6654
  './src'
6676
6655
  ]);
6677
- return F(options, 'devtool', ()=>!!development && 'cheap-module-source-map'), D(options, 'watch', !1), D(options, 'lazyCompilation', !1), D(options, 'bail', !1), F(options, 'cache', ()=>development), applyIncrementalDefaults(options), applyExperimentsDefaults(options.experiments), applyOptimizationDefaults(options.optimization, {
6656
+ return F(options, 'devtool', ()=>!!development && 'cheap-module-source-map'), D(options, 'watch', !1), D(options, 'lazyCompilation', !1), D(options, 'bail', !1), F(options, 'cache', ()=>!!development && {
6657
+ type: 'memory'
6658
+ }), applyCacheDefaults(options.cache, {
6659
+ context: options.context,
6660
+ name: options.name,
6661
+ mode: options.mode,
6662
+ compilerIndex
6663
+ }), applyIncrementalDefaults(options), applyExperimentsDefaults(options.experiments, {
6664
+ production
6665
+ }), applyOptimizationDefaults(options.optimization, {
6678
6666
  production,
6679
6667
  development
6680
- }), applySnapshotDefaults(options.snapshot, {
6681
- production
6682
6668
  }), applyOutputDefaults(options, {
6683
6669
  context: options.context,
6684
6670
  targetProperties,
@@ -6721,11 +6707,23 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6721
6707
  esVersion: targetProperties.esVersion,
6722
6708
  targets: targetProperties.targets
6723
6709
  };
6724
- }, applyExperimentsDefaults = (experiments)=>{
6725
- D(experiments, 'futureDefaults', !1), D(experiments, 'asyncWebAssembly', !0), D(experiments, 'deferImport', !1), D(experiments, 'sourceImport', !1), D(experiments, 'buildHttp', void 0), experiments.buildHttp && 'object' == typeof experiments.buildHttp && D(experiments.buildHttp, 'upgrade', !1), D(experiments, 'useInputFileSystem', !1), D(experiments, 'pureFunctions', !1);
6710
+ }, applyCacheDefaults = (cache, { context, name, mode, compilerIndex })=>{
6711
+ if (!1 !== cache) switch(cache.type){
6712
+ case 'memory':
6713
+ break;
6714
+ case 'persistent':
6715
+ D(cache, 'version', ''), F(cache, 'buildDependencies', ()=>[]), F(cache.snapshot, 'immutablePaths', ()=>[]), F(cache.snapshot, 'unmanagedPaths', ()=>[]), F(cache.snapshot, 'managedPaths', ()=>[
6716
+ /[\\/]node_modules[\\/][^.]/
6717
+ ]), D(cache.storage, 'type', 'filesystem'), D(cache.storage, 'maxAge', 604800), D(cache.storage, 'maxGenerations', 3), F(cache.storage, 'directory', ()=>{
6718
+ let modeName = mode || 'production', compilerName = name ? `${name}-${modeName}` : modeName, cacheName = compilerIndex ? `${compilerName}-${compilerIndex}` : compilerName;
6719
+ return node_path.resolve(context, 'node_modules/.cache/rspack', cacheName);
6720
+ }), D(cache, 'portable', !1), D(cache, 'readonly', !1);
6721
+ }
6722
+ }, applyExperimentsDefaults = (experiments, { production })=>{
6723
+ D(experiments, 'futureDefaults', !1), D(experiments, 'asyncWebAssembly', !0), D(experiments, 'deferImport', !1), D(experiments, 'sourceImport', !1), D(experiments, 'buildHttp', void 0), experiments.buildHttp && 'object' == typeof experiments.buildHttp && D(experiments.buildHttp, 'upgrade', !1), D(experiments, 'useInputFileSystem', !1), D(experiments, 'pureFunctions', production), D(experiments, 'runtimeMode', 'webpack');
6726
6724
  }, applyIncrementalDefaults = (options)=>{
6727
6725
  D(options, 'incremental', {}), 'object' == typeof options.incremental && (D(options.incremental, 'silent', !0), D(options.incremental, 'buildModuleGraph', !0), D(options.incremental, 'finishModules', !0), D(options.incremental, 'optimizeDependencies', !0), D(options.incremental, 'buildChunkGraph', !0), D(options.incremental, 'optimizeChunkModules', !0), D(options.incremental, 'moduleIds', !0), D(options.incremental, 'chunkIds', !0), D(options.incremental, 'modulesHashes', !0), D(options.incremental, 'modulesCodegen', !0), D(options.incremental, 'modulesRuntimeRequirements', !0), D(options.incremental, 'chunksRuntimeRequirements', !0), D(options.incremental, 'chunksHashes', !0), D(options.incremental, 'chunkAsset', !0), D(options.incremental, 'emitAssets', !0));
6728
- }, applySnapshotDefaults = (_snapshot, _env)=>{}, applyCssParserOptionsDefaults = (parserOptions)=>{
6726
+ }, applyCssParserOptionsDefaults = (parserOptions)=>{
6729
6727
  D(parserOptions, 'namedExports', !0), D(parserOptions, 'url', !0), D(parserOptions, 'import', !0);
6730
6728
  }, applyCssModuleGeneratorOptionsDefaults = (generatorOptions, { hashFunction, hashSalt, localIdentName, targetProperties })=>{
6731
6729
  D(generatorOptions, 'exportsOnly', !targetProperties || !1 === targetProperties.document), D(generatorOptions, 'esModule', !0), D(generatorOptions, 'exportsConvention', 'as-is'), D(generatorOptions, 'localIdentName', localIdentName), D(generatorOptions, 'localIdentHashSalt', hashSalt), D(generatorOptions, 'localIdentHashFunction', hashFunction), D(generatorOptions, 'localIdentHashDigest', 'base64url'), D(generatorOptions, 'localIdentHashDigestLength', 6);
@@ -6737,7 +6735,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6737
6735
  assertNotNill(module.parser), assertNotNill(module.generator), F(module.parser, "asset", ()=>({})), assertNotNill(module.parser.asset), F(module.parser.asset, 'dataUrlCondition', ()=>({})), 'object' == typeof module.parser.asset.dataUrlCondition && D(module.parser.asset.dataUrlCondition, 'maxSize', 8096), F(module.parser, "javascript", ()=>({})), assertNotNill(module.parser.javascript), ((parserOptions, { deferImport, sourceImport, outputModule })=>{
6738
6736
  D(parserOptions, 'dynamicImportMode', 'lazy'), D(parserOptions, 'dynamicImportPrefetch', !1), D(parserOptions, 'dynamicImportPreload', !1), D(parserOptions, 'url', !0), D(parserOptions, 'exprContextCritical', !0), D(parserOptions, 'unknownContextCritical', !0), D(parserOptions, 'wrappedContextCritical', !1), D(parserOptions, 'strictThisContextOnImports', !1), D(parserOptions, 'wrappedContextRegExp', /.*/), D(parserOptions, 'exportsPresence', 'error'), D(parserOptions, 'requireAsExpression', !0), D(parserOptions, 'requireAlias', !1), D(parserOptions, 'requireDynamic', !0), D(parserOptions, 'requireResolve', !0), D(parserOptions, 'commonjs', !0), D(parserOptions, 'importDynamic', !0), D(parserOptions, 'worker', [
6739
6737
  '...'
6740
- ]), D(parserOptions, 'importMeta', !outputModule || 'preserve-unknown'), D(parserOptions, 'typeReexportsPresence', 'no-tolerant'), D(parserOptions, 'jsx', !1), D(parserOptions, 'deferImport', deferImport), D(parserOptions, 'sourceImport', sourceImport), D(parserOptions, 'importMetaResolve', !1);
6738
+ ]), D(parserOptions, 'importMeta', !outputModule || 'preserve-unknown'), D(parserOptions, 'typeReexportsPresence', 'no-tolerant'), D(parserOptions, 'jsx', !1), D(parserOptions, 'deferImport', deferImport), D(parserOptions, 'sourceImport', sourceImport), D(parserOptions, 'importMetaResolve', !1), D(parserOptions, 'createRequire', !1);
6741
6739
  })(module.parser.javascript, {
6742
6740
  deferImport,
6743
6741
  sourceImport,
@@ -7033,7 +7031,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
7033
7031
  return output.wasmLoading && enabledWasmLoadingTypes.add(output.wasmLoading), output.workerWasmLoading && enabledWasmLoadingTypes.add(output.workerWasmLoading), forEachEntry((desc)=>{
7034
7032
  desc.wasmLoading && enabledWasmLoadingTypes.add(desc.wasmLoading);
7035
7033
  }), Array.from(enabledWasmLoadingTypes);
7036
- }), D(output, 'bundlerInfo', {}), 'object' == typeof output.bundlerInfo && (D(output.bundlerInfo, 'version', "2.0.8"), D(output.bundlerInfo, 'bundler', 'rspack'), D(output.bundlerInfo, 'force', !1));
7034
+ }), D(output, 'bundlerInfo', {}), 'object' == typeof output.bundlerInfo && (D(output.bundlerInfo, 'version', "2.1.0-rc.0"), D(output.bundlerInfo, 'bundler', 'rspack'), D(output.bundlerInfo, 'force', !1));
7037
7035
  }, applyExternalsPresetsDefaults = (externalsPresets, { targetProperties, buildHttp, outputModule })=>{
7038
7036
  let isUniversal = (key)=>!!(outputModule && targetProperties && null === targetProperties[key]);
7039
7037
  D(externalsPresets, 'web', !buildHttp && targetProperties && (targetProperties.web || isUniversal('node'))), D(externalsPresets, 'node', targetProperties && (targetProperties.node || isUniversal('node'))), D(externalsPresets, 'electron', targetProperties && targetProperties.electron || isUniversal('electron')), D(externalsPresets, 'electronMain', targetProperties && !!targetProperties.electron && (targetProperties.electronMain || isUniversal('electronMain'))), D(externalsPresets, 'electronPreload', targetProperties && !!targetProperties.electron && (targetProperties.electronPreload || isUniversal('electronPreload'))), D(externalsPresets, 'electronRenderer', targetProperties && !!targetProperties.electron && (targetProperties.electronRenderer || isUniversal('electronRenderer'))), D(externalsPresets, 'nwjs', targetProperties && (targetProperties.nwjs || isUniversal('nwjs')));
@@ -7047,7 +7045,16 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
7047
7045
  }
7048
7046
  }), D(loader, 'environment', environment);
7049
7047
  }, applyNodeDefaults = (node, { outputModule, targetProperties })=>{
7050
- !1 !== node && (F(node, 'global', ()=>(!targetProperties || !targetProperties.global) && 'warn'), F(node, '__dirname', ()=>targetProperties && targetProperties.node ? outputModule ? 'node-module' : 'eval-only' : 'warn-mock'), F(node, '__filename', ()=>targetProperties && targetProperties.node ? outputModule ? 'node-module' : 'eval-only' : 'warn-mock'));
7048
+ if (!1 === node) return;
7049
+ F(node, 'global', ()=>(!targetProperties || !targetProperties.global) && 'warn');
7050
+ let handlerForNames = ()=>{
7051
+ if (targetProperties) {
7052
+ if (targetProperties.node) return outputModule ? 'node-module' : 'eval-only';
7053
+ if (outputModule && null === targetProperties.node && null === targetProperties.web) return 'eval-only';
7054
+ }
7055
+ return 'warn-mock';
7056
+ };
7057
+ F(node, '__dirname', handlerForNames), F(node, '__filename', handlerForNames);
7051
7058
  }, applyPerformanceDefaults = (performance, { production })=>{
7052
7059
  !1 !== performance && (D(performance, 'maxAssetSize', 307200), D(performance, 'maxEntrypointSize', 512000), F(performance, 'hints', ()=>!!production && 'warning'));
7053
7060
  }, applyOptimizationDefaults = (optimization, { production, development })=>{
@@ -7325,34 +7332,49 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
7325
7332
  ...node
7326
7333
  }),
7327
7334
  loader: cloneObject(config.loader),
7328
- snapshot: nestedConfig(config.snapshot, (_snapshot)=>({})),
7329
7335
  cache: optionalNestedConfig(config.cache, (cache)=>{
7330
- if ('boolean' == typeof cache || 'memory' === cache.type) return cache;
7331
- let snapshot = cache.snapshot || {};
7332
- return {
7333
- type: 'persistent',
7334
- buildDependencies: nestedArray(cache.buildDependencies, (deps)=>deps.map((d)=>node_path.resolve(config.context || process.cwd(), d))),
7335
- version: cache.version || '',
7336
- snapshot: {
7337
- immutablePaths: nestedArray(snapshot.immutablePaths, (p)=>[
7338
- ...p
7339
- ]),
7340
- unmanagedPaths: nestedArray(snapshot.unmanagedPaths, (p)=>[
7341
- ...p
7342
- ]),
7343
- managedPaths: optionalNestedArray(snapshot.managedPaths, (p)=>[
7344
- ...p
7345
- ]) || [
7346
- /[\\/]node_modules[\\/][^.]/
7347
- ]
7348
- },
7349
- storage: {
7350
- type: 'filesystem',
7351
- directory: node_path.resolve(config.context || process.cwd(), cache.storage?.directory || 'node_modules/.cache/rspack')
7352
- },
7353
- portable: cache.portable,
7354
- readonly: cache.readonly
7336
+ if (!1 === cache) return !1;
7337
+ if (!0 === cache) return {
7338
+ type: 'memory'
7355
7339
  };
7340
+ switch(cache.type){
7341
+ case void 0:
7342
+ case 'memory':
7343
+ return {
7344
+ ...cache,
7345
+ type: 'memory'
7346
+ };
7347
+ case 'persistent':
7348
+ {
7349
+ let context = config.context || process.cwd();
7350
+ return {
7351
+ type: 'persistent',
7352
+ version: cache.version,
7353
+ portable: cache.portable,
7354
+ readonly: cache.readonly,
7355
+ buildDependencies: nestedArray(cache.buildDependencies, (deps)=>deps.map((d)=>node_path.resolve(context, d))),
7356
+ snapshot: nestedConfig(cache.snapshot, (snapshot)=>({
7357
+ immutablePaths: optionalNestedArray(snapshot.immutablePaths, (p)=>[
7358
+ ...p
7359
+ ]),
7360
+ unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, (p)=>[
7361
+ ...p
7362
+ ]),
7363
+ managedPaths: optionalNestedArray(snapshot.managedPaths, (p)=>[
7364
+ ...p
7365
+ ])
7366
+ })),
7367
+ storage: nestedConfig(cache.storage, (storage)=>({
7368
+ type: storage.type,
7369
+ directory: optionalNestedConfig(storage.directory, (d)=>node_path.resolve(context, d)),
7370
+ maxAge: storage.maxAge,
7371
+ maxGenerations: storage.maxGenerations
7372
+ }))
7373
+ };
7374
+ }
7375
+ default:
7376
+ throw Error(`Not implemented cache.type ${cache.type}`);
7377
+ }
7356
7378
  }),
7357
7379
  stats: nestedConfig(config.stats, (stats)=>!1 === stats ? {
7358
7380
  preset: 'none'
@@ -7490,31 +7512,49 @@ function __to_binding_runtime_globals(runtimeRequirements, compilerRuntimeGlobal
7490
7512
  return res;
7491
7513
  }
7492
7514
  var RuntimeGlobals_RuntimeGlobals = ((RuntimeGlobals = RuntimeGlobals_RuntimeGlobals || {})[RuntimeGlobals.require = 0] = "require", RuntimeGlobals[RuntimeGlobals.requireScope = 1] = "requireScope", RuntimeGlobals[RuntimeGlobals.exports = 2] = "exports", RuntimeGlobals[RuntimeGlobals.thisAsExports = 3] = "thisAsExports", RuntimeGlobals[RuntimeGlobals.returnExportsFromRuntime = 4] = "returnExportsFromRuntime", RuntimeGlobals[RuntimeGlobals.module = 5] = "module", RuntimeGlobals[RuntimeGlobals.moduleId = 6] = "moduleId", RuntimeGlobals[RuntimeGlobals.moduleLoaded = 7] = "moduleLoaded", RuntimeGlobals[RuntimeGlobals.publicPath = 8] = "publicPath", RuntimeGlobals[RuntimeGlobals.entryModuleId = 9] = "entryModuleId", RuntimeGlobals[RuntimeGlobals.moduleCache = 10] = "moduleCache", RuntimeGlobals[RuntimeGlobals.moduleFactories = 11] = "moduleFactories", RuntimeGlobals[RuntimeGlobals.moduleFactoriesAddOnly = 12] = "moduleFactoriesAddOnly", RuntimeGlobals[RuntimeGlobals.ensureChunk = 13] = "ensureChunk", RuntimeGlobals[RuntimeGlobals.ensureChunkHandlers = 14] = "ensureChunkHandlers", RuntimeGlobals[RuntimeGlobals.ensureChunkIncludeEntries = 15] = "ensureChunkIncludeEntries", RuntimeGlobals[RuntimeGlobals.prefetchChunk = 16] = "prefetchChunk", RuntimeGlobals[RuntimeGlobals.prefetchChunkHandlers = 17] = "prefetchChunkHandlers", RuntimeGlobals[RuntimeGlobals.preloadChunk = 18] = "preloadChunk", RuntimeGlobals[RuntimeGlobals.preloadChunkHandlers = 19] = "preloadChunkHandlers", RuntimeGlobals[RuntimeGlobals.definePropertyGetters = 20] = "definePropertyGetters", RuntimeGlobals[RuntimeGlobals.makeNamespaceObject = 21] = "makeNamespaceObject", RuntimeGlobals[RuntimeGlobals.createFakeNamespaceObject = 22] = "createFakeNamespaceObject", RuntimeGlobals[RuntimeGlobals.compatGetDefaultExport = 23] = "compatGetDefaultExport", RuntimeGlobals[RuntimeGlobals.harmonyModuleDecorator = 24] = "harmonyModuleDecorator", RuntimeGlobals[RuntimeGlobals.nodeModuleDecorator = 25] = "nodeModuleDecorator", RuntimeGlobals[RuntimeGlobals.getFullHash = 26] = "getFullHash", RuntimeGlobals[RuntimeGlobals.wasmInstances = 27] = "wasmInstances", RuntimeGlobals[RuntimeGlobals.instantiateWasm = 28] = "instantiateWasm", RuntimeGlobals[RuntimeGlobals.compileWasm = 29] = "compileWasm", RuntimeGlobals[RuntimeGlobals.uncaughtErrorHandler = 30] = "uncaughtErrorHandler", RuntimeGlobals[RuntimeGlobals.scriptNonce = 31] = "scriptNonce", RuntimeGlobals[RuntimeGlobals.loadScript = 32] = "loadScript", RuntimeGlobals[RuntimeGlobals.createScript = 33] = "createScript", RuntimeGlobals[RuntimeGlobals.createScriptUrl = 34] = "createScriptUrl", RuntimeGlobals[RuntimeGlobals.getTrustedTypesPolicy = 35] = "getTrustedTypesPolicy", RuntimeGlobals[RuntimeGlobals.hasFetchPriority = 36] = "hasFetchPriority", RuntimeGlobals[RuntimeGlobals.chunkName = 37] = "chunkName", RuntimeGlobals[RuntimeGlobals.runtimeId = 38] = "runtimeId", RuntimeGlobals[RuntimeGlobals.getChunkScriptFilename = 39] = "getChunkScriptFilename", RuntimeGlobals[RuntimeGlobals.getChunkCssFilename = 40] = "getChunkCssFilename", RuntimeGlobals[RuntimeGlobals.rspackVersion = 41] = "rspackVersion", RuntimeGlobals[RuntimeGlobals.hasCssModules = 42] = "hasCssModules", RuntimeGlobals[RuntimeGlobals.rspackUniqueId = 43] = "rspackUniqueId", RuntimeGlobals[RuntimeGlobals.getChunkUpdateScriptFilename = 44] = "getChunkUpdateScriptFilename", RuntimeGlobals[RuntimeGlobals.getChunkUpdateCssFilename = 45] = "getChunkUpdateCssFilename", RuntimeGlobals[RuntimeGlobals.startup = 46] = "startup", RuntimeGlobals[RuntimeGlobals.startupNoDefault = 47] = "startupNoDefault", RuntimeGlobals[RuntimeGlobals.startupOnlyAfter = 48] = "startupOnlyAfter", RuntimeGlobals[RuntimeGlobals.startupOnlyBefore = 49] = "startupOnlyBefore", RuntimeGlobals[RuntimeGlobals.chunkCallback = 50] = "chunkCallback", RuntimeGlobals[RuntimeGlobals.startupEntrypoint = 51] = "startupEntrypoint", RuntimeGlobals[RuntimeGlobals.startupChunkDependencies = 52] = "startupChunkDependencies", RuntimeGlobals[RuntimeGlobals.onChunksLoaded = 53] = "onChunksLoaded", RuntimeGlobals[RuntimeGlobals.externalInstallChunk = 54] = "externalInstallChunk", RuntimeGlobals[RuntimeGlobals.interceptModuleExecution = 55] = "interceptModuleExecution", RuntimeGlobals[RuntimeGlobals.global = 56] = "global", RuntimeGlobals[RuntimeGlobals.shareScopeMap = 57] = "shareScopeMap", RuntimeGlobals[RuntimeGlobals.initializeSharing = 58] = "initializeSharing", RuntimeGlobals[RuntimeGlobals.currentRemoteGetScope = 59] = "currentRemoteGetScope", RuntimeGlobals[RuntimeGlobals.getUpdateManifestFilename = 60] = "getUpdateManifestFilename", RuntimeGlobals[RuntimeGlobals.hmrDownloadManifest = 61] = "hmrDownloadManifest", RuntimeGlobals[RuntimeGlobals.hmrDownloadUpdateHandlers = 62] = "hmrDownloadUpdateHandlers", RuntimeGlobals[RuntimeGlobals.hmrModuleData = 63] = "hmrModuleData", RuntimeGlobals[RuntimeGlobals.hmrInvalidateModuleHandlers = 64] = "hmrInvalidateModuleHandlers", RuntimeGlobals[RuntimeGlobals.hmrRuntimeStatePrefix = 65] = "hmrRuntimeStatePrefix", RuntimeGlobals[RuntimeGlobals.amdDefine = 66] = "amdDefine", RuntimeGlobals[RuntimeGlobals.amdOptions = 67] = "amdOptions", RuntimeGlobals[RuntimeGlobals.system = 68] = "system", RuntimeGlobals[RuntimeGlobals.hasOwnProperty = 69] = "hasOwnProperty", RuntimeGlobals[RuntimeGlobals.systemContext = 70] = "systemContext", RuntimeGlobals[RuntimeGlobals.baseURI = 71] = "baseURI", RuntimeGlobals[RuntimeGlobals.relativeUrl = 72] = "relativeUrl", RuntimeGlobals[RuntimeGlobals.asyncModule = 73] = "asyncModule", RuntimeGlobals[RuntimeGlobals.asyncModuleExportSymbol = 74] = "asyncModuleExportSymbol", RuntimeGlobals[RuntimeGlobals.makeDeferredNamespaceObject = 75] = "makeDeferredNamespaceObject", RuntimeGlobals[RuntimeGlobals.makeDeferredNamespaceObjectSymbol = 76] = "makeDeferredNamespaceObjectSymbol", RuntimeGlobals);
7493
- function renderRuntimeVariables(variable, _compilerOptions) {
7515
+ function renderRuntimeVariables(variable, compilerOptions) {
7516
+ if (compilerOptions?.experiments.runtimeMode === 'rspack') switch(variable){
7517
+ case 0:
7518
+ return '__rspack_require';
7519
+ case 1:
7520
+ return '__rspack_context';
7521
+ case 2:
7522
+ return '__rspack_modules';
7523
+ case 3:
7524
+ return '__rspack_module_cache';
7525
+ case 4:
7526
+ return '__rspack_module';
7527
+ case 5:
7528
+ return '__rspack_exports';
7529
+ case 6:
7530
+ return '__rspack_exec';
7531
+ }
7494
7532
  switch(variable){
7495
7533
  case 0:
7496
7534
  return '__webpack_require__';
7497
7535
  case 1:
7498
- return '__webpack_modules__';
7536
+ return '__rspack_context';
7499
7537
  case 2:
7500
- return '__webpack_module_cache__';
7538
+ return '__webpack_modules__';
7501
7539
  case 3:
7502
- return '__webpack_module__';
7540
+ return '__webpack_module_cache__';
7503
7541
  case 4:
7504
- return '__webpack_exports__';
7542
+ return '__webpack_module__';
7505
7543
  case 5:
7544
+ return '__webpack_exports__';
7545
+ case 6:
7506
7546
  return '__webpack_exec__';
7507
7547
  }
7508
7548
  }
7509
7549
  function createCompilerRuntimeGlobals(compilerOptions) {
7510
7550
  let res = {};
7511
7551
  for (let key of Object.keys(RuntimeGlobals_RuntimeGlobals))res[key] = function(runtimeGlobals, _compilerOptions) {
7512
- let scope_name = renderRuntimeVariables(0, _compilerOptions), exports_name = renderRuntimeVariables(4, _compilerOptions);
7552
+ let require_name = renderRuntimeVariables(0, _compilerOptions), context_name = renderRuntimeVariables(1, _compilerOptions), usesRuntimeContext = _compilerOptions?.experiments.runtimeMode === 'rspack', scope_name = usesRuntimeContext ? context_name : require_name, exports_name = renderRuntimeVariables(5, _compilerOptions);
7513
7553
  switch(runtimeGlobals){
7514
7554
  case 0:
7515
- return scope_name;
7555
+ return usesRuntimeContext ? `${context_name}.r` : require_name;
7516
7556
  case 1:
7517
- return `${scope_name}.*`;
7557
+ return usesRuntimeContext ? context_name : `${require_name}.*`;
7518
7558
  case 2:
7519
7559
  return exports_name;
7520
7560
  case 3:
@@ -7554,7 +7594,7 @@ function createCompilerRuntimeGlobals(compilerOptions) {
7554
7594
  case 20:
7555
7595
  return `${scope_name}.d`;
7556
7596
  case 21:
7557
- return `${scope_name}.r`;
7597
+ return usesRuntimeContext ? `${context_name}.N` : `${require_name}.r`;
7558
7598
  case 22:
7559
7599
  return `${scope_name}.t`;
7560
7600
  case 23:
@@ -7678,9 +7718,10 @@ class ExecuteModulePlugin {
7678
7718
  compiler.__internal__get_module_execution_results_map().clear(), compilation.hooks.executeModule.tap('executeModule', (options, context)=>{
7679
7719
  let vm = ExecuteModulePlugin_require('node:vm'), moduleObject = options.moduleObject, source = options.codeGenerationResult.get("javascript");
7680
7720
  if (void 0 !== source) try {
7681
- vm.runInThisContext(`(function(module, ${renderRuntimeVariables(3, compiler.options)}, ${renderRuntimeVariables(4, compiler.options)}, exports, ${renderRuntimeVariables(0, compiler.options)}) {\n${source}\n})`, {
7721
+ let isRspackRuntimeMode = compiler.options.experiments?.runtimeMode === 'rspack', moduleArgument = renderRuntimeVariables(4, compiler.options), exportsArgument = renderRuntimeVariables(5, compiler.options), requireArgument = renderRuntimeVariables(0, compiler.options), runtimeContextArgument = renderRuntimeVariables(1, compiler.options), runtimeContext = context[runtimeContextArgument], runtimeModeArguments = isRspackRuntimeMode ? `, ${runtimeContextArgument}` : '';
7722
+ vm.runInThisContext(`(function(module, ${moduleArgument}, ${exportsArgument}, exports, ${requireArgument}${runtimeModeArguments}) {\n${source}\n})`, {
7682
7723
  filename: moduleObject.id
7683
- }).call(moduleObject.exports, moduleObject, moduleObject, moduleObject.exports, moduleObject.exports, context[renderRuntimeVariables(0, compiler.options)]);
7724
+ }).call(moduleObject.exports, moduleObject, moduleObject, moduleObject.exports, moduleObject.exports, context[requireArgument], runtimeContext);
7684
7725
  } catch (e) {
7685
7726
  let err = e instanceof Error ? e : Error(e);
7686
7727
  throw err.stack += printGeneratedCodeForStack(moduleObject.id, source), err;
@@ -8288,7 +8329,7 @@ class MultiStats {
8288
8329
  obj.children = this.stats.map((stat, idx)=>{
8289
8330
  let obj = stat.toJson(childOptions.children[idx]), compilationName = stat.compilation.name;
8290
8331
  return obj.name = compilationName && makePathsRelative(childOptions.context, compilationName, stat.compilation.compiler.root), obj;
8291
- }), childOptions.version && (obj.rspackVersion = "2.0.8", obj.version = "5.75.0"), childOptions.hash && (obj.hash = obj.children.map((j)=>j.hash).join(''));
8332
+ }), childOptions.version && (obj.rspackVersion = "2.1.0-rc.0", obj.version = "5.75.0"), childOptions.hash && (obj.hash = obj.children.map((j)=>j.hash).join(''));
8292
8333
  let mapError = (j, obj)=>({
8293
8334
  ...obj,
8294
8335
  compilerPath: obj.compilerPath ? `${j.name}.${obj.compilerPath}` : j.name
@@ -8797,7 +8838,7 @@ let arraySum = (array)=>{
8797
8838
  let str = `${a}`, length = lengths[i];
8798
8839
  return str.length === length ? str : length > 5 ? `...${str.slice(-length + 3)}` : length > 0 ? str.slice(-length) : '';
8799
8840
  });
8800
- }, CachedInputFileSystem = __webpack_require__("../../node_modules/.pnpm/enhanced-resolve@5.22.1/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js");
8841
+ }, CachedInputFileSystem = __webpack_require__("../../node_modules/.pnpm/enhanced-resolve@5.24.0/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js");
8801
8842
  var CachedInputFileSystem_default = __webpack_require__.n(CachedInputFileSystem);
8802
8843
  class NodeEnvironmentPlugin {
8803
8844
  options;
@@ -9562,7 +9603,7 @@ let iterateConfig = (config, options, fn)=>{
9562
9603
  object.hash = context.getStatsCompilation(compilation).hash;
9563
9604
  },
9564
9605
  version: (object)=>{
9565
- object.version = "5.75.0", object.rspackVersion = "2.0.8";
9606
+ object.version = "5.75.0", object.rspackVersion = "2.1.0-rc.0";
9566
9607
  },
9567
9608
  env: (object, _compilation, _context, { _env })=>{
9568
9609
  object.env = _env;
@@ -10827,7 +10868,7 @@ class RspackOptionsApply {
10827
10868
  moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
10828
10869
  namespace: options.output.devtoolNamespace
10829
10870
  }).apply(compiler);
10830
- new JavascriptModulesPlugin().apply(compiler), new URLPlugin().apply(compiler), new JsonModulesPlugin().apply(compiler), new AssetModulesPlugin().apply(compiler), options.experiments.asyncWebAssembly && new AsyncWebAssemblyModulesPlugin().apply(compiler), new CssModulesPlugin().apply(compiler), new lib_EntryOptionPlugin().apply(compiler), assertNotNill(options.context), compiler.hooks.entryOption.call(options.context, options.entry), new RuntimePlugin().apply(compiler), options.output.bundlerInfo && new BundlerInfoRspackPlugin(options.output.bundlerInfo).apply(compiler), new InferAsyncModulesPlugin().apply(compiler), new APIPlugin().apply(compiler), new DataUriPlugin().apply(compiler), new FileUriPlugin().apply(compiler), options.experiments.buildHttp && new HttpUriPlugin(options.experiments.buildHttp).apply(compiler), new EnsureChunkConditionsPlugin().apply(compiler), options.optimization.mergeDuplicateChunks && new MergeDuplicateChunksPlugin().apply(compiler), options.optimization.sideEffects && new SideEffectsFlagPlugin(options.experiments.pureFunctions).apply(compiler), options.optimization.providedExports && new FlagDependencyExportsPlugin().apply(compiler), 'production' === options.mode && new CircularModulesInfoPlugin().apply(compiler), options.optimization.usedExports && new FlagDependencyUsagePlugin('global' === options.optimization.usedExports).apply(compiler), options.optimization.concatenateModules && new ModuleConcatenationPlugin().apply(compiler), options.optimization.inlineExports && new InlineExportsPlugin().apply(compiler), options.optimization.mangleExports && new MangleExportsPlugin('size' !== options.optimization.mangleExports).apply(compiler);
10871
+ new JavascriptModulesPlugin().apply(compiler), new URLPlugin().apply(compiler), new JsonModulesPlugin().apply(compiler), new AssetModulesPlugin().apply(compiler), options.experiments.asyncWebAssembly && new AsyncWebAssemblyModulesPlugin().apply(compiler), new CssModulesPlugin().apply(compiler), new lib_EntryOptionPlugin().apply(compiler), assertNotNill(options.context), compiler.hooks.entryOption.call(options.context, options.entry), new RuntimePlugin().apply(compiler), options.output.bundlerInfo && new BundlerInfoRspackPlugin(options.output.bundlerInfo).apply(compiler), new InferAsyncModulesPlugin().apply(compiler), new APIPlugin().apply(compiler), new DataUriPlugin().apply(compiler), new FileUriPlugin().apply(compiler), options.experiments.buildHttp && new HttpUriPlugin(options.experiments.buildHttp).apply(compiler), new EnsureChunkConditionsPlugin().apply(compiler), options.optimization.mergeDuplicateChunks && new MergeDuplicateChunksPlugin().apply(compiler), options.optimization.sideEffects && new SideEffectsFlagPlugin(options.experiments.pureFunctions && !0 === options.optimization.sideEffects).apply(compiler), options.optimization.providedExports && new FlagDependencyExportsPlugin().apply(compiler), 'production' === options.mode && new CircularModulesInfoPlugin().apply(compiler), options.optimization.usedExports && new FlagDependencyUsagePlugin('global' === options.optimization.usedExports).apply(compiler), options.optimization.concatenateModules && new ModuleConcatenationPlugin().apply(compiler), options.optimization.inlineExports && new InlineExportsPlugin().apply(compiler), options.optimization.mangleExports && new MangleExportsPlugin('size' !== options.optimization.mangleExports).apply(compiler);
10831
10872
  let enableLibSplitChunks = !1;
10832
10873
  if (options.output.enabledLibraryTypes && options.output.enabledLibraryTypes.length > 0) {
10833
10874
  let hasModernModule = options.output.enabledLibraryTypes.includes('modern-module'), hasNonModernModule = options.output.enabledLibraryTypes.some((t)=>'modern-module' !== t);
@@ -10909,7 +10950,7 @@ function validateRspackConfig(config) {
10909
10950
  Array.isArray(externals) ? externals.forEach((external)=>checkExternalItem(external)) : checkExternalItem(externals);
10910
10951
  })(config);
10911
10952
  }
10912
- function createCompiler(userOptions) {
10953
+ function createCompiler(userOptions, compilerIndex) {
10913
10954
  var infrastructureLogging;
10914
10955
  let tty, options = getNormalizedRspackOptions(userOptions);
10915
10956
  if (F(options, 'context', ()=>process.cwd()), F(infrastructureLogging = options.infrastructureLogging, 'stream', ()=>process.stderr), tty = infrastructureLogging.stream?.isTTY && 'dumb' !== process.env.TERM, D(infrastructureLogging, 'level', 'info'), D(infrastructureLogging, 'debug', !1), D(infrastructureLogging, 'colors', tty), D(infrastructureLogging, 'appendOnly', !tty), isNil(options.context)) throw Error('options.context is required');
@@ -10917,7 +10958,7 @@ function createCompiler(userOptions) {
10917
10958
  if (new NodeEnvironmentPlugin({
10918
10959
  infrastructureLogging: options.infrastructureLogging
10919
10960
  }).apply(compiler), Array.isArray(options.plugins)) for (let plugin of options.plugins)'function' == typeof plugin ? plugin.call(compiler, compiler) : plugin && plugin.apply(compiler);
10920
- let tp = applyRspackOptionsDefaults(compiler.options);
10961
+ let tp = applyRspackOptionsDefaults(compiler.options, compilerIndex);
10921
10962
  return tp && (compiler.platform = tp.platform, compiler.target = {
10922
10963
  esVersion: tp.esVersion,
10923
10964
  targets: tp.targets
@@ -10937,7 +10978,7 @@ function rspack_rspack(options, callback) {
10937
10978
  let create = ()=>{
10938
10979
  if (isMultiRspackOptions(options)) {
10939
10980
  let compiler = function(options) {
10940
- let compilers = options.map(createCompiler), compiler = new MultiCompiler(compilers, options);
10981
+ let compilers = options.map((option, index)=>createCompiler(option, index)), compiler = new MultiCompiler(compilers, options);
10941
10982
  for (let childCompiler of compilers)childCompiler.options.dependencies && compiler.setDependencies(childCompiler, childCompiler.options.dependencies);
10942
10983
  return compiler;
10943
10984
  }(options);
@@ -11223,7 +11264,7 @@ class TraceHookPlugin {
11223
11264
  });
11224
11265
  }
11225
11266
  }
11226
- let CORE_VERSION = "2.0.8", VFILES_BY_COMPILER = new WeakMap();
11267
+ let CORE_VERSION = "2.1.0-rc.0", VFILES_BY_COMPILER = new WeakMap();
11227
11268
  class VirtualModulesPlugin {
11228
11269
  #staticModules;
11229
11270
  #compiler;
@@ -11589,7 +11630,7 @@ class Compiler {
11589
11630
  electron: null
11590
11631
  }, this.#target = {}, this.__internal_browser_require = ()=>{
11591
11632
  throw Error('Cannot execute user defined code in browser without `BrowserRequirePlugin`');
11592
- }, this.resolverFactory = new ResolverFactory(options.resolve.pnp ?? getPnpDefault(), options.resolve, options.resolveLoader), new JsLoaderRspackPlugin(this).apply(this), new ExecuteModulePlugin().apply(this), 'on' === JavaScriptTracer.state && new TraceHookPlugin().apply(this), Object.defineProperty(this, GET_COMPILER_ID, {
11633
+ }, this.resolverFactory = new ResolverFactory(options.resolve.pnp ?? getPnpDefault(), options.resolve, options.resolveLoader), new JsLoaderRspackPlugin(this).apply(this), new ExecuteModulePlugin().apply(this), JavaScriptTracer.isEnabled() && new TraceHookPlugin().apply(this), Object.defineProperty(this, GET_COMPILER_ID, {
11593
11634
  writable: !1,
11594
11635
  configurable: !1,
11595
11636
  enumerable: !1,
@@ -11878,7 +11919,29 @@ Help:
11878
11919
  return delete obj.preset, obj;
11879
11920
  }(options.stats)).colors ? isStatsColorSupported() : !!statsOptions.colors
11880
11921
  },
11881
- cache: options.cache || !1,
11922
+ cache: function(cache) {
11923
+ if (!1 === cache) return !1;
11924
+ if ('memory' === cache.type) return cache;
11925
+ let toRawStorageLimit = (name, value)=>{
11926
+ if (value === 1 / 0) return 0;
11927
+ if (!Number.isSafeInteger(value) || value < 1 || value > 0xffffffff) throw Error(`Invalid Rspack configuration: "${name}" must be a positive integer (1..4294967295) or Infinity, get \`${value}\`.`);
11928
+ return value;
11929
+ };
11930
+ return {
11931
+ ...cache,
11932
+ storage: {
11933
+ ...cache.storage,
11934
+ directory: cache.storage.directory,
11935
+ maxAge: toRawStorageLimit('cache.storage.maxAge', cache.storage.maxAge),
11936
+ maxGenerations: toRawStorageLimit('cache.storage.maxGenerations', cache.storage.maxGenerations)
11937
+ },
11938
+ snapshot: {
11939
+ immutablePaths: cache.snapshot.immutablePaths,
11940
+ unmanagedPaths: cache.snapshot.unmanagedPaths,
11941
+ managedPaths: cache.snapshot.managedPaths
11942
+ }
11943
+ };
11944
+ }(options.cache),
11882
11945
  experiments,
11883
11946
  incremental: options.incremental,
11884
11947
  node: function(node) {
@@ -12035,7 +12098,10 @@ Help:
12035
12098
  let originSource = module.source?.source;
12036
12099
  queried.call(runtimeModule, chunk);
12037
12100
  let newSource = module.source?.source;
12038
- if (newSource && newSource !== originSource) return module;
12101
+ if (newSource && newSource !== originSource) {
12102
+ if (getCompiler().options.experiments?.runtimeMode === 'rspack') throw Error('Compilation.hooks.runtimeModule source modifications are not supported when experiments.runtimeMode is "rspack".');
12103
+ return module;
12104
+ }
12039
12105
  };
12040
12106
  }),
12041
12107
  registerCompilationBuildModuleTaps: createTap(binding_default().RegisterJsTapKind.CompilationBuildModule, function() {
@@ -12064,7 +12130,7 @@ Help:
12064
12130
  }, function(queried) {
12065
12131
  return function({ entry, id, codegenResults, runtimeModules }) {
12066
12132
  try {
12067
- let RuntimeGlobals = getCompiler().rspack.RuntimeGlobals, moduleRequireFn = (id)=>{
12133
+ let RuntimeGlobals = getCompiler().rspack.RuntimeGlobals, runtimeContext = {}, moduleRequireFn = (id)=>{
12068
12134
  let cached = moduleCache[id];
12069
12135
  if (void 0 !== cached) {
12070
12136
  if (cached.error) throw cached.error;
@@ -12093,10 +12159,13 @@ Help:
12093
12159
  codeGenerationResult: new CodeGenerationResult(result),
12094
12160
  moduleObject
12095
12161
  }, {
12096
- [RuntimeGlobals.require]: moduleRequireFn
12162
+ [RuntimeGlobals.require]: moduleRequireFn,
12163
+ [renderRuntimeVariables(0, getCompiler().options)]: moduleRequireFn,
12164
+ [renderRuntimeVariables(1, getCompiler().options)]: runtimeContext
12097
12165
  }), 'Compilation.hooks.executeModule'), moduleObject.loaded = !0, moduleObject.exports;
12098
12166
  }, moduleCache = moduleRequireFn[RuntimeGlobals.moduleCache.replace(`${RuntimeGlobals.require}.`, '')] = {}, interceptModuleExecution = moduleRequireFn[RuntimeGlobals.interceptModuleExecution.replace(`${RuntimeGlobals.require}.`, '')] = [];
12099
- for (let runtimeModule of runtimeModules)moduleRequireFn(runtimeModule);
12167
+ for (let runtimeModule of (moduleRequireFn.r = moduleRequireFn, runtimeContext.r = moduleRequireFn, runtimeModules))moduleRequireFn(runtimeModule);
12168
+ for (let key of Reflect.ownKeys(moduleRequireFn))runtimeContext[key] = moduleRequireFn[key];
12100
12169
  let executeResult = moduleRequireFn(entry);
12101
12170
  getCompiler().__internal__get_module_execution_results_map().set(id, executeResult);
12102
12171
  } catch (e) {
@@ -13474,6 +13543,7 @@ function getDefaultEntryRuntimeRequest(resource) {
13474
13543
  return `${MF_RUNTIME_LOADER}!=!${resource}`;
13475
13544
  }
13476
13545
  function getDefaultEntryRuntimeSource(paths, options, compiler, treeShakingShareFallbacks) {
13546
+ var source, runtimeRequire;
13477
13547
  let runtimePlugins = options.runtimePlugins ?? [], remoteInfos = getRemoteInfos(options), runtimePluginImports = [], runtimePluginVars = [], libraryType = options.library?.type || 'var', shouldInitializePublicPath = getSharedOptions(options).some(([, config])=>config.treeShaking);
13478
13548
  for(let i = 0; i < runtimePlugins.length; i++){
13479
13549
  let runtimePluginVar = `__module_federation_runtime_plugin_${i}__`, pluginSpec = runtimePlugins[i], pluginPath = Array.isArray(pluginSpec) ? pluginSpec[0] : pluginSpec, pluginParams = Array.isArray(pluginSpec) ? pluginSpec[1] : void 0;
@@ -13481,12 +13551,25 @@ function getDefaultEntryRuntimeSource(paths, options, compiler, treeShakingShare
13481
13551
  let paramsCode = void 0 === pluginParams ? 'undefined' : JSON.stringify(pluginParams);
13482
13552
  runtimePluginVars.push(`{ plugin: ${runtimePluginVar}, params: ${paramsCode} }`);
13483
13553
  }
13554
+ let defaultRuntimeSource = compiler.rspack.Template.getFunctionContent(ModuleFederationPlugin_require('./moduleFederationDefaultRuntime.js').default), compilerRuntimeGlobals = createCompilerRuntimeGlobals(compiler.options), runtimeSource = (source = defaultRuntimeSource, runtimeRequire = 'rspack' === compiler.options.experiments.runtimeMode ? `new Proxy(function (moduleId) {
13555
+ return ${compilerRuntimeGlobals.require}(moduleId);
13556
+ }, {
13557
+ get(_target, key) {
13558
+ return ${compilerRuntimeGlobals.requireScope}[key];
13559
+ },
13560
+ set(_target, key, value) {
13561
+ ${compilerRuntimeGlobals.requireScope}[key] = value;
13562
+ return true;
13563
+ }
13564
+ })` : compilerRuntimeGlobals.require, source.replace('__module_federation_runtime_require__', runtimeRequire));
13484
13565
  return [
13485
13566
  `import __module_federation_bundler_runtime__ from ${JSON.stringify(paths.bundlerRuntime)}`,
13486
13567
  ...runtimePluginImports,
13487
13568
  shouldInitializePublicPath ? function(compiler) {
13488
13569
  let publicPath = compiler.options.output.publicPath;
13489
- if ('string' == typeof publicPath && 'auto' !== publicPath) return `if (typeof __webpack_require__.p === "undefined") __webpack_require__.p = ${JSON.stringify(publicPath)}`;
13570
+ if ('string' != typeof publicPath || 'auto' === publicPath) return;
13571
+ let publicPathRuntimeGlobal = createCompilerRuntimeGlobals().publicPath;
13572
+ return `if (typeof ${publicPathRuntimeGlobal} === "undefined") ${publicPathRuntimeGlobal} = ${JSON.stringify(publicPath)}`;
13490
13573
  }(compiler) : void 0,
13491
13574
  `const __module_federation_runtime_plugins__ = [${runtimePluginVars.join(', ')}].filter(({ plugin }) => plugin).map(({ plugin, params }) => plugin(params))`,
13492
13575
  `const __module_federation_remote_infos__ = ${JSON.stringify(remoteInfos)}`,
@@ -13494,7 +13577,7 @@ function getDefaultEntryRuntimeSource(paths, options, compiler, treeShakingShare
13494
13577
  `const __module_federation_share_strategy__ = ${JSON.stringify(options.shareStrategy ?? 'version-first')}`,
13495
13578
  `const __module_federation_share_fallbacks__ = ${JSON.stringify(treeShakingShareFallbacks)}`,
13496
13579
  `const __module_federation_library_type__ = ${JSON.stringify(libraryType)}`,
13497
- compiler.rspack.Template.getFunctionContent(ModuleFederationPlugin_require('./moduleFederationDefaultRuntime.js').default)
13580
+ runtimeSource
13498
13581
  ].join(';');
13499
13582
  }
13500
13583
  function getDefaultEntryRuntime(paths, options, compiler, treeShakingShareFallbacks) {
@@ -13602,7 +13685,7 @@ async function transform(source, options) {
13602
13685
  let _options = JSON.stringify(options || {});
13603
13686
  return binding_default().transform(source, _options);
13604
13687
  }
13605
- let exports_rspackVersion = "2.0.8", exports_version = "5.75.0", exports_WebpackError = Error, exports_config = {
13688
+ let exports_rspackVersion = "2.1.0-rc.0", exports_version = "5.75.0", exports_WebpackError = Error, exports_config = {
13606
13689
  getNormalizedRspackOptions: getNormalizedRspackOptions,
13607
13690
  applyRspackOptionsDefaults: applyRspackOptionsDefaults,
13608
13691
  getNormalizedWebpackOptions: getNormalizedRspackOptions,