@rspack/core 0.7.2 → 0.7.3-canary-607ec67-20240612123914

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.
Files changed (32) hide show
  1. package/dist/Compiler.js +1 -0
  2. package/dist/RuleSetCompiler.d.ts +1 -0
  3. package/dist/RuleSetCompiler.js +1 -0
  4. package/dist/builtin-loader/swc/index.d.ts +3 -1
  5. package/dist/builtin-loader/swc/index.js +3 -1
  6. package/dist/builtin-loader/swc/preact.d.ts +7 -0
  7. package/dist/builtin-loader/swc/preact.js +15 -0
  8. package/dist/builtin-plugin/ExternalsPlugin.d.ts +2 -2
  9. package/dist/builtin-plugin/JsLoaderRspackPlugin.d.ts +1 -1
  10. package/dist/builtin-plugin/ProgressPlugin.js +5 -1
  11. package/dist/builtin-plugin/RSCClientEntryRspackPlugin.d.ts +10 -0
  12. package/dist/builtin-plugin/RSCClientEntryRspackPlugin.js +6 -0
  13. package/dist/builtin-plugin/RSCClientReferenceManifestRspackPlugin.d.ts +21 -0
  14. package/dist/builtin-plugin/RSCClientReferenceManifestRspackPlugin.js +60 -0
  15. package/dist/builtin-plugin/RSCProxyRspackPlugin.d.ts +12 -0
  16. package/dist/builtin-plugin/RSCProxyRspackPlugin.js +28 -0
  17. package/dist/builtin-plugin/index.d.ts +6 -0
  18. package/dist/builtin-plugin/index.js +6 -0
  19. package/dist/config/adapter.js +9 -9
  20. package/dist/config/adapterRuleUse.d.ts +3 -39
  21. package/dist/config/adapterRuleUse.js +14 -7
  22. package/dist/config/normalization.d.ts +1 -0
  23. package/dist/config/zod.d.ts +310 -302
  24. package/dist/config/zod.js +2 -1
  25. package/dist/container/ContainerReferencePlugin.d.ts +1 -1
  26. package/dist/exports.d.ts +3 -0
  27. package/dist/exports.js +7 -0
  28. package/dist/loader-runner/index.d.ts +25 -2
  29. package/dist/loader-runner/index.js +333 -345
  30. package/dist/loader-runner/loadLoader.js +1 -53
  31. package/dist/util/index.d.ts +1 -1
  32. package/package.json +4 -4
@@ -8,45 +8,38 @@
8
8
  * Copyright (c) JS Foundation and other contributors
9
9
  * https://github.com/webpack/loader-runner/blob/main/LICENSE
10
10
  */
11
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
+ if (kind === "m") throw new TypeError("Private method is not writable");
13
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
+ };
17
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ var _LoaderObject_cachedData, _LoaderObject_loaderItem;
11
26
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.runLoaders = exports.parsePathQueryFragment = void 0;
27
+ exports.parsePathQueryFragment = exports.runLoaders = exports.LoaderObject = void 0;
28
+ const node_querystring_1 = __importDefault(require("node:querystring"));
29
+ const assert_1 = __importDefault(require("assert"));
30
+ const util_1 = require("util");
31
+ const binding_1 = require("@rspack/binding");
13
32
  const webpack_sources_1 = require("webpack-sources");
33
+ const Module_1 = require("../Module");
14
34
  const NormalModule_1 = require("../NormalModule");
15
35
  const adapterRuleUse_1 = require("../config/adapterRuleUse");
16
- const util_1 = require("../util");
36
+ const util_2 = require("../util");
17
37
  const createHash_1 = require("../util/createHash");
18
38
  const identifier_1 = require("../util/identifier");
19
39
  const memoize_1 = require("../util/memoize");
20
- const loadLoader = require("./loadLoader");
21
- const Module_1 = require("../Module");
22
- const querystring = require("node:querystring");
23
- const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
24
- function parsePathQueryFragment(str) {
25
- const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
26
- return {
27
- path: match?.[1].replace(/\u200b(.)/g, "$1") || "",
28
- query: match?.[2] ? match[2].replace(/\u200b(.)/g, "$1") : "",
29
- fragment: match?.[3] || ""
30
- };
31
- }
32
- exports.parsePathQueryFragment = parsePathQueryFragment;
33
- function dirname(path) {
34
- if (path === "/")
35
- return "/";
36
- const i = path.lastIndexOf("/");
37
- const j = path.lastIndexOf("\\");
38
- const i2 = path.indexOf("/");
39
- const j2 = path.indexOf("\\");
40
- const idx = i > j ? i : j;
41
- const idx2 = i > j ? i2 : j2;
42
- if (idx < 0)
43
- return path;
44
- if (idx === idx2)
45
- return path.slice(0, idx + 1);
46
- return path.slice(0, idx);
47
- }
40
+ const loadLoader_1 = __importDefault(require("./loadLoader"));
48
41
  function createLoaderObject(loader, compiler) {
49
- const obj = {
42
+ var obj = {
50
43
  path: null,
51
44
  query: null,
52
45
  fragment: null,
@@ -67,37 +60,42 @@ function createLoaderObject(loader, compiler) {
67
60
  obj.fragment);
68
61
  },
69
62
  set: function (value) {
70
- if (typeof value === "string") {
71
- const splittedRequest = parsePathQueryFragment(value);
72
- obj.path = splittedRequest.path;
73
- obj.query = splittedRequest.query;
74
- obj.fragment = splittedRequest.fragment;
75
- obj.options = undefined;
76
- obj.ident = undefined;
77
- }
78
- else {
79
- if (!value.loader)
80
- throw new Error("request should be a string or object with loader and options (" +
81
- JSON.stringify(value) +
82
- ")");
83
- obj.path = value.loader;
84
- obj.fragment = value.fragment || "";
85
- obj.type = value.type;
86
- obj.options = value.options;
87
- obj.ident = value.ident;
88
- if (obj.options === null)
89
- obj.query = value.query;
90
- else if (obj.options === undefined)
91
- obj.query = value.query;
92
- else if (typeof obj.options === "string")
93
- obj.query = "?" + obj.options;
94
- else if (obj.ident)
95
- obj.query = "??" + obj.ident;
96
- else if (typeof obj.options === "object" && obj.options.ident)
97
- obj.query = "??" + obj.options.ident;
98
- else
99
- obj.query = "?" + JSON.stringify(obj.options);
63
+ var splittedRequest = (0, identifier_1.parseResourceWithoutFragment)(value.request);
64
+ obj.path = splittedRequest.path;
65
+ obj.query = splittedRequest.query;
66
+ obj.fragment = splittedRequest.fragment || "";
67
+ obj.options =
68
+ obj.options === null
69
+ ? splittedRequest.query
70
+ ? splittedRequest.query.slice(1)
71
+ : undefined
72
+ : obj.options;
73
+ if (typeof obj.options === "string" && obj.options[0] === "?") {
74
+ const ident = obj.options.slice(1);
75
+ if (ident === "[[missing ident]]") {
76
+ throw new Error("No ident is provided by referenced loader. " +
77
+ "When using a function for Rule.use in config you need to " +
78
+ "provide an 'ident' property for referenced loader options.");
79
+ }
80
+ obj.options = compiler.__internal__ruleSet.references.get(ident);
81
+ if (obj.options === undefined) {
82
+ throw new Error("Invalid ident is provided by referenced loader");
83
+ }
84
+ obj.ident = ident;
100
85
  }
86
+ obj.type = value.type;
87
+ if (obj.options === null)
88
+ obj.query = "";
89
+ else if (obj.options === undefined)
90
+ obj.query = "";
91
+ else if (typeof obj.options === "string")
92
+ obj.query = "?" + obj.options;
93
+ else if (obj.ident)
94
+ obj.query = "??" + obj.ident;
95
+ else if (typeof obj.options === "object" && obj.options.ident)
96
+ obj.query = "??" + obj.options.ident;
97
+ else
98
+ obj.query = "?" + JSON.stringify(obj.options);
101
99
  }
102
100
  });
103
101
  obj.request = loader;
@@ -106,6 +104,169 @@ function createLoaderObject(loader, compiler) {
106
104
  }
107
105
  return obj;
108
106
  }
107
+ class LoaderObject {
108
+ constructor(loaderItem, compiler) {
109
+ _LoaderObject_cachedData.set(this, void 0);
110
+ _LoaderObject_loaderItem.set(this, void 0);
111
+ const { request, path, query, fragment, options, ident, normal, pitch, raw, type } = createLoaderObject(loaderItem, compiler);
112
+ this.request = request;
113
+ this.path = path;
114
+ this.query = query;
115
+ this.fragment = fragment;
116
+ this.options = options;
117
+ this.ident = ident;
118
+ this.normal = normal;
119
+ this.pitch = pitch;
120
+ this.raw = raw;
121
+ this.type = type;
122
+ __classPrivateFieldSet(this, _LoaderObject_loaderItem, loaderItem, "f");
123
+ __classPrivateFieldSet(this, _LoaderObject_cachedData, null, "f");
124
+ }
125
+ get pitchExecuted() {
126
+ return (0, binding_1.__loader_item_get_pitch_executed)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner);
127
+ }
128
+ set pitchExecuted(value) {
129
+ (0, assert_1.default)(value);
130
+ (0, binding_1.__loader_item_set_pitch_executed)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner);
131
+ }
132
+ get normalExecuted() {
133
+ return (0, binding_1.__loader_item_get_normal_executed)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner);
134
+ }
135
+ set normalExecuted(value) {
136
+ (0, assert_1.default)(value);
137
+ (0, binding_1.__loader_item_set_normal_executed)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner);
138
+ }
139
+ // A data object shared between the pitch and the normal phase
140
+ get data() {
141
+ __classPrivateFieldSet(this, _LoaderObject_cachedData, __classPrivateFieldGet(this, _LoaderObject_cachedData, "f") ??
142
+ (0, binding_1.__loader_item_get_loader_data)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner) ??
143
+ {}, "f");
144
+ return new Proxy(__classPrivateFieldGet(this, _LoaderObject_cachedData, "f"), {
145
+ set: (_, property, value) => {
146
+ if (typeof property === "string") {
147
+ console.log(property, value);
148
+ __classPrivateFieldGet(this, _LoaderObject_cachedData, "f")[property] = value;
149
+ (0, binding_1.__loader_item_set_loader_data)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner, __classPrivateFieldGet(this, _LoaderObject_cachedData, "f"));
150
+ }
151
+ return true;
152
+ },
153
+ get: (_, property) => {
154
+ if (typeof property === "string") {
155
+ return __classPrivateFieldGet(this, _LoaderObject_cachedData, "f")[property];
156
+ }
157
+ }
158
+ });
159
+ }
160
+ // A data object shared between the pitch and the normal phase
161
+ set data(data) {
162
+ __classPrivateFieldSet(this, _LoaderObject_cachedData, data, "f");
163
+ (0, binding_1.__loader_item_set_loader_data)(__classPrivateFieldGet(this, _LoaderObject_loaderItem, "f").inner, data);
164
+ }
165
+ shouldYield() {
166
+ return this.request.startsWith(adapterRuleUse_1.BUILTIN_LOADER_PREFIX);
167
+ }
168
+ static __from_binding(loaderItem, compiler) {
169
+ return new this(loaderItem, compiler);
170
+ }
171
+ static __to_binding(loader) {
172
+ return __classPrivateFieldGet(loader, _LoaderObject_loaderItem, "f").inner;
173
+ }
174
+ }
175
+ exports.LoaderObject = LoaderObject;
176
+ _LoaderObject_cachedData = new WeakMap(), _LoaderObject_loaderItem = new WeakMap();
177
+ class JsSourceMap {
178
+ static __from_binding(map) {
179
+ return (0, util_2.isNil)(map) ? undefined : (0, util_2.toObject)(map);
180
+ }
181
+ static __to_binding(map) {
182
+ return (0, util_2.serializeObject)(map);
183
+ }
184
+ }
185
+ const loadLoaderAsync = (0, util_1.promisify)(loadLoader_1.default);
186
+ const runSyncOrAsync = (0, util_1.promisify)(function runSyncOrAsync(fn, context, args, callback) {
187
+ let isSync = true;
188
+ let isDone = false;
189
+ let isError = false; // internal error
190
+ let reportedError = false;
191
+ // @ts-expect-error loader-runner leverages `arguments` to achieve the same functionality.
192
+ context.async = function async() {
193
+ if (isDone) {
194
+ if (reportedError)
195
+ return; // ignore
196
+ throw new Error("async(): The callback was already called.");
197
+ }
198
+ isSync = false;
199
+ return innerCallback;
200
+ };
201
+ const innerCallback = (context.callback = function (err, ...args) {
202
+ if (isDone) {
203
+ if (reportedError)
204
+ return; // ignore
205
+ throw new Error("callback(): The callback was already called.");
206
+ }
207
+ isDone = true;
208
+ isSync = false;
209
+ try {
210
+ // @ts-expect-error
211
+ callback(err, args);
212
+ }
213
+ catch (e) {
214
+ isError = true;
215
+ throw e;
216
+ }
217
+ });
218
+ try {
219
+ const result = (function LOADER_EXECUTION() {
220
+ return fn.apply(context, args);
221
+ })();
222
+ if (isSync) {
223
+ isDone = true;
224
+ // @ts-expect-error
225
+ if (result === undefined)
226
+ return callback();
227
+ if (result &&
228
+ typeof result === "object" &&
229
+ typeof result.then === "function") {
230
+ return result.then(function (r) {
231
+ callback(null, [r]);
232
+ }, callback);
233
+ }
234
+ return callback(null, [result]);
235
+ }
236
+ }
237
+ catch (e) {
238
+ if (isError)
239
+ throw e;
240
+ if (isDone) {
241
+ // loader is already "done", so we cannot use the callback function
242
+ // for better debugging we print the error on the console
243
+ if (e instanceof Error)
244
+ console.error(e.stack);
245
+ else
246
+ console.error(e);
247
+ return;
248
+ }
249
+ isDone = true;
250
+ reportedError = true;
251
+ // @ts-expect-error
252
+ callback(e);
253
+ }
254
+ });
255
+ function dirname(path) {
256
+ if (path === "/")
257
+ return "/";
258
+ const i = path.lastIndexOf("/");
259
+ const j = path.lastIndexOf("\\");
260
+ const i2 = path.indexOf("/");
261
+ const j2 = path.indexOf("\\");
262
+ const idx = i > j ? i : j;
263
+ const idx2 = i > j ? i2 : j2;
264
+ if (idx < 0)
265
+ return path;
266
+ if (idx === idx2)
267
+ return path.slice(0, idx + 1);
268
+ return path.slice(0, idx);
269
+ }
109
270
  function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
110
271
  if (loaderContext.loaders &&
111
272
  loaderContext.loaders.length &&
@@ -116,10 +277,10 @@ function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
116
277
  }
117
278
  return null;
118
279
  }
119
- async function runLoaders(compiler, rawContext) {
120
- const resource = rawContext.resource;
121
- const loaderContext = {};
280
+ async function runLoaders(compiler, context) {
281
+ const loaderState = context.loaderState;
122
282
  //
283
+ const { resource } = context.resourceData;
123
284
  const splittedResource = resource && parsePathQueryFragment(resource);
124
285
  const resourcePath = splittedResource ? splittedResource.path : undefined;
125
286
  const resourceQuery = splittedResource ? splittedResource.query : undefined;
@@ -128,51 +289,21 @@ async function runLoaders(compiler, rawContext) {
128
289
  : undefined;
129
290
  const contextDirectory = resourcePath ? dirname(resourcePath) : null;
130
291
  // execution state
131
- let cacheable = true;
132
- const fileDependencies = rawContext.fileDependencies.slice();
133
- const contextDependencies = rawContext.contextDependencies.slice();
134
- const missingDependencies = rawContext.missingDependencies.slice();
135
- const buildDependencies = rawContext.buildDependencies.slice();
136
- const assetFilenames = rawContext.assetFilenames.slice();
137
- const loaders = rawContext.currentLoader.split("$").map(loader => {
138
- const splittedRequest = (0, identifier_1.parseResourceWithoutFragment)(loader);
139
- const obj = {};
140
- obj.loader = obj.path = splittedRequest.path;
141
- obj.query = splittedRequest.query;
142
- obj.fragment = splittedRequest.fragment;
143
- const type = /\.mjs$/i.test(splittedRequest.path) ? "module" : "commonjs";
144
- obj.type = type;
145
- obj.options = splittedRequest.query
146
- ? splittedRequest.query.slice(1)
147
- : undefined;
148
- if (typeof obj.options === "string" && obj.options[0] === "?") {
149
- const ident = obj.options.slice(1);
150
- if (ident === "[[missing ident]]") {
151
- throw new Error("No ident is provided by referenced loader. " +
152
- "When using a function for Rule.use in config you need to " +
153
- "provide an 'ident' property for referenced loader options.");
154
- }
155
- obj.options = compiler.__internal__ruleSet.references.get(ident);
156
- if (obj.options === undefined) {
157
- throw new Error(`Invalid ident("${ident}") is provided by referenced loader`);
158
- }
159
- obj.ident = ident;
160
- }
161
- return createLoaderObject(obj, compiler);
292
+ const fileDependencies = context.fileDependencies;
293
+ const contextDependencies = context.contextDependencies;
294
+ const missingDependencies = context.missingDependencies;
295
+ const buildDependencies = context.buildDependencies;
296
+ const assetFilenames = context.assetFilenames;
297
+ /// Construct `loaderContext`
298
+ const loaderContext = {};
299
+ loaderContext.loaders = context.loaderItems.map(item => {
300
+ return LoaderObject.__from_binding(item, compiler);
162
301
  });
163
- loaderContext.__internal__context = rawContext;
164
- loaderContext.hot = rawContext.hot;
302
+ loaderContext.hot = context.hot;
165
303
  loaderContext.context = contextDirectory;
166
- loaderContext.loaderIndex = 0;
167
- loaderContext.loaders = loaders;
168
304
  loaderContext.resourcePath = resourcePath;
169
305
  loaderContext.resourceQuery = resourceQuery;
170
306
  loaderContext.resourceFragment = resourceFragment;
171
- loaderContext.cacheable = function (flag) {
172
- if (flag === false) {
173
- cacheable = false;
174
- }
175
- };
176
307
  loaderContext.dependency = loaderContext.addDependency =
177
308
  function addDependency(file) {
178
309
  fileDependencies.push(file);
@@ -183,6 +314,9 @@ async function runLoaders(compiler, rawContext) {
183
314
  loaderContext.addMissingDependency = function addMissingDependency(context) {
184
315
  missingDependencies.push(context);
185
316
  };
317
+ loaderContext.addBuildDependency = function addBuildDependency(file) {
318
+ buildDependencies.push(file);
319
+ };
186
320
  loaderContext.getDependencies = function getDependencies() {
187
321
  return fileDependencies.slice();
188
322
  };
@@ -196,14 +330,14 @@ async function runLoaders(compiler, rawContext) {
196
330
  fileDependencies.length = 0;
197
331
  contextDependencies.length = 0;
198
332
  missingDependencies.length = 0;
199
- cacheable = true;
333
+ context.cacheable = true;
200
334
  };
201
335
  loaderContext.importModule = function importModule(request, options, callback) {
202
336
  if (!callback) {
203
337
  return new Promise((resolve, reject) => {
204
338
  compiler
205
339
  ._lastCompilation.__internal_getInner()
206
- .importModule(request, options.publicPath, options.baseUri, rawContext._module.moduleIdentifier, loaderContext.context, (err, res) => {
340
+ .importModule(request, options.publicPath, options.baseUri, context._module.moduleIdentifier, loaderContext.context, (err, res) => {
207
341
  if (err)
208
342
  reject(err);
209
343
  else {
@@ -230,7 +364,7 @@ async function runLoaders(compiler, rawContext) {
230
364
  }
231
365
  return compiler
232
366
  ._lastCompilation.__internal_getInner()
233
- .importModule(request, options.publicPath, options.baseUri, rawContext._module.moduleIdentifier, loaderContext.context, (err, res) => {
367
+ .importModule(request, options.publicPath, options.baseUri, context._module.moduleIdentifier, loaderContext.context, (err, res) => {
234
368
  if (err) {
235
369
  callback(err, undefined);
236
370
  }
@@ -335,12 +469,6 @@ async function runLoaders(compiler, rawContext) {
335
469
  : entry.query;
336
470
  }
337
471
  });
338
- Object.defineProperty(loaderContext, "data", {
339
- enumerable: true,
340
- get: function () {
341
- return loaderContext.loaders[loaderContext.loaderIndex].data;
342
- }
343
- });
344
472
  loaderContext.version = 2;
345
473
  loaderContext.sourceMap = compiler.options.devtool
346
474
  ? (0, adapterRuleUse_1.isUseSourceMap)(compiler.options.devtool)
@@ -399,18 +527,14 @@ async function runLoaders(compiler, rawContext) {
399
527
  loaderContext.rootContext = compiler.context;
400
528
  loaderContext.emitError = function emitError(error) {
401
529
  const title = "Module Error";
402
- const message = error instanceof Error ? (0, util_1.concatErrorMsgAndStack)(error) : error;
403
- compiler._lastCompilation.__internal__pushDiagnostic("error", title, `${message}\n(from: ${(0, util_1.stringifyLoaderObject)(loaderContext.loaders[loaderContext.loaderIndex])})`);
530
+ const message = error instanceof Error ? (0, util_2.concatErrorMsgAndStack)(error) : error;
531
+ compiler._lastCompilation.__internal__pushDiagnostic("error", title, `${message}\n(from: ${(0, util_2.stringifyLoaderObject)(loaderContext.loaders[loaderContext.loaderIndex])})`);
404
532
  };
405
533
  loaderContext.emitWarning = function emitWarning(warning) {
406
534
  const title = "Module Warning";
407
- const message = warning instanceof Error ? (0, util_1.concatErrorMsgAndStack)(warning) : warning;
408
- compiler._lastCompilation.__internal__pushDiagnostic("warning", title, `${message}\n(from: ${(0, util_1.stringifyLoaderObject)(loaderContext.loaders[loaderContext.loaderIndex])})`);
535
+ const message = warning instanceof Error ? (0, util_2.concatErrorMsgAndStack)(warning) : warning;
536
+ compiler._lastCompilation.__internal__pushDiagnostic("warning", title, `${message}\n(from: ${(0, util_2.stringifyLoaderObject)(loaderContext.loaders[loaderContext.loaderIndex])})`);
409
537
  };
410
- loaderContext.__internal__pushNativeDiagnostics =
411
- function __internal__pushNativeDiagnostics(diagnostics) {
412
- compiler._lastCompilation.__internal__pushNativeDiagnostics(diagnostics);
413
- };
414
538
  loaderContext.emitFile = function emitFile(name, content, sourceMap, assetInfo) {
415
539
  let source;
416
540
  if (sourceMap) {
@@ -455,38 +579,9 @@ async function runLoaders(compiler, rawContext) {
455
579
  return (0, createHash_1.createHash)(type || compiler._lastCompilation.outputOptions.hashFunction);
456
580
  }
457
581
  };
458
- loaderContext.addBuildDependency = function addBuildDependency(file) {
459
- buildDependencies.push(file);
460
- };
461
- loaderContext.addDependency = function addDependency(file) {
462
- fileDependencies.push(file);
463
- };
464
- loaderContext.dependency = function dependency(file) {
465
- fileDependencies.push(file);
466
- };
467
- loaderContext.addContextDependency = function addContextDependency(context) {
468
- contextDependencies.push(context);
469
- };
470
- loaderContext.addMissingDependency = function addMissingDependency(missing) {
471
- missingDependencies.push(missing);
472
- };
473
- loaderContext.clearDependencies = function clearDependencies() {
474
- fileDependencies.length = 0;
475
- contextDependencies.length = 0;
476
- missingDependencies.length = 0;
477
- };
478
- loaderContext.getDependencies = function getDependencies() {
479
- return fileDependencies.slice();
480
- };
481
- loaderContext.getContextDependencies = function getContextDependencies() {
482
- return contextDependencies.slice();
483
- };
484
- loaderContext.getMissingDependencies = function getMissingDependencies() {
485
- return missingDependencies.slice();
486
- };
487
582
  loaderContext._compiler = compiler;
488
583
  loaderContext._compilation = compiler._lastCompilation;
489
- loaderContext._module = Module_1.Module.__from_binding(rawContext._module, compiler._lastCompilation);
584
+ loaderContext._module = Module_1.Module.__from_binding(context._module, compiler._lastCompilation);
490
585
  loaderContext.getOptions = function () {
491
586
  const loader = getCurrentLoader(loaderContext);
492
587
  let options = loader?.options;
@@ -501,7 +596,7 @@ async function runLoaders(compiler, rawContext) {
501
596
  }
502
597
  }
503
598
  else {
504
- options = querystring.parse(options);
599
+ options = node_querystring_1.default.parse(options);
505
600
  }
506
601
  }
507
602
  if (options === null || options === undefined) {
@@ -519,60 +614,89 @@ async function runLoaders(compiler, rawContext) {
519
614
  throw Error("Too many nested child compiler, exceeded max limitation 1000");
520
615
  }
521
616
  }
522
- return new Promise((resolve, reject) => {
523
- if (loaderContext.__internal__context.isPitching) {
524
- iteratePitchingLoaders(loaderContext, [], (err, result) => {
525
- if (err) {
526
- return reject(err);
617
+ /// Sync with `context`
618
+ Object.defineProperty(loaderContext, "loaderIndex", {
619
+ enumerable: true,
620
+ get: () => context.loaderIndex,
621
+ set: loaderIndex => (context.loaderIndex = loaderIndex)
622
+ });
623
+ Object.defineProperty(loaderContext, "cacheable", {
624
+ enumerable: true,
625
+ get: () => (cacheable) => {
626
+ if (cacheable === false) {
627
+ context.cacheable = cacheable;
628
+ }
629
+ }
630
+ });
631
+ Object.defineProperty(loaderContext, "data", {
632
+ enumerable: true,
633
+ get: () => loaderContext.loaders[loaderContext.loaderIndex].data,
634
+ set: data => (loaderContext.loaders[loaderContext.loaderIndex].data = data)
635
+ });
636
+ switch (loaderState) {
637
+ case binding_1.JsLoaderState.Pitching: {
638
+ while (loaderContext.loaderIndex < loaderContext.loaders.length) {
639
+ const currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
640
+ if (currentLoaderObject.shouldYield())
641
+ break;
642
+ if (currentLoaderObject.pitchExecuted) {
643
+ loaderContext.loaderIndex += 1;
644
+ continue;
527
645
  }
528
- const [content, sourceMap, additionalData] = result;
529
- resolve({
530
- content: (0, util_1.isNil)(content) ? undefined : (0, util_1.toBuffer)(content),
531
- sourceMap: (0, util_1.serializeObject)(sourceMap),
532
- additionalData,
533
- buildDependencies,
534
- cacheable,
535
- fileDependencies,
536
- contextDependencies,
537
- missingDependencies,
538
- assetFilenames,
539
- isPitching: loaderContext.__internal__context.isPitching,
540
- additionalDataExternal: loaderContext.__internal__context.additionalDataExternal
646
+ await loadLoaderAsync(currentLoaderObject);
647
+ const fn = currentLoaderObject.pitch;
648
+ currentLoaderObject.pitchExecuted = true;
649
+ if (!fn)
650
+ continue;
651
+ const args = (await runSyncOrAsync(fn, loaderContext, [
652
+ loaderContext.remainingRequest,
653
+ loaderContext.previousRequest,
654
+ currentLoaderObject.data
655
+ ])) || [];
656
+ const hasArg = args.some(function (value) {
657
+ return value !== undefined;
541
658
  });
542
- });
659
+ if (hasArg) {
660
+ const [content, sourceMap, additionalData] = args;
661
+ context.content = (0, util_2.isNil)(content) ? null : (0, util_2.toBuffer)(content);
662
+ context.sourceMap = (0, util_2.serializeObject)(sourceMap);
663
+ context.additionalData = additionalData;
664
+ break;
665
+ }
666
+ }
667
+ break;
543
668
  }
544
- else {
545
- // normal
546
- loaderContext.loaderIndex = loaderContext.loaders.length - 1;
547
- iterateNormalLoaders(loaderContext, [
548
- rawContext.content,
549
- (0, util_1.isNil)(rawContext.sourceMap)
550
- ? undefined
551
- : (0, util_1.toObject)(rawContext.sourceMap),
552
- (0, util_1.isNil)(rawContext.additionalData)
553
- ? undefined
554
- : rawContext.additionalData
555
- ], (err, result) => {
556
- if (err) {
557
- return reject(err);
669
+ case binding_1.JsLoaderState.Normal: {
670
+ let content = context.content;
671
+ let sourceMap = JsSourceMap.__from_binding(context.sourceMap);
672
+ let additionalData = context.additionalData;
673
+ while (loaderContext.loaderIndex >= 0) {
674
+ const currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
675
+ if (currentLoaderObject.shouldYield())
676
+ break;
677
+ if (currentLoaderObject.normalExecuted) {
678
+ loaderContext.loaderIndex--;
679
+ continue;
558
680
  }
559
- const [content, sourceMap, additionalData] = result;
560
- resolve({
561
- content: (0, util_1.isNil)(content) ? undefined : (0, util_1.toBuffer)(content),
562
- sourceMap: (0, util_1.serializeObject)(sourceMap),
563
- additionalData,
564
- buildDependencies,
565
- cacheable,
566
- fileDependencies,
567
- contextDependencies,
568
- missingDependencies,
569
- assetFilenames,
570
- isPitching: loaderContext.__internal__context.isPitching,
571
- additionalDataExternal: loaderContext.__internal__context.additionalDataExternal
572
- });
573
- });
681
+ await loadLoaderAsync(currentLoaderObject);
682
+ const fn = currentLoaderObject.normal;
683
+ currentLoaderObject.normalExecuted = true;
684
+ if (!fn)
685
+ continue;
686
+ let args = [content, sourceMap, additionalData];
687
+ convertArgs(args, !!currentLoaderObject.raw);
688
+ [content, sourceMap, additionalData] =
689
+ (await runSyncOrAsync(fn, loaderContext, args)) || [];
690
+ }
691
+ context.content = (0, util_2.isNil)(content) ? null : (0, util_2.toBuffer)(content);
692
+ context.sourceMap = JsSourceMap.__to_binding(sourceMap);
693
+ context.additionalData = additionalData;
694
+ break;
574
695
  }
575
- });
696
+ default:
697
+ throw new Error(`Unexpected loader runner state: ${loaderState}`);
698
+ }
699
+ return context;
576
700
  }
577
701
  exports.runLoaders = runLoaders;
578
702
  function utf8BufferToString(buf) {
@@ -590,149 +714,13 @@ function convertArgs(args, raw) {
590
714
  else if (raw && typeof args[0] === "string")
591
715
  args[0] = Buffer.from(args[0], "utf-8");
592
716
  }
593
- function runSyncOrAsync(fn, context, args, callback) {
594
- let isSync = true;
595
- let isDone = false;
596
- let isError = false; // internal error
597
- let reportedError = false;
598
- // @ts-expect-error loader-runner leverages `arguments` to achieve the same functionality.
599
- context.async = function async() {
600
- if (isDone) {
601
- if (reportedError)
602
- return; // ignore
603
- throw new Error("async(): The callback was already called.");
604
- }
605
- isSync = false;
606
- return innerCallback;
717
+ const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
718
+ function parsePathQueryFragment(str) {
719
+ const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
720
+ return {
721
+ path: match?.[1].replace(/\u200b(.)/g, "$1") || "",
722
+ query: match?.[2] ? match[2].replace(/\u200b(.)/g, "$1") : "",
723
+ fragment: match?.[3] || ""
607
724
  };
608
- const innerCallback = (context.callback = function () {
609
- if (isDone) {
610
- if (reportedError)
611
- return; // ignore
612
- throw new Error("callback(): The callback was already called.");
613
- }
614
- isDone = true;
615
- isSync = false;
616
- try {
617
- callback.apply(null, arguments);
618
- }
619
- catch (e) {
620
- isError = true;
621
- throw e;
622
- }
623
- });
624
- try {
625
- const result = (function LOADER_EXECUTION() {
626
- return fn.apply(context, args);
627
- })();
628
- if (isSync) {
629
- isDone = true;
630
- if (result === undefined)
631
- return callback();
632
- if (result &&
633
- typeof result === "object" &&
634
- typeof result.then === "function") {
635
- return result.then(function (r) {
636
- callback(null, r);
637
- }, callback);
638
- }
639
- return callback(null, result);
640
- }
641
- }
642
- catch (e) {
643
- if (isError)
644
- throw e;
645
- if (isDone) {
646
- // loader is already "done", so we cannot use the callback function
647
- // for better debugging we print the error on the console
648
- if (e instanceof Error)
649
- console.error(e.stack);
650
- else
651
- console.error(e);
652
- return;
653
- }
654
- isDone = true;
655
- reportedError = true;
656
- callback(e);
657
- }
658
- }
659
- function iteratePitchingLoaders(loaderContext, args, callback) {
660
- // Running out of js loaders, so yield back to rust.
661
- // Directly callback as we may still have other loaders on the rust side,
662
- // The difference between rspack loader-runner and webpack loader-runner is
663
- // that we do not run the loaders in the normal stage if pitching is not successful.
664
- if (loaderContext.loaderIndex >= loaderContext.loaders.length)
665
- return callback(null, args);
666
- const currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
667
- // iterate
668
- if (currentLoaderObject.pitchExecuted) {
669
- loaderContext.loaderIndex++;
670
- return iteratePitchingLoaders(loaderContext, args, callback);
671
- }
672
- // load loader module
673
- loadLoader(currentLoaderObject, function (err) {
674
- if (err) {
675
- loaderContext.cacheable(false);
676
- return callback(err);
677
- }
678
- const fn = currentLoaderObject.pitch;
679
- currentLoaderObject.pitchExecuted = true;
680
- if (!fn)
681
- return iteratePitchingLoaders(loaderContext, args, callback);
682
- runSyncOrAsync(fn, loaderContext, [
683
- loaderContext.remainingRequest,
684
- loaderContext.previousRequest,
685
- (currentLoaderObject.data = {})
686
- ], function (err) {
687
- if (err)
688
- return callback(err);
689
- const args = Array.prototype.slice.call(arguments, 1);
690
- // Determine whether to continue the pitching process based on
691
- // argument values (as opposed to argument presence) in order
692
- // to support synchronous and asynchronous usages.
693
- const hasArg = args.some(function (value) {
694
- return value !== undefined;
695
- });
696
- // If a loader pitched successfully,
697
- // then It should execute normal loaders too.
698
- if (hasArg) {
699
- // Instruct rust side to execute loaders in backwards.
700
- loaderContext.__internal__context.isPitching = false;
701
- loaderContext.loaderIndex--;
702
- iterateNormalLoaders(loaderContext, args, callback);
703
- }
704
- else {
705
- iteratePitchingLoaders(loaderContext, args, callback);
706
- }
707
- });
708
- });
709
- }
710
- function iterateNormalLoaders(loaderContext, args, callback) {
711
- // JS loaders ends
712
- if (loaderContext.loaderIndex < 0)
713
- return callback(null, args);
714
- const currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
715
- // iterate
716
- if (currentLoaderObject.normalExecuted) {
717
- loaderContext.loaderIndex--;
718
- return iterateNormalLoaders(loaderContext, args, callback);
719
- }
720
- loadLoader(currentLoaderObject, function (err) {
721
- if (err) {
722
- loaderContext.cacheable(false);
723
- return callback(err);
724
- }
725
- const fn = currentLoaderObject.normal;
726
- currentLoaderObject.normalExecuted = true;
727
- if (!fn) {
728
- return iterateNormalLoaders(loaderContext, args, callback);
729
- }
730
- convertArgs(args, !!currentLoaderObject.raw);
731
- runSyncOrAsync(fn, loaderContext, args, function (err) {
732
- if (err)
733
- return callback(err);
734
- const args = Array.prototype.slice.call(arguments, 1);
735
- iterateNormalLoaders(loaderContext, args, callback);
736
- });
737
- });
738
725
  }
726
+ exports.parsePathQueryFragment = parsePathQueryFragment;