@rspack/core 1.3.0 → 1.3.2

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/worker.js ADDED
@@ -0,0 +1,1904 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
+
36
+ // src/lib/WebpackError.ts
37
+ var import_node_util, WebpackError, WebpackError_default;
38
+ var init_WebpackError = __esm({
39
+ "src/lib/WebpackError.ts"() {
40
+ "use strict";
41
+ import_node_util = require("util");
42
+ WebpackError = class extends Error {
43
+ [import_node_util.inspect.custom]() {
44
+ return this.stack + (this.details ? `
45
+ ${this.details}` : "");
46
+ }
47
+ };
48
+ WebpackError_default = WebpackError;
49
+ }
50
+ });
51
+
52
+ // src/lib/AbstractMethodError.ts
53
+ function createMessage(method) {
54
+ return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`;
55
+ }
56
+ var CURRENT_METHOD_REGEXP, Message, AbstractMethodError, AbstractMethodError_default;
57
+ var init_AbstractMethodError = __esm({
58
+ "src/lib/AbstractMethodError.ts"() {
59
+ "use strict";
60
+ init_WebpackError();
61
+ CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
62
+ Message = class extends Error {
63
+ constructor() {
64
+ super();
65
+ this.stack = void 0;
66
+ Error.captureStackTrace(this);
67
+ const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP);
68
+ this.message = (match == null ? void 0 : match[1]) ? createMessage(match[1]) : createMessage();
69
+ }
70
+ };
71
+ AbstractMethodError = class extends WebpackError_default {
72
+ constructor() {
73
+ super(new Message().message);
74
+ this.name = "AbstractMethodError";
75
+ }
76
+ };
77
+ AbstractMethodError_default = AbstractMethodError;
78
+ }
79
+ });
80
+
81
+ // src/util/hash/index.ts
82
+ var Hash;
83
+ var init_hash = __esm({
84
+ "src/util/hash/index.ts"() {
85
+ "use strict";
86
+ init_AbstractMethodError();
87
+ Hash = class {
88
+ /* istanbul ignore next */
89
+ /**
90
+ * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
91
+ * @abstract
92
+ * @param data data
93
+ * @param inputEncoding data encoding
94
+ * @returns updated hash
95
+ */
96
+ update(data, inputEncoding) {
97
+ throw new AbstractMethodError_default();
98
+ }
99
+ /* istanbul ignore next */
100
+ /**
101
+ * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
102
+ * @abstract
103
+ * @param encoding encoding of the return value
104
+ * @returns digest
105
+ */
106
+ digest(encoding) {
107
+ throw new AbstractMethodError_default();
108
+ }
109
+ };
110
+ }
111
+ });
112
+
113
+ // src/util/hash/wasm-hash.ts
114
+ var MAX_SHORT_STRING, WasmHash, create, wasm_hash_default;
115
+ var init_wasm_hash = __esm({
116
+ "src/util/hash/wasm-hash.ts"() {
117
+ "use strict";
118
+ MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & ~3;
119
+ WasmHash = class {
120
+ /**
121
+ * @param instance wasm instance
122
+ * @param instancesPool pool of instances
123
+ * @param chunkSize size of data chunks passed to wasm
124
+ * @param digestSize size of digest returned by wasm
125
+ */
126
+ constructor(instance, instancesPool, chunkSize, digestSize) {
127
+ const exports2 = instance.exports;
128
+ exports2.init();
129
+ this.exports = exports2;
130
+ this.mem = Buffer.from(exports2.memory.buffer, 0, 65536);
131
+ this.buffered = 0;
132
+ this.instancesPool = instancesPool;
133
+ this.chunkSize = chunkSize;
134
+ this.digestSize = digestSize;
135
+ }
136
+ reset() {
137
+ this.buffered = 0;
138
+ this.exports.init();
139
+ }
140
+ /**
141
+ * @param data data
142
+ * @param encoding encoding
143
+ * @returns itself
144
+ */
145
+ update(data, encoding) {
146
+ if (typeof data === "string") {
147
+ let normalizedData = data;
148
+ while (normalizedData.length > MAX_SHORT_STRING) {
149
+ this._updateWithShortString(
150
+ normalizedData.slice(0, MAX_SHORT_STRING),
151
+ encoding
152
+ );
153
+ normalizedData = normalizedData.slice(MAX_SHORT_STRING);
154
+ }
155
+ this._updateWithShortString(normalizedData, encoding);
156
+ return this;
157
+ }
158
+ this._updateWithBuffer(data);
159
+ return this;
160
+ }
161
+ /**
162
+ * @param {string} data data
163
+ * @param {BufferEncoding=} encoding encoding
164
+ * @returns {void}
165
+ */
166
+ _updateWithShortString(data, encoding) {
167
+ const { exports: exports2, buffered, mem, chunkSize } = this;
168
+ let endPos;
169
+ if (data.length < 70) {
170
+ if (!encoding || encoding === "utf-8" || encoding === "utf8") {
171
+ endPos = buffered;
172
+ for (let i = 0; i < data.length; i++) {
173
+ const cc = data.charCodeAt(i);
174
+ if (cc < 128) mem[endPos++] = cc;
175
+ else if (cc < 2048) {
176
+ mem[endPos] = cc >> 6 | 192;
177
+ mem[endPos + 1] = cc & 63 | 128;
178
+ endPos += 2;
179
+ } else {
180
+ endPos += mem.write(data.slice(i), endPos, encoding);
181
+ break;
182
+ }
183
+ }
184
+ } else if (encoding === "latin1") {
185
+ endPos = buffered;
186
+ for (let i = 0; i < data.length; i++) {
187
+ const cc = data.charCodeAt(i);
188
+ mem[endPos++] = cc;
189
+ }
190
+ } else {
191
+ endPos = buffered + mem.write(data, buffered, encoding);
192
+ }
193
+ } else {
194
+ endPos = buffered + mem.write(data, buffered, encoding);
195
+ }
196
+ if (endPos < chunkSize) {
197
+ this.buffered = endPos;
198
+ } else {
199
+ const l = endPos & ~(this.chunkSize - 1);
200
+ exports2.update(l);
201
+ const newBuffered = endPos - l;
202
+ this.buffered = newBuffered;
203
+ if (newBuffered > 0) mem.copyWithin(0, l, endPos);
204
+ }
205
+ }
206
+ /**
207
+ * @param data data
208
+ * @returns
209
+ */
210
+ _updateWithBuffer(data) {
211
+ const { exports: exports2, buffered, mem } = this;
212
+ const length = data.length;
213
+ if (buffered + length < this.chunkSize) {
214
+ data.copy(mem, buffered, 0, length);
215
+ this.buffered += length;
216
+ } else {
217
+ const l = buffered + length & ~(this.chunkSize - 1);
218
+ if (l > 65536) {
219
+ let i = 65536 - buffered;
220
+ data.copy(mem, buffered, 0, i);
221
+ exports2.update(65536);
222
+ const stop = l - buffered - 65536;
223
+ while (i < stop) {
224
+ data.copy(mem, 0, i, i + 65536);
225
+ exports2.update(65536);
226
+ i += 65536;
227
+ }
228
+ data.copy(mem, 0, i, l - buffered);
229
+ exports2.update(l - buffered - i);
230
+ } else {
231
+ data.copy(mem, buffered, 0, l - buffered);
232
+ exports2.update(l);
233
+ }
234
+ const newBuffered = length + buffered - l;
235
+ this.buffered = newBuffered;
236
+ if (newBuffered > 0) data.copy(mem, 0, length - newBuffered, length);
237
+ }
238
+ }
239
+ digest(type) {
240
+ const { exports: exports2, buffered, mem, digestSize } = this;
241
+ exports2.final(buffered);
242
+ this.instancesPool.push(this);
243
+ const hex = mem.toString("latin1", 0, digestSize);
244
+ if (type === "hex") return hex;
245
+ if (type === "binary" || !type) return Buffer.from(hex, "hex");
246
+ return Buffer.from(hex, "hex").toString(type);
247
+ }
248
+ };
249
+ create = (wasmModule, instancesPool, chunkSize, digestSize) => {
250
+ if (instancesPool.length > 0) {
251
+ const old = instancesPool.pop();
252
+ old.reset();
253
+ return old;
254
+ }
255
+ return new WasmHash(
256
+ new WebAssembly.Instance(wasmModule),
257
+ instancesPool,
258
+ chunkSize,
259
+ digestSize
260
+ );
261
+ };
262
+ wasm_hash_default = create;
263
+ }
264
+ });
265
+
266
+ // src/util/hash/BatchedHash.ts
267
+ var BatchedHash;
268
+ var init_BatchedHash = __esm({
269
+ "src/util/hash/BatchedHash.ts"() {
270
+ "use strict";
271
+ init_hash();
272
+ init_wasm_hash();
273
+ BatchedHash = class extends Hash {
274
+ constructor(hash) {
275
+ super();
276
+ this.string = void 0;
277
+ this.encoding = void 0;
278
+ this.hash = hash;
279
+ }
280
+ /**
281
+ * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
282
+ * @param data data
283
+ * @param inputEncoding data encoding
284
+ * @returns updated hash
285
+ */
286
+ update(data, inputEncoding) {
287
+ if (this.string !== void 0) {
288
+ if (typeof data === "string" && inputEncoding === this.encoding && this.string.length + data.length < MAX_SHORT_STRING) {
289
+ this.string += data;
290
+ return this;
291
+ }
292
+ this.hash.update(this.string, this.encoding);
293
+ this.string = void 0;
294
+ }
295
+ if (typeof data === "string") {
296
+ if (data.length < MAX_SHORT_STRING && // base64 encoding is not valid since it may contain padding chars
297
+ (!inputEncoding || !inputEncoding.startsWith("ba"))) {
298
+ this.string = data;
299
+ this.encoding = inputEncoding;
300
+ } else {
301
+ this.hash.update(data, inputEncoding);
302
+ }
303
+ } else {
304
+ this.hash.update(data);
305
+ }
306
+ return this;
307
+ }
308
+ /**
309
+ * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
310
+ * @param encoding encoding of the return value
311
+ * @returns digest
312
+ */
313
+ digest(encoding) {
314
+ if (this.string !== void 0) {
315
+ this.hash.update(this.string, this.encoding);
316
+ }
317
+ return this.hash.digest(encoding);
318
+ }
319
+ };
320
+ }
321
+ });
322
+
323
+ // src/util/hash/md4.ts
324
+ var createMd4, md4_default;
325
+ var init_md4 = __esm({
326
+ "src/util/hash/md4.ts"() {
327
+ "use strict";
328
+ init_wasm_hash();
329
+ md4_default = () => {
330
+ if (!createMd4) {
331
+ const md4 = new WebAssembly.Module(
332
+ Buffer.from(
333
+ // 2156 bytes
334
+ "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",
335
+ "base64"
336
+ )
337
+ );
338
+ createMd4 = wasm_hash_default.bind(null, md4, [], 64, 32);
339
+ }
340
+ return createMd4();
341
+ };
342
+ }
343
+ });
344
+
345
+ // src/util/hash/xxhash64.ts
346
+ var createXxhash64, xxhash64_default;
347
+ var init_xxhash64 = __esm({
348
+ "src/util/hash/xxhash64.ts"() {
349
+ "use strict";
350
+ init_wasm_hash();
351
+ xxhash64_default = () => {
352
+ if (!createXxhash64) {
353
+ const xxhash64 = new WebAssembly.Module(
354
+ Buffer.from(
355
+ // 1170 bytes
356
+ "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",
357
+ "base64"
358
+ )
359
+ );
360
+ createXxhash64 = wasm_hash_default.bind(null, xxhash64, [], 32, 16);
361
+ }
362
+ return createXxhash64();
363
+ };
364
+ }
365
+ });
366
+
367
+ // src/util/createHash.ts
368
+ var createHash_exports = {};
369
+ __export(createHash_exports, {
370
+ createHash: () => createHash
371
+ });
372
+ var import_node_crypto, BULK_SIZE, digestCaches, BulkUpdateDecorator, DebugHash, createHash;
373
+ var init_createHash = __esm({
374
+ "src/util/createHash.ts"() {
375
+ "use strict";
376
+ import_node_crypto = __toESM(require("crypto"));
377
+ init_hash();
378
+ init_BatchedHash();
379
+ init_md4();
380
+ init_xxhash64();
381
+ BULK_SIZE = 2e3;
382
+ digestCaches = {};
383
+ BulkUpdateDecorator = class extends Hash {
384
+ /**
385
+ * @param hashOrFactory function to create a hash
386
+ * @param hashKey key for caching
387
+ */
388
+ constructor(hashOrFactory, hashKey) {
389
+ super();
390
+ this.hashKey = hashKey;
391
+ if (typeof hashOrFactory === "function") {
392
+ this.hashFactory = hashOrFactory;
393
+ this.hash = void 0;
394
+ } else {
395
+ this.hashFactory = void 0;
396
+ this.hash = hashOrFactory;
397
+ }
398
+ this.buffer = "";
399
+ }
400
+ /**
401
+ * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
402
+ * @param data data
403
+ * @param inputEncoding data encoding
404
+ * @returns updated hash
405
+ */
406
+ update(data, inputEncoding) {
407
+ if (inputEncoding !== void 0 || typeof data !== "string" || data.length > BULK_SIZE) {
408
+ if (this.hash === void 0) this.hash = this.hashFactory();
409
+ if (this.buffer.length > 0) {
410
+ this.hash.update(this.buffer);
411
+ this.buffer = "";
412
+ }
413
+ this.hash.update(data, inputEncoding);
414
+ } else {
415
+ this.buffer += data;
416
+ if (this.buffer.length > BULK_SIZE) {
417
+ if (this.hash === void 0) this.hash = this.hashFactory();
418
+ this.hash.update(this.buffer);
419
+ this.buffer = "";
420
+ }
421
+ }
422
+ return this;
423
+ }
424
+ /**
425
+ * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
426
+ * @param encoding encoding of the return value
427
+ * @returns digest
428
+ */
429
+ digest(encoding) {
430
+ let digestCache;
431
+ const buffer = this.buffer;
432
+ if (this.hash === void 0) {
433
+ const cacheKey = `${this.hashKey}-${encoding}`;
434
+ digestCache = digestCaches[cacheKey];
435
+ if (digestCache === void 0) {
436
+ digestCache = digestCaches[cacheKey] = /* @__PURE__ */ new Map();
437
+ }
438
+ const cacheEntry = digestCache.get(buffer);
439
+ if (cacheEntry !== void 0) return cacheEntry;
440
+ this.hash = this.hashFactory();
441
+ }
442
+ if (buffer.length > 0) {
443
+ this.hash.update(buffer);
444
+ }
445
+ const digestResult = this.hash.digest(encoding);
446
+ const result = typeof digestResult === "string" ? digestResult : digestResult.toString();
447
+ if (digestCache !== void 0) {
448
+ digestCache.set(buffer, result);
449
+ }
450
+ return result;
451
+ }
452
+ };
453
+ DebugHash = class extends Hash {
454
+ constructor() {
455
+ super();
456
+ this.string = "";
457
+ }
458
+ /**
459
+ * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
460
+ * @param data data
461
+ * @param _inputEncoding data encoding
462
+ * @returns updated hash
463
+ */
464
+ update(data, _inputEncoding) {
465
+ var _a;
466
+ let normalizedData;
467
+ if (typeof data !== "string") {
468
+ normalizedData = data.toString("utf-8");
469
+ } else {
470
+ normalizedData = data;
471
+ }
472
+ if (normalizedData.startsWith("debug-digest-")) {
473
+ normalizedData = Buffer.from(
474
+ normalizedData.slice("debug-digest-".length),
475
+ "hex"
476
+ ).toString();
477
+ }
478
+ this.string += `[${normalizedData}](${(_a = new Error().stack) == null ? void 0 : _a.split("\n", 3)[2]})
479
+ `;
480
+ return this;
481
+ }
482
+ /**
483
+ * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
484
+ * @param encoding encoding of the return value
485
+ * @returns digest
486
+ */
487
+ digest(encoding) {
488
+ return `debug-digest-${Buffer.from(this.string).toString(encoding || "hex")}`;
489
+ }
490
+ };
491
+ createHash = (algorithm) => {
492
+ if (typeof algorithm === "function") {
493
+ return new BulkUpdateDecorator(() => new algorithm());
494
+ }
495
+ switch (algorithm) {
496
+ // TODO add non-cryptographic algorithm here
497
+ case "debug":
498
+ return new DebugHash();
499
+ case "xxhash64":
500
+ return new BatchedHash(xxhash64_default());
501
+ case "md4":
502
+ return new BatchedHash(md4_default());
503
+ case "native-md4":
504
+ return new BulkUpdateDecorator(() => import_node_crypto.default.createHash("md4"), "md4");
505
+ default:
506
+ return new BulkUpdateDecorator(
507
+ () => import_node_crypto.default.createHash(algorithm),
508
+ algorithm
509
+ );
510
+ }
511
+ };
512
+ }
513
+ });
514
+
515
+ // src/util/cleverMerge.ts
516
+ var cleverMerge_exports = {};
517
+ __export(cleverMerge_exports, {
518
+ DELETE: () => DELETE,
519
+ cachedCleverMerge: () => cachedCleverMerge,
520
+ cachedSetProperty: () => cachedSetProperty,
521
+ cleverMerge: () => cleverMerge,
522
+ removeOperations: () => removeOperations,
523
+ resolveByProperty: () => resolveByProperty
524
+ });
525
+ function isPropertyInObject(obj, property) {
526
+ return typeof obj === "object" && obj !== null && property in obj;
527
+ }
528
+ var DYNAMIC_INFO, mergeCache, setPropertyCache, DELETE, cachedCleverMerge, cachedSetProperty, parseCache, cachedParseObject, parseObject, serializeObject, VALUE_TYPE_UNDEFINED, VALUE_TYPE_ATOM, VALUE_TYPE_ARRAY_EXTEND, VALUE_TYPE_OBJECT, VALUE_TYPE_DELETE, getValueType, cleverMerge, _cleverMerge, mergeEntries, getFromByValues, mergeSingleValue, removeOperations, resolveByProperty;
529
+ var init_cleverMerge = __esm({
530
+ "src/util/cleverMerge.ts"() {
531
+ "use strict";
532
+ DYNAMIC_INFO = Symbol("cleverMerge dynamic info");
533
+ mergeCache = /* @__PURE__ */ new WeakMap();
534
+ setPropertyCache = /* @__PURE__ */ new WeakMap();
535
+ DELETE = Symbol("DELETE");
536
+ cachedCleverMerge = (first, second) => {
537
+ if (second === void 0) return first;
538
+ if (first === void 0) return second;
539
+ if (typeof second !== "object" || second === null) return second;
540
+ if (typeof first !== "object" || first === null) return first;
541
+ let innerCache = mergeCache.get(first);
542
+ if (innerCache === void 0) {
543
+ innerCache = /* @__PURE__ */ new WeakMap();
544
+ mergeCache.set(first, innerCache);
545
+ }
546
+ const prevMerge = innerCache.get(second);
547
+ if (prevMerge !== void 0) return prevMerge;
548
+ const newMerge = _cleverMerge(first, second, true);
549
+ innerCache.set(second, newMerge);
550
+ return newMerge;
551
+ };
552
+ cachedSetProperty = (obj, property, value) => {
553
+ let mapByProperty = setPropertyCache.get(obj);
554
+ if (mapByProperty === void 0) {
555
+ mapByProperty = /* @__PURE__ */ new Map();
556
+ setPropertyCache.set(obj, mapByProperty);
557
+ }
558
+ let mapByValue = mapByProperty.get(property);
559
+ if (mapByValue === void 0) {
560
+ mapByValue = /* @__PURE__ */ new Map();
561
+ mapByProperty.set(property, mapByValue);
562
+ }
563
+ let result = mapByValue.get(value);
564
+ if (result) return result;
565
+ result = {
566
+ ...obj,
567
+ [property]: value
568
+ };
569
+ mapByValue.set(value, result);
570
+ return result;
571
+ };
572
+ parseCache = /* @__PURE__ */ new WeakMap();
573
+ cachedParseObject = (obj) => {
574
+ const entry = parseCache.get(obj);
575
+ if (entry !== void 0) return entry;
576
+ const result = parseObject(obj);
577
+ parseCache.set(obj, result);
578
+ return result;
579
+ };
580
+ parseObject = (obj) => {
581
+ const info = /* @__PURE__ */ new Map();
582
+ let dynamicInfo;
583
+ const getInfo = (p) => {
584
+ const entry = info.get(p);
585
+ if (entry !== void 0) return entry;
586
+ const newEntry = {
587
+ base: void 0,
588
+ byProperty: void 0,
589
+ byValues: /* @__PURE__ */ new Map()
590
+ };
591
+ info.set(p, newEntry);
592
+ return newEntry;
593
+ };
594
+ for (const key of Object.keys(obj)) {
595
+ if (key.startsWith("by")) {
596
+ const byProperty = key;
597
+ const byObj = obj[byProperty];
598
+ if (typeof byObj === "object") {
599
+ for (const byValue of Object.keys(byObj)) {
600
+ const obj2 = byObj[byValue];
601
+ for (const key2 of Object.keys(obj2)) {
602
+ const entry = getInfo(key2);
603
+ if (entry.byProperty === void 0) {
604
+ entry.byProperty = byProperty;
605
+ } else if (entry.byProperty !== byProperty) {
606
+ throw new Error(
607
+ `${byProperty} and ${entry.byProperty} for a single property is not supported`
608
+ );
609
+ }
610
+ entry.byValues.set(byValue, obj2[key2]);
611
+ if (byValue === "default") {
612
+ for (const otherByValue of Object.keys(byObj)) {
613
+ if (!entry.byValues.has(otherByValue))
614
+ entry.byValues.set(otherByValue, void 0);
615
+ }
616
+ }
617
+ }
618
+ }
619
+ } else if (typeof byObj === "function") {
620
+ if (dynamicInfo === void 0) {
621
+ dynamicInfo = {
622
+ byProperty: key,
623
+ fn: byObj
624
+ };
625
+ } else {
626
+ throw new Error(
627
+ `${key} and ${dynamicInfo.byProperty} when both are functions is not supported`
628
+ );
629
+ }
630
+ } else {
631
+ const entry = getInfo(key);
632
+ entry.base = obj[key];
633
+ }
634
+ } else {
635
+ const entry = getInfo(key);
636
+ entry.base = obj[key];
637
+ }
638
+ }
639
+ return {
640
+ static: info,
641
+ dynamic: dynamicInfo
642
+ };
643
+ };
644
+ serializeObject = (info, dynamicInfo) => {
645
+ const obj = {};
646
+ for (const entry of info.values()) {
647
+ if (entry.byProperty !== void 0) {
648
+ const byObj = obj[entry.byProperty] = obj[entry.byProperty] || {};
649
+ for (const byValue of entry.byValues.keys()) {
650
+ byObj[byValue] = byObj[byValue] || {};
651
+ }
652
+ }
653
+ }
654
+ for (const [key, entry] of info) {
655
+ if (entry.base !== void 0) {
656
+ obj[key] = entry.base;
657
+ }
658
+ if (entry.byProperty !== void 0) {
659
+ const byObj = obj[entry.byProperty] = obj[entry.byProperty] || {};
660
+ for (const byValue of Object.keys(byObj)) {
661
+ const value = getFromByValues(entry.byValues, byValue);
662
+ if (value !== void 0) byObj[byValue][key] = value;
663
+ }
664
+ }
665
+ }
666
+ if (dynamicInfo !== void 0) {
667
+ obj[dynamicInfo.byProperty] = dynamicInfo.fn;
668
+ }
669
+ return obj;
670
+ };
671
+ VALUE_TYPE_UNDEFINED = 0;
672
+ VALUE_TYPE_ATOM = 1;
673
+ VALUE_TYPE_ARRAY_EXTEND = 2;
674
+ VALUE_TYPE_OBJECT = 3;
675
+ VALUE_TYPE_DELETE = 4;
676
+ getValueType = (value) => {
677
+ if (value === void 0) {
678
+ return VALUE_TYPE_UNDEFINED;
679
+ }
680
+ if (value === DELETE) {
681
+ return VALUE_TYPE_DELETE;
682
+ }
683
+ if (Array.isArray(value)) {
684
+ if (value.lastIndexOf("...") !== -1) return VALUE_TYPE_ARRAY_EXTEND;
685
+ return VALUE_TYPE_ATOM;
686
+ }
687
+ if (typeof value === "object" && value !== null && (!value.constructor || value.constructor === Object)) {
688
+ return VALUE_TYPE_OBJECT;
689
+ }
690
+ return VALUE_TYPE_ATOM;
691
+ };
692
+ cleverMerge = (first, second) => {
693
+ if (second === void 0) return first;
694
+ if (first === void 0) return second;
695
+ if (typeof second !== "object" || second === null) return second;
696
+ if (typeof first !== "object" || first === null) return first;
697
+ return _cleverMerge(first, second, false);
698
+ };
699
+ _cleverMerge = (first, second, internalCaching = false) => {
700
+ const firstObject = internalCaching ? cachedParseObject(first) : parseObject(first);
701
+ const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject;
702
+ let secondObj = second;
703
+ if (firstDynamicInfo !== void 0) {
704
+ let { byProperty, fn } = firstDynamicInfo;
705
+ const fnInfo = fn[DYNAMIC_INFO];
706
+ if (fnInfo) {
707
+ secondObj = internalCaching ? cachedCleverMerge(fnInfo[1], second) : cleverMerge(fnInfo[1], second);
708
+ fn = fnInfo[0];
709
+ }
710
+ const newFn = (...args) => {
711
+ const fnResult = fn(...args);
712
+ return internalCaching ? cachedCleverMerge(fnResult, secondObj) : cleverMerge(fnResult, secondObj);
713
+ };
714
+ newFn[DYNAMIC_INFO] = [fn, secondObj];
715
+ return serializeObject(firstObject.static, { byProperty, fn: newFn });
716
+ }
717
+ const secondObject = internalCaching ? cachedParseObject(second) : parseObject(second);
718
+ const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject;
719
+ const resultInfo = /* @__PURE__ */ new Map();
720
+ for (const [key, firstEntry] of firstInfo) {
721
+ const secondEntry = secondInfo.get(key);
722
+ const entry = secondEntry !== void 0 ? mergeEntries(firstEntry, secondEntry, internalCaching) : firstEntry;
723
+ resultInfo.set(key, entry);
724
+ }
725
+ for (const [key, secondEntry] of secondInfo) {
726
+ if (!firstInfo.has(key)) {
727
+ resultInfo.set(key, secondEntry);
728
+ }
729
+ }
730
+ return serializeObject(resultInfo, secondDynamicInfo);
731
+ };
732
+ mergeEntries = (firstEntry, secondEntry, internalCaching) => {
733
+ switch (getValueType(secondEntry.base)) {
734
+ case VALUE_TYPE_ATOM:
735
+ case VALUE_TYPE_DELETE:
736
+ return secondEntry;
737
+ case VALUE_TYPE_UNDEFINED: {
738
+ if (!firstEntry.byProperty) {
739
+ return {
740
+ base: firstEntry.base,
741
+ byProperty: secondEntry.byProperty,
742
+ byValues: secondEntry.byValues
743
+ };
744
+ }
745
+ if (firstEntry.byProperty !== secondEntry.byProperty) {
746
+ throw new Error(
747
+ `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported`
748
+ );
749
+ }
750
+ const newByValues = new Map(firstEntry.byValues);
751
+ for (const [key, value] of secondEntry.byValues) {
752
+ const firstValue = getFromByValues(firstEntry.byValues, key);
753
+ newByValues.set(
754
+ key,
755
+ mergeSingleValue(firstValue, value, internalCaching)
756
+ );
757
+ }
758
+ return {
759
+ base: firstEntry.base,
760
+ byProperty: firstEntry.byProperty,
761
+ byValues: newByValues
762
+ };
763
+ }
764
+ default: {
765
+ if (!firstEntry.byProperty) {
766
+ return {
767
+ base: mergeSingleValue(
768
+ firstEntry.base,
769
+ secondEntry.base,
770
+ internalCaching
771
+ ),
772
+ byProperty: secondEntry.byProperty,
773
+ byValues: secondEntry.byValues
774
+ };
775
+ }
776
+ let newBase;
777
+ const intermediateByValues = new Map(firstEntry.byValues);
778
+ for (const [key, value] of intermediateByValues) {
779
+ intermediateByValues.set(
780
+ key,
781
+ mergeSingleValue(value, secondEntry.base, internalCaching)
782
+ );
783
+ }
784
+ if (Array.from(firstEntry.byValues.values()).every((value) => {
785
+ const type = getValueType(value);
786
+ return type === VALUE_TYPE_ATOM || type === VALUE_TYPE_DELETE;
787
+ })) {
788
+ newBase = mergeSingleValue(
789
+ firstEntry.base,
790
+ secondEntry.base,
791
+ internalCaching
792
+ );
793
+ } else {
794
+ newBase = firstEntry.base;
795
+ if (!intermediateByValues.has("default"))
796
+ intermediateByValues.set("default", secondEntry.base);
797
+ }
798
+ if (!secondEntry.byProperty) {
799
+ return {
800
+ base: newBase,
801
+ byProperty: firstEntry.byProperty,
802
+ byValues: intermediateByValues
803
+ };
804
+ }
805
+ if (firstEntry.byProperty !== secondEntry.byProperty) {
806
+ throw new Error(
807
+ `${firstEntry.byProperty} and ${secondEntry.byProperty} for a single property is not supported`
808
+ );
809
+ }
810
+ const newByValues = new Map(intermediateByValues);
811
+ for (const [key, value] of secondEntry.byValues) {
812
+ const firstValue = getFromByValues(intermediateByValues, key);
813
+ newByValues.set(
814
+ key,
815
+ mergeSingleValue(firstValue, value, internalCaching)
816
+ );
817
+ }
818
+ return {
819
+ base: newBase,
820
+ byProperty: firstEntry.byProperty,
821
+ byValues: newByValues
822
+ };
823
+ }
824
+ }
825
+ };
826
+ getFromByValues = (byValues, key) => {
827
+ if (key !== "default" && byValues.has(key)) {
828
+ return byValues.get(key);
829
+ }
830
+ return byValues.get("default");
831
+ };
832
+ mergeSingleValue = (a, b, internalCaching) => {
833
+ const bType = getValueType(b);
834
+ const aType = getValueType(a);
835
+ switch (bType) {
836
+ case VALUE_TYPE_DELETE:
837
+ case VALUE_TYPE_ATOM:
838
+ return b;
839
+ case VALUE_TYPE_OBJECT: {
840
+ return aType !== VALUE_TYPE_OBJECT ? b : internalCaching ? cachedCleverMerge(a, b) : cleverMerge(a, b);
841
+ }
842
+ case VALUE_TYPE_UNDEFINED:
843
+ return a;
844
+ case VALUE_TYPE_ARRAY_EXTEND:
845
+ switch (aType !== VALUE_TYPE_ATOM ? aType : Array.isArray(a) ? VALUE_TYPE_ARRAY_EXTEND : VALUE_TYPE_OBJECT) {
846
+ case VALUE_TYPE_UNDEFINED:
847
+ return b;
848
+ case VALUE_TYPE_DELETE:
849
+ return b.filter((item) => item !== "...");
850
+ case VALUE_TYPE_ARRAY_EXTEND: {
851
+ const newArray = [];
852
+ for (const item of b) {
853
+ if (item === "...") {
854
+ for (const item2 of a) {
855
+ newArray.push(item2);
856
+ }
857
+ } else {
858
+ newArray.push(item);
859
+ }
860
+ }
861
+ return newArray;
862
+ }
863
+ case VALUE_TYPE_OBJECT:
864
+ return b.map((item) => item === "..." ? a : item);
865
+ default:
866
+ throw new Error("Not implemented");
867
+ }
868
+ default:
869
+ throw new Error("Not implemented");
870
+ }
871
+ };
872
+ removeOperations = (obj) => {
873
+ const newObj = {};
874
+ for (const key of Object.keys(obj)) {
875
+ const value = obj[key];
876
+ const type = getValueType(value);
877
+ switch (type) {
878
+ case VALUE_TYPE_UNDEFINED:
879
+ case VALUE_TYPE_DELETE:
880
+ break;
881
+ case VALUE_TYPE_OBJECT:
882
+ newObj[key] = removeOperations(value);
883
+ break;
884
+ case VALUE_TYPE_ARRAY_EXTEND:
885
+ newObj[key] = value.filter((i) => i !== "...");
886
+ break;
887
+ default:
888
+ newObj[key] = value;
889
+ break;
890
+ }
891
+ }
892
+ return newObj;
893
+ };
894
+ resolveByProperty = (obj, byProperty, ...values) => {
895
+ if (!isPropertyInObject(obj, byProperty)) {
896
+ return obj;
897
+ }
898
+ const { [byProperty]: _byValue, ..._remaining } = obj;
899
+ const remaining = _remaining;
900
+ const byValue = _byValue;
901
+ if (typeof byValue === "object") {
902
+ const key = values[0];
903
+ if (key in byValue) {
904
+ return cachedCleverMerge(remaining, byValue[key]);
905
+ }
906
+ if ("default" in byValue) {
907
+ return cachedCleverMerge(remaining, byValue.default);
908
+ }
909
+ return remaining;
910
+ }
911
+ if (typeof byValue === "function") {
912
+ const result = byValue.apply(null, values);
913
+ return cachedCleverMerge(
914
+ remaining,
915
+ resolveByProperty(result, byProperty, ...values)
916
+ );
917
+ }
918
+ };
919
+ }
920
+ });
921
+
922
+ // ../../node_modules/.pnpm/json-parse-even-better-errors@3.0.2/node_modules/json-parse-even-better-errors/lib/index.js
923
+ var require_lib = __commonJS({
924
+ "../../node_modules/.pnpm/json-parse-even-better-errors@3.0.2/node_modules/json-parse-even-better-errors/lib/index.js"(exports2, module2) {
925
+ "use strict";
926
+ var INDENT = Symbol.for("indent");
927
+ var NEWLINE = Symbol.for("newline");
928
+ var DEFAULT_NEWLINE = "\n";
929
+ var DEFAULT_INDENT = " ";
930
+ var BOM = /^\uFEFF/;
931
+ var FORMAT = /^\s*[{[]((?:\r?\n)+)([\s\t]*)/;
932
+ var EMPTY = /^(?:\{\}|\[\])((?:\r?\n)+)?$/;
933
+ var UNEXPECTED_TOKEN = /^Unexpected token '?(.)'?(,)? /i;
934
+ var hexify = (char) => {
935
+ const h = char.charCodeAt(0).toString(16).toUpperCase();
936
+ return `0x${h.length % 2 ? "0" : ""}${h}`;
937
+ };
938
+ var stripBOM = (txt) => String(txt).replace(BOM, "");
939
+ var makeParsedError = (msg, parsing, position = 0) => ({
940
+ message: `${msg} while parsing ${parsing}`,
941
+ position
942
+ });
943
+ var parseError = (e, txt, context = 20) => {
944
+ let msg = e.message;
945
+ if (!txt) {
946
+ return makeParsedError(msg, "empty string");
947
+ }
948
+ const badTokenMatch = msg.match(UNEXPECTED_TOKEN);
949
+ const badIndexMatch = msg.match(/ position\s+(\d+)/i);
950
+ if (badTokenMatch) {
951
+ msg = msg.replace(
952
+ UNEXPECTED_TOKEN,
953
+ `Unexpected token ${JSON.stringify(badTokenMatch[1])} (${hexify(badTokenMatch[1])})$2 `
954
+ );
955
+ }
956
+ let errIdx;
957
+ if (badIndexMatch) {
958
+ errIdx = +badIndexMatch[1];
959
+ } else if (msg.match(/^Unexpected end of JSON.*/i)) {
960
+ errIdx = txt.length - 1;
961
+ }
962
+ if (errIdx == null) {
963
+ return makeParsedError(msg, `'${txt.slice(0, context * 2)}'`);
964
+ }
965
+ const start = errIdx <= context ? 0 : errIdx - context;
966
+ const end = errIdx + context >= txt.length ? txt.length : errIdx + context;
967
+ const slice = `${start ? "..." : ""}${txt.slice(start, end)}${end === txt.length ? "" : "..."}`;
968
+ return makeParsedError(
969
+ msg,
970
+ `${txt === slice ? "" : "near "}${JSON.stringify(slice)}`,
971
+ errIdx
972
+ );
973
+ };
974
+ var JSONParseError = class extends SyntaxError {
975
+ constructor(er, txt, context, caller) {
976
+ const metadata = parseError(er, txt, context);
977
+ super(metadata.message);
978
+ Object.assign(this, metadata);
979
+ this.code = "EJSONPARSE";
980
+ this.systemError = er;
981
+ Error.captureStackTrace(this, caller || this.constructor);
982
+ }
983
+ get name() {
984
+ return this.constructor.name;
985
+ }
986
+ set name(n) {
987
+ }
988
+ get [Symbol.toStringTag]() {
989
+ return this.constructor.name;
990
+ }
991
+ };
992
+ var parseJson = (txt, reviver) => {
993
+ const result = JSON.parse(txt, reviver);
994
+ if (result && typeof result === "object") {
995
+ const match = txt.match(EMPTY) || txt.match(FORMAT) || [null, "", ""];
996
+ result[NEWLINE] = match[1] ?? DEFAULT_NEWLINE;
997
+ result[INDENT] = match[2] ?? DEFAULT_INDENT;
998
+ }
999
+ return result;
1000
+ };
1001
+ var parseJsonError = (raw, reviver, context) => {
1002
+ const txt = stripBOM(raw);
1003
+ try {
1004
+ return parseJson(txt, reviver);
1005
+ } catch (e) {
1006
+ if (typeof raw !== "string" && !Buffer.isBuffer(raw)) {
1007
+ const msg = Array.isArray(raw) && raw.length === 0 ? "an empty array" : String(raw);
1008
+ throw Object.assign(
1009
+ new TypeError(`Cannot parse ${msg}`),
1010
+ { code: "EJSONPARSE", systemError: e }
1011
+ );
1012
+ }
1013
+ throw new JSONParseError(e, txt, context, parseJsonError);
1014
+ }
1015
+ };
1016
+ module2.exports = parseJsonError;
1017
+ parseJsonError.JSONParseError = JSONParseError;
1018
+ parseJsonError.noExceptions = (raw, reviver) => {
1019
+ try {
1020
+ return parseJson(stripBOM(raw), reviver);
1021
+ } catch {
1022
+ }
1023
+ };
1024
+ }
1025
+ });
1026
+
1027
+ // src/loader-runner/worker.ts
1028
+ var import_node_querystring = __toESM(require("querystring"));
1029
+ var import_node_util3 = require("util");
1030
+ var import_node_worker_threads2 = require("worker_threads");
1031
+ var import_binding = require("@rspack/binding");
1032
+ init_createHash();
1033
+
1034
+ // src/util/identifier.ts
1035
+ var import_node_path = __toESM(require("path"));
1036
+ var WINDOWS_ABS_PATH_REGEXP = /^[a-zA-Z]:[\\/]/;
1037
+ var SEGMENTS_SPLIT_REGEXP = /([|!])/;
1038
+ var WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
1039
+ var relativePathToRequest = (relativePath) => {
1040
+ if (relativePath === "") return "./.";
1041
+ if (relativePath === "..") return "../.";
1042
+ if (relativePath.startsWith("../")) return relativePath;
1043
+ return `./${relativePath}`;
1044
+ };
1045
+ var absoluteToRequest = (context, maybeAbsolutePath) => {
1046
+ if (maybeAbsolutePath[0] === "/") {
1047
+ if (maybeAbsolutePath.length > 1 && maybeAbsolutePath[maybeAbsolutePath.length - 1] === "/") {
1048
+ return maybeAbsolutePath;
1049
+ }
1050
+ const querySplitPos = maybeAbsolutePath.indexOf("?");
1051
+ let resource = querySplitPos === -1 ? maybeAbsolutePath : maybeAbsolutePath.slice(0, querySplitPos);
1052
+ resource = relativePathToRequest(import_node_path.default.posix.relative(context, resource));
1053
+ return querySplitPos === -1 ? resource : resource + maybeAbsolutePath.slice(querySplitPos);
1054
+ }
1055
+ if (WINDOWS_ABS_PATH_REGEXP.test(maybeAbsolutePath)) {
1056
+ const querySplitPos = maybeAbsolutePath.indexOf("?");
1057
+ let resource = querySplitPos === -1 ? maybeAbsolutePath : maybeAbsolutePath.slice(0, querySplitPos);
1058
+ resource = import_node_path.default.win32.relative(context, resource);
1059
+ if (!WINDOWS_ABS_PATH_REGEXP.test(resource)) {
1060
+ resource = relativePathToRequest(
1061
+ resource.replace(WINDOWS_PATH_SEPARATOR_REGEXP, "/")
1062
+ );
1063
+ }
1064
+ return querySplitPos === -1 ? resource : resource + maybeAbsolutePath.slice(querySplitPos);
1065
+ }
1066
+ return maybeAbsolutePath;
1067
+ };
1068
+ var requestToAbsolute = (context, relativePath) => {
1069
+ if (relativePath.startsWith("./") || relativePath.startsWith("../"))
1070
+ return import_node_path.default.join(context, relativePath);
1071
+ return relativePath;
1072
+ };
1073
+ var makeCacheable = (realFn) => {
1074
+ const cache = /* @__PURE__ */ new WeakMap();
1075
+ const getCache = (associatedObjectForCache) => {
1076
+ const entry = cache.get(associatedObjectForCache);
1077
+ if (entry !== void 0) return entry;
1078
+ const map = /* @__PURE__ */ new Map();
1079
+ cache.set(associatedObjectForCache, map);
1080
+ return map;
1081
+ };
1082
+ const fn = (str, associatedObjectForCache) => {
1083
+ if (!associatedObjectForCache) return realFn(str);
1084
+ const cache2 = getCache(associatedObjectForCache);
1085
+ const entry = cache2.get(str);
1086
+ if (entry !== void 0) return entry;
1087
+ const result = realFn(str);
1088
+ cache2.set(str, result);
1089
+ return result;
1090
+ };
1091
+ fn.bindCache = (associatedObjectForCache) => {
1092
+ const cache2 = getCache(associatedObjectForCache);
1093
+ return (str) => {
1094
+ const entry = cache2.get(str);
1095
+ if (entry !== void 0) return entry;
1096
+ const result = realFn(str);
1097
+ cache2.set(str, result);
1098
+ return result;
1099
+ };
1100
+ };
1101
+ return fn;
1102
+ };
1103
+ var makeCacheableWithContext = (fn) => {
1104
+ const cache = /* @__PURE__ */ new WeakMap();
1105
+ const cachedFn = (context, identifier, associatedObjectForCache) => {
1106
+ if (!associatedObjectForCache) return fn(context, identifier);
1107
+ let innerCache = cache.get(
1108
+ associatedObjectForCache
1109
+ );
1110
+ if (innerCache === void 0) {
1111
+ innerCache = /* @__PURE__ */ new Map();
1112
+ cache.set(associatedObjectForCache, innerCache);
1113
+ }
1114
+ let cachedResult;
1115
+ let innerSubCache = innerCache.get(context);
1116
+ if (innerSubCache === void 0) {
1117
+ innerCache.set(context, innerSubCache = /* @__PURE__ */ new Map());
1118
+ } else {
1119
+ cachedResult = innerSubCache.get(identifier);
1120
+ }
1121
+ if (cachedResult !== void 0) {
1122
+ return cachedResult;
1123
+ }
1124
+ const result = fn(context, identifier);
1125
+ innerSubCache.set(identifier, result);
1126
+ return result;
1127
+ };
1128
+ cachedFn.bindCache = (associatedObjectForCache) => {
1129
+ let innerCache;
1130
+ if (associatedObjectForCache) {
1131
+ innerCache = cache.get(associatedObjectForCache);
1132
+ if (innerCache === void 0) {
1133
+ innerCache = /* @__PURE__ */ new Map();
1134
+ cache.set(associatedObjectForCache, innerCache);
1135
+ }
1136
+ } else {
1137
+ innerCache = /* @__PURE__ */ new Map();
1138
+ }
1139
+ const boundFn = (context, identifier) => {
1140
+ let cachedResult;
1141
+ let innerSubCache = innerCache == null ? void 0 : innerCache.get(context);
1142
+ if (innerSubCache === void 0) {
1143
+ innerSubCache = /* @__PURE__ */ new Map();
1144
+ innerCache == null ? void 0 : innerCache.set(context, innerSubCache);
1145
+ } else {
1146
+ cachedResult = innerSubCache.get(identifier);
1147
+ }
1148
+ if (cachedResult !== void 0) {
1149
+ return cachedResult;
1150
+ }
1151
+ const result = fn(context, identifier);
1152
+ innerSubCache.set(identifier, result);
1153
+ return result;
1154
+ };
1155
+ return boundFn;
1156
+ };
1157
+ cachedFn.bindContextCache = (context, associatedObjectForCache) => {
1158
+ let innerSubCache;
1159
+ if (associatedObjectForCache) {
1160
+ let innerCache = cache.get(associatedObjectForCache);
1161
+ if (innerCache === void 0) {
1162
+ innerCache = /* @__PURE__ */ new Map();
1163
+ cache.set(associatedObjectForCache, innerCache);
1164
+ }
1165
+ innerSubCache = innerCache.get(context);
1166
+ if (innerSubCache === void 0) {
1167
+ innerCache.set(context, innerSubCache = /* @__PURE__ */ new Map());
1168
+ }
1169
+ } else {
1170
+ innerSubCache = /* @__PURE__ */ new Map();
1171
+ }
1172
+ const boundFn = (identifier) => {
1173
+ const cachedResult = innerSubCache == null ? void 0 : innerSubCache.get(identifier);
1174
+ if (cachedResult !== void 0) {
1175
+ return cachedResult;
1176
+ }
1177
+ const result = fn(context, identifier);
1178
+ innerSubCache == null ? void 0 : innerSubCache.set(identifier, result);
1179
+ return result;
1180
+ };
1181
+ return boundFn;
1182
+ };
1183
+ return cachedFn;
1184
+ };
1185
+ var _makePathsRelative = (context, identifier) => {
1186
+ return identifier.split(SEGMENTS_SPLIT_REGEXP).map((str) => absoluteToRequest(context, str)).join("");
1187
+ };
1188
+ var makePathsRelative = makeCacheableWithContext(_makePathsRelative);
1189
+ var _makePathsAbsolute = (context, identifier) => {
1190
+ return identifier.split(SEGMENTS_SPLIT_REGEXP).map((str) => requestToAbsolute(context, str)).join("");
1191
+ };
1192
+ var makePathsAbsolute = makeCacheableWithContext(_makePathsAbsolute);
1193
+ var _contextify = (context, request) => {
1194
+ return request.split("!").map((r) => absoluteToRequest(context, r)).join("!");
1195
+ };
1196
+ var contextify = makeCacheableWithContext(_contextify);
1197
+ var _absolutify = (context, request) => {
1198
+ return request.split("!").map((r) => requestToAbsolute(context, r)).join("!");
1199
+ };
1200
+ var absolutify = makeCacheableWithContext(_absolutify);
1201
+ var PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
1202
+ var PATH_QUERY_REGEXP = /^((?:\u200b.|[^?\u200b])*)(\?.*)?$/;
1203
+ var _parseResource = (str) => {
1204
+ const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
1205
+ return {
1206
+ resource: str,
1207
+ path: match[1].replace(/\u200b(.)/g, "$1"),
1208
+ query: match[2] ? match[2].replace(/\u200b(.)/g, "$1") : "",
1209
+ fragment: match[3] || ""
1210
+ };
1211
+ };
1212
+ var parseResource = makeCacheable(_parseResource);
1213
+ var _parseResourceWithoutFragment = (str) => {
1214
+ const match = PATH_QUERY_REGEXP.exec(str);
1215
+ return {
1216
+ resource: str,
1217
+ path: match[1].replace(/\u200b(.)/g, "$1"),
1218
+ query: match[2] ? match[2].replace(/\u200b(.)/g, "$1") : ""
1219
+ };
1220
+ };
1221
+ var parseResourceWithoutFragment = makeCacheable(
1222
+ _parseResourceWithoutFragment
1223
+ );
1224
+
1225
+ // src/util/memoize.ts
1226
+ var memoize = (fn) => {
1227
+ let cache = false;
1228
+ let result;
1229
+ let callback = fn;
1230
+ return () => {
1231
+ if (cache) {
1232
+ return result;
1233
+ }
1234
+ result = callback();
1235
+ cache = true;
1236
+ callback = void 0;
1237
+ return result;
1238
+ };
1239
+ };
1240
+
1241
+ // src/loader-runner/LoaderLoadingError.ts
1242
+ var LoadingLoaderError = class extends Error {
1243
+ constructor(message) {
1244
+ super(message);
1245
+ this.name = "LoaderRunnerError";
1246
+ Error.captureStackTrace(this, this.constructor);
1247
+ }
1248
+ };
1249
+ var LoaderLoadingError_default = LoadingLoaderError;
1250
+
1251
+ // src/loader-runner/loadLoader.ts
1252
+ var url = void 0;
1253
+ function loadLoader(loader, callback) {
1254
+ if (loader.type === "module") {
1255
+ try {
1256
+ if (url === void 0) url = require("url");
1257
+ const loaderUrl = url.pathToFileURL(loader.path);
1258
+ const modulePromise = import(loaderUrl.toString());
1259
+ modulePromise.then((module2) => {
1260
+ handleResult(loader, module2, callback);
1261
+ }, callback);
1262
+ return;
1263
+ } catch (e) {
1264
+ callback(e);
1265
+ }
1266
+ } else {
1267
+ let module2;
1268
+ try {
1269
+ module2 = require(loader.path);
1270
+ } catch (e) {
1271
+ if (e instanceof Error && e.code === "EMFILE") {
1272
+ const retry = loadLoader.bind(null, loader, callback);
1273
+ return void setImmediate(retry);
1274
+ }
1275
+ return callback(e);
1276
+ }
1277
+ return handleResult(loader, module2, callback);
1278
+ }
1279
+ }
1280
+ function handleResult(loader, module2, callback) {
1281
+ if (typeof module2 !== "function" && typeof module2 !== "object") {
1282
+ return callback(
1283
+ new LoaderLoadingError_default(
1284
+ `Module '${loader.path}' is not a loader (export function or es6 module)`
1285
+ )
1286
+ );
1287
+ }
1288
+ loader.normal = typeof module2 === "function" ? module2 : module2.default;
1289
+ loader.pitch = module2.pitch;
1290
+ loader.raw = module2.raw;
1291
+ if (typeof loader.normal !== "function" && typeof loader.pitch !== "function") {
1292
+ return callback(
1293
+ new LoaderLoadingError_default(
1294
+ `Module '${loader.path}' is not a loader (must have normal or pitch function)`
1295
+ )
1296
+ );
1297
+ }
1298
+ callback();
1299
+ }
1300
+
1301
+ // src/loader-runner/service.ts
1302
+ var import_node_path2 = __toESM(require("path"));
1303
+ var import_node_worker_threads = require("worker_threads");
1304
+ function isWorkerResponseMessage(message) {
1305
+ return message.type === "response";
1306
+ }
1307
+ function isWorkerResponseErrorMessage(message) {
1308
+ return message.type === "response-error";
1309
+ }
1310
+ function serializeError(error) {
1311
+ if (error instanceof Error || error && typeof error === "object" && "message" in error) {
1312
+ return {
1313
+ ...error,
1314
+ name: error.name,
1315
+ stack: error.stack,
1316
+ message: error.message
1317
+ };
1318
+ }
1319
+ if (typeof error === "string") {
1320
+ return {
1321
+ name: "Error",
1322
+ message: error
1323
+ };
1324
+ }
1325
+ throw new Error(
1326
+ "Failed to serialize error, only string, Error instances and objects with a message property are supported"
1327
+ );
1328
+ }
1329
+
1330
+ // src/loader-runner/utils.ts
1331
+ var import_node_util2 = require("util");
1332
+ var decoder = new TextDecoder();
1333
+ function utf8BufferToString(buf) {
1334
+ const str = decoder.decode(buf);
1335
+ if (str.charCodeAt(0) === 65279) {
1336
+ return str.slice(1);
1337
+ }
1338
+ return str;
1339
+ }
1340
+ function convertArgs(args, raw) {
1341
+ if (!raw && args[0] instanceof Uint8Array)
1342
+ args[0] = utf8BufferToString(args[0]);
1343
+ else if (raw && typeof args[0] === "string")
1344
+ args[0] = Buffer.from(args[0], "utf-8");
1345
+ if (raw && args[0] instanceof Uint8Array && !Buffer.isBuffer(args[0])) {
1346
+ args[0] = Buffer.from(args[0].buffer);
1347
+ }
1348
+ }
1349
+ var loadLoader2 = (0, import_node_util2.promisify)(loadLoader);
1350
+ var runSyncOrAsync = (0, import_node_util2.promisify)(function runSyncOrAsync2(fn, context, args, callback) {
1351
+ let isSync = true;
1352
+ let isDone = false;
1353
+ let isError = false;
1354
+ let reportedError = false;
1355
+ context.async = function async() {
1356
+ if (isDone) {
1357
+ if (reportedError) return void 0;
1358
+ throw new Error("async(): The callback was already called.");
1359
+ }
1360
+ isSync = false;
1361
+ return innerCallback;
1362
+ };
1363
+ const innerCallback = (err, ...args2) => {
1364
+ if (isDone) {
1365
+ if (reportedError) return;
1366
+ throw new Error("callback(): The callback was already called.");
1367
+ }
1368
+ isDone = true;
1369
+ isSync = false;
1370
+ try {
1371
+ callback(err, args2);
1372
+ } catch (e) {
1373
+ isError = true;
1374
+ throw e;
1375
+ }
1376
+ };
1377
+ context.callback = innerCallback;
1378
+ try {
1379
+ const result = function LOADER_EXECUTION() {
1380
+ return fn.apply(context, args);
1381
+ }();
1382
+ if (isSync) {
1383
+ isDone = true;
1384
+ if (result === void 0) {
1385
+ callback(null, []);
1386
+ return;
1387
+ }
1388
+ if (result && typeof result === "object" && typeof result.then === "function") {
1389
+ result.then((r) => {
1390
+ callback(null, [r]);
1391
+ }, callback);
1392
+ return;
1393
+ }
1394
+ callback(null, [result]);
1395
+ return;
1396
+ }
1397
+ } catch (e) {
1398
+ const err = e;
1399
+ if ("hideStack" in err && err.hideStack) {
1400
+ err.hideStack = "true";
1401
+ }
1402
+ if (isError) throw e;
1403
+ if (isDone) {
1404
+ if (e instanceof Error) console.error(e.stack);
1405
+ else console.error(e);
1406
+ return;
1407
+ }
1408
+ isDone = true;
1409
+ reportedError = true;
1410
+ callback(e, []);
1411
+ }
1412
+ });
1413
+
1414
+ // src/loader-runner/worker.ts
1415
+ var BUILTIN_LOADER_PREFIX = "builtin:";
1416
+ var loadLoaderAsync = (0, import_node_util3.promisify)(loadLoader);
1417
+ function dirname(path3) {
1418
+ if (path3 === "/") return "/";
1419
+ const i = path3.lastIndexOf("/");
1420
+ const j = path3.lastIndexOf("\\");
1421
+ const i2 = path3.indexOf("/");
1422
+ const j2 = path3.indexOf("\\");
1423
+ const idx = i > j ? i : j;
1424
+ const idx2 = i > j ? i2 : j2;
1425
+ if (idx < 0) return path3;
1426
+ if (idx === idx2) return path3.slice(0, idx + 1);
1427
+ return path3.slice(0, idx);
1428
+ }
1429
+ async function loaderImpl({ args, loaderContext, loaderState }, sendRequest, waitForPendingRequest) {
1430
+ const resourcePath = loaderContext.resourcePath;
1431
+ const contextDirectory = resourcePath ? dirname(resourcePath) : null;
1432
+ const pendingDependencyRequest = [];
1433
+ loaderContext.parallel = true;
1434
+ loaderContext.dependency = loaderContext.addDependency = function addDependency(file) {
1435
+ pendingDependencyRequest.push(
1436
+ sendRequest("AddDependency" /* AddDependency */, file)
1437
+ );
1438
+ };
1439
+ loaderContext.addContextDependency = function addContextDependency(context) {
1440
+ pendingDependencyRequest.push(
1441
+ sendRequest("AddContextDependency" /* AddContextDependency */, context)
1442
+ );
1443
+ };
1444
+ loaderContext.addBuildDependency = function addBuildDependency(file) {
1445
+ pendingDependencyRequest.push(
1446
+ sendRequest("AddBuildDependency" /* AddBuildDependency */, file)
1447
+ );
1448
+ };
1449
+ loaderContext.getDependencies = function getDependencies() {
1450
+ waitForPendingRequest(pendingDependencyRequest);
1451
+ return sendRequest("GetDependencies" /* GetDependencies */).wait();
1452
+ };
1453
+ loaderContext.getContextDependencies = function getContextDependencies() {
1454
+ waitForPendingRequest(pendingDependencyRequest);
1455
+ return sendRequest("GetContextDependencies" /* GetContextDependencies */).wait();
1456
+ };
1457
+ loaderContext.getMissingDependencies = function getMissingDependencies() {
1458
+ waitForPendingRequest(pendingDependencyRequest);
1459
+ return sendRequest("GetMissingDependencies" /* GetMissingDependencies */).wait();
1460
+ };
1461
+ loaderContext.clearDependencies = function clearDependencies() {
1462
+ pendingDependencyRequest.push(sendRequest("ClearDependencies" /* ClearDependencies */));
1463
+ };
1464
+ loaderContext.resolve = function resolve(context, request, callback) {
1465
+ sendRequest("Resolve" /* Resolve */, context, request).then(
1466
+ (result) => {
1467
+ callback(null, result);
1468
+ },
1469
+ (err) => {
1470
+ callback(err);
1471
+ }
1472
+ );
1473
+ };
1474
+ loaderContext.getResolve = function getResolve(options) {
1475
+ return (context, request, callback) => {
1476
+ if (!callback) {
1477
+ return new Promise((resolve, reject) => {
1478
+ sendRequest("GetResolve" /* GetResolve */, options, context, request).then(
1479
+ (result) => {
1480
+ resolve(result);
1481
+ },
1482
+ (err) => {
1483
+ reject(err);
1484
+ }
1485
+ );
1486
+ });
1487
+ }
1488
+ sendRequest("GetResolve" /* GetResolve */, options, context, request).then(
1489
+ (result) => {
1490
+ callback(null, result);
1491
+ },
1492
+ (err) => {
1493
+ callback(err);
1494
+ }
1495
+ );
1496
+ };
1497
+ };
1498
+ loaderContext.getLogger = function getLogger(name) {
1499
+ return {
1500
+ error(...args2) {
1501
+ sendRequest("GetLogger" /* GetLogger */, "error", name, args2);
1502
+ },
1503
+ warn(...args2) {
1504
+ sendRequest("GetLogger" /* GetLogger */, "warn", name, args2);
1505
+ },
1506
+ info(...args2) {
1507
+ sendRequest("GetLogger" /* GetLogger */, "info", name, args2);
1508
+ },
1509
+ log(...args2) {
1510
+ sendRequest("GetLogger" /* GetLogger */, "log", name, args2);
1511
+ },
1512
+ debug(...args2) {
1513
+ sendRequest("GetLogger" /* GetLogger */, "debug", name, args2);
1514
+ },
1515
+ assert(assertion, ...args2) {
1516
+ if (!assertion) {
1517
+ sendRequest("GetLogger" /* GetLogger */, "error", name, args2);
1518
+ }
1519
+ },
1520
+ trace() {
1521
+ sendRequest("GetLogger" /* GetLogger */, "trace", name, ["Trace"]);
1522
+ },
1523
+ clear() {
1524
+ sendRequest("GetLogger" /* GetLogger */, "clear", name);
1525
+ },
1526
+ status(...args2) {
1527
+ sendRequest("GetLogger" /* GetLogger */, "status", name, args2);
1528
+ },
1529
+ group(...args2) {
1530
+ sendRequest("GetLogger" /* GetLogger */, "group", name, args2);
1531
+ },
1532
+ groupCollapsed(...args2) {
1533
+ sendRequest("GetLogger" /* GetLogger */, "groupCollapsed", name, args2);
1534
+ },
1535
+ groupEnd(...args2) {
1536
+ sendRequest("GetLogger" /* GetLogger */, "groupEnd", name, args2);
1537
+ },
1538
+ profile(label) {
1539
+ sendRequest("GetLogger" /* GetLogger */, "profile", name, [label]);
1540
+ },
1541
+ profileEnd(label) {
1542
+ sendRequest("GetLogger" /* GetLogger */, "profileEnd", name, [label]);
1543
+ },
1544
+ time(label) {
1545
+ sendRequest("GetLogger" /* GetLogger */, "time", name, [label]);
1546
+ },
1547
+ timeEnd(label) {
1548
+ sendRequest("GetLogger" /* GetLogger */, "timeEnd", name, [label]);
1549
+ },
1550
+ timeLog(label, ...args2) {
1551
+ sendRequest("GetLogger" /* GetLogger */, "timeLog", name, [label, ...args2]);
1552
+ },
1553
+ timeAggregate(label) {
1554
+ sendRequest("GetLogger" /* GetLogger */, "timeAggregate", name, [label]);
1555
+ },
1556
+ timeAggregateEnd(label) {
1557
+ sendRequest("GetLogger" /* GetLogger */, "timeAggregateEnd", name, [label]);
1558
+ }
1559
+ };
1560
+ };
1561
+ loaderContext.emitError = function emitError(err) {
1562
+ sendRequest("EmitError" /* EmitError */, serializeError(err));
1563
+ };
1564
+ loaderContext.emitWarning = function emitWarning(warning) {
1565
+ sendRequest("EmitWarning" /* EmitWarning */, serializeError(warning));
1566
+ };
1567
+ loaderContext.emitFile = function emitFile(name, content, sourceMap, assetInfo) {
1568
+ sendRequest("EmitFile" /* EmitFile */, name, content, sourceMap, assetInfo);
1569
+ };
1570
+ loaderContext.experiments = {
1571
+ emitDiagnostic(diagnostic) {
1572
+ sendRequest("EmitDiagnostic" /* EmitDiagnostic */, diagnostic);
1573
+ }
1574
+ };
1575
+ const getAbsolutify = memoize(() => absolutify.bindCache({}));
1576
+ const getAbsolutifyInContext = memoize(
1577
+ () => absolutify.bindContextCache(contextDirectory, {})
1578
+ );
1579
+ const getContextify = memoize(() => contextify.bindCache({}));
1580
+ const getContextifyInContext = memoize(
1581
+ () => contextify.bindContextCache(contextDirectory, {})
1582
+ );
1583
+ loaderContext.utils = {
1584
+ absolutify: (context, request) => {
1585
+ return context === contextDirectory ? getAbsolutifyInContext()(request) : getAbsolutify()(context, request);
1586
+ },
1587
+ contextify: (context, request) => {
1588
+ return context === contextDirectory ? getContextifyInContext()(request) : getContextify()(context, request);
1589
+ },
1590
+ createHash: (type) => {
1591
+ return createHash(
1592
+ type || loaderContext._compilation.outputOptions.hashFunction
1593
+ );
1594
+ }
1595
+ };
1596
+ loaderContext._compiler = {
1597
+ ...loaderContext._compiler,
1598
+ // @ts-expect-error: some properties are missing.
1599
+ webpack: {
1600
+ util: {
1601
+ createHash: (init_createHash(), __toCommonJS(createHash_exports)).createHash,
1602
+ cleverMerge: (init_cleverMerge(), __toCommonJS(cleverMerge_exports)).cleverMerge
1603
+ }
1604
+ }
1605
+ };
1606
+ loaderContext._compilation = {
1607
+ ...loaderContext._compilation,
1608
+ getPath(filename, data) {
1609
+ return sendRequest("CompilationGetPath" /* CompilationGetPath */, filename, data).wait();
1610
+ },
1611
+ getPathWithInfo(filename, data) {
1612
+ return sendRequest(
1613
+ "CompilationGetPathWithInfo" /* CompilationGetPathWithInfo */,
1614
+ filename,
1615
+ data
1616
+ ).wait();
1617
+ },
1618
+ getAssetPath(filename, data) {
1619
+ return sendRequest(
1620
+ "CompilationGetAssetPath" /* CompilationGetAssetPath */,
1621
+ filename,
1622
+ data
1623
+ ).wait();
1624
+ },
1625
+ getAssetPathWithInfo(filename, data) {
1626
+ return sendRequest(
1627
+ "CompilationGetAssetPathWithInfo" /* CompilationGetAssetPathWithInfo */,
1628
+ filename,
1629
+ data
1630
+ ).wait();
1631
+ }
1632
+ };
1633
+ const _module = loaderContext._module;
1634
+ loaderContext._module = {
1635
+ type: _module.type,
1636
+ identifier() {
1637
+ return _module.identifier;
1638
+ },
1639
+ matchResource: _module.matchResource,
1640
+ request: _module.request,
1641
+ userRequest: _module.userRequest,
1642
+ rawRequest: _module.rawRequest
1643
+ };
1644
+ loaderContext.importModule = function importModule(request, options, callback) {
1645
+ if (!callback) {
1646
+ return new Promise((resolve, reject) => {
1647
+ sendRequest("ImportModule" /* ImportModule */, request, options).then(
1648
+ (result) => {
1649
+ resolve(result);
1650
+ },
1651
+ (err) => {
1652
+ reject(err);
1653
+ }
1654
+ );
1655
+ });
1656
+ }
1657
+ sendRequest("ImportModule" /* ImportModule */, request, options).then(
1658
+ (result) => {
1659
+ callback(null, result);
1660
+ },
1661
+ (err) => {
1662
+ callback(err);
1663
+ }
1664
+ );
1665
+ };
1666
+ loaderContext.fs = require("fs");
1667
+ Object.defineProperty(loaderContext, "request", {
1668
+ enumerable: true,
1669
+ get: () => loaderContext.loaders.map((o) => o.request).concat(loaderContext.resource || "").join("!")
1670
+ });
1671
+ Object.defineProperty(loaderContext, "remainingRequest", {
1672
+ enumerable: true,
1673
+ get: () => {
1674
+ if (loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource)
1675
+ return "";
1676
+ return loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map((o) => o.request).concat(loaderContext.resource || "").join("!");
1677
+ }
1678
+ });
1679
+ Object.defineProperty(loaderContext, "currentRequest", {
1680
+ enumerable: true,
1681
+ get: () => loaderContext.loaders.slice(loaderContext.loaderIndex).map((o) => o.request).concat(loaderContext.resource || "").join("!")
1682
+ });
1683
+ Object.defineProperty(loaderContext, "previousRequest", {
1684
+ enumerable: true,
1685
+ get: () => loaderContext.loaders.slice(0, loaderContext.loaderIndex).map((o) => o.request).join("!")
1686
+ });
1687
+ Object.defineProperty(loaderContext, "query", {
1688
+ enumerable: true,
1689
+ get: () => {
1690
+ const entry = loaderContext.loaders[loaderContext.loaderIndex];
1691
+ return entry.options && typeof entry.options === "object" ? entry.options : entry.query;
1692
+ }
1693
+ });
1694
+ loaderContext.getOptions = function getOptions() {
1695
+ const loader = getCurrentLoader(loaderContext);
1696
+ let options = loader == null ? void 0 : loader.options;
1697
+ if (typeof options === "string") {
1698
+ if (options.startsWith("{") && options.endsWith("}")) {
1699
+ try {
1700
+ const parseJson = require_lib();
1701
+ options = parseJson(options);
1702
+ } catch (e) {
1703
+ throw new Error(`Cannot parse string options: ${e.message}`);
1704
+ }
1705
+ } else {
1706
+ options = import_node_querystring.default.parse(options);
1707
+ }
1708
+ }
1709
+ if (options === null || options === void 0) {
1710
+ options = {};
1711
+ }
1712
+ return options;
1713
+ };
1714
+ loaderContext.cacheable = function cacheable(flag) {
1715
+ if (flag === false) {
1716
+ sendRequest("SetCacheable" /* SetCacheable */, false);
1717
+ }
1718
+ };
1719
+ Object.defineProperty(loaderContext, "data", {
1720
+ enumerable: true,
1721
+ get: () => loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data,
1722
+ set: (value) => {
1723
+ loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data = value;
1724
+ }
1725
+ });
1726
+ const shouldYieldToMainThread = (currentLoaderObject) => {
1727
+ if (!(currentLoaderObject == null ? void 0 : currentLoaderObject.parallel)) {
1728
+ return true;
1729
+ }
1730
+ if (currentLoaderObject == null ? void 0 : currentLoaderObject.request.startsWith(BUILTIN_LOADER_PREFIX)) {
1731
+ return true;
1732
+ }
1733
+ return false;
1734
+ };
1735
+ switch (loaderState) {
1736
+ case import_binding.JsLoaderState.Pitching: {
1737
+ while (loaderContext.loaderIndex < loaderContext.loaders.length) {
1738
+ const currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
1739
+ if (shouldYieldToMainThread(currentLoaderObject)) break;
1740
+ if (currentLoaderObject.pitchExecuted) {
1741
+ loaderContext.loaderIndex += 1;
1742
+ continue;
1743
+ }
1744
+ await loadLoaderAsync(currentLoaderObject);
1745
+ const fn = currentLoaderObject.pitch;
1746
+ currentLoaderObject.pitchExecuted = true;
1747
+ if (!fn) continue;
1748
+ args = await runSyncOrAsync(fn, loaderContext, [
1749
+ loaderContext.remainingRequest,
1750
+ loaderContext.previousRequest,
1751
+ currentLoaderObject.loaderItem.data
1752
+ ]) || [];
1753
+ const hasArg = args.some((value) => value !== void 0);
1754
+ if (hasArg) {
1755
+ break;
1756
+ }
1757
+ }
1758
+ }
1759
+ case import_binding.JsLoaderState.Normal: {
1760
+ while (loaderContext.loaderIndex >= 0) {
1761
+ const currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex];
1762
+ if (shouldYieldToMainThread(currentLoaderObject)) break;
1763
+ if (currentLoaderObject.normalExecuted) {
1764
+ loaderContext.loaderIndex--;
1765
+ continue;
1766
+ }
1767
+ await loadLoaderAsync(currentLoaderObject);
1768
+ const fn = currentLoaderObject.normal;
1769
+ currentLoaderObject.normalExecuted = true;
1770
+ if (!fn) continue;
1771
+ convertArgs(args, !!currentLoaderObject.raw);
1772
+ args = await runSyncOrAsync(fn, loaderContext, args) || [];
1773
+ }
1774
+ }
1775
+ }
1776
+ sendRequest(
1777
+ "UpdateLoaderObjects" /* UpdateLoaderObjects */,
1778
+ loaderContext.loaders.map((item) => {
1779
+ return {
1780
+ data: item.loaderItem.data,
1781
+ normalExecuted: item.normalExecuted,
1782
+ pitchExecuted: item.pitchExecuted
1783
+ };
1784
+ })
1785
+ );
1786
+ return args;
1787
+ }
1788
+ var nextId = 0;
1789
+ var responseCallbacks = {};
1790
+ function handleIncomingResponses(workerMessage) {
1791
+ if (isWorkerResponseMessage(workerMessage)) {
1792
+ const { id, data } = workerMessage;
1793
+ const callback = responseCallbacks[id];
1794
+ if (callback) {
1795
+ delete responseCallbacks[id];
1796
+ callback(
1797
+ null,
1798
+ /* data */
1799
+ data
1800
+ );
1801
+ } else {
1802
+ throw new Error(`No callback found for response with id ${id}`);
1803
+ }
1804
+ } else if (isWorkerResponseErrorMessage(workerMessage)) {
1805
+ const { id, error } = workerMessage;
1806
+ const callback = responseCallbacks[id];
1807
+ if (callback) {
1808
+ delete responseCallbacks[id];
1809
+ callback(error, void 0);
1810
+ } else {
1811
+ throw new Error(`No callback found for response with id ${id}`);
1812
+ }
1813
+ }
1814
+ }
1815
+ function createWaitForPendingRequest(sendRequest) {
1816
+ return (requests) => {
1817
+ return sendRequest.sync(
1818
+ "WaitForPendingRequest" /* WaitForPendingRequest */,
1819
+ (Array.isArray(requests) ? requests : [requests]).map((request) => {
1820
+ return request.id;
1821
+ })
1822
+ );
1823
+ };
1824
+ }
1825
+ function createSendRequest(workerPort, workerSyncPort) {
1826
+ const sendRequest = (requestType, ...args) => {
1827
+ const id = nextId++;
1828
+ workerPort.postMessage({
1829
+ type: "request",
1830
+ id,
1831
+ requestType,
1832
+ data: args
1833
+ });
1834
+ const result = new Promise((resolve, reject) => {
1835
+ responseCallbacks[id] = (err, data) => {
1836
+ if (err) {
1837
+ reject(err);
1838
+ return;
1839
+ }
1840
+ resolve(data);
1841
+ };
1842
+ });
1843
+ result.wait = () => {
1844
+ return sendRequest.sync("WaitForPendingRequest" /* WaitForPendingRequest */, id);
1845
+ };
1846
+ result.id = id;
1847
+ return result;
1848
+ };
1849
+ sendRequest.sync = createSendRequestSync(workerSyncPort);
1850
+ return sendRequest;
1851
+ }
1852
+ function createSendRequestSync(workerSyncPort) {
1853
+ return (requestType, ...args) => {
1854
+ const id = nextId++;
1855
+ const sharedBuffer = new SharedArrayBuffer(8);
1856
+ const sharedBufferView = new Int32Array(sharedBuffer);
1857
+ workerSyncPort.postMessage({
1858
+ type: "request-sync",
1859
+ id,
1860
+ requestType,
1861
+ data: args,
1862
+ sharedBuffer
1863
+ });
1864
+ const status = Atomics.wait(sharedBufferView, 0, 0);
1865
+ if (status !== "ok" && status !== "not-equal")
1866
+ throw new Error(`Internal error: Atomics.wait() failed: ${status}`);
1867
+ const {
1868
+ message
1869
+ } = (0, import_node_worker_threads2.receiveMessageOnPort)(workerSyncPort);
1870
+ if (id !== message.id) {
1871
+ throw new Error(`Unexpected response id: ${message.id}, expected: ${id}`);
1872
+ }
1873
+ if (isWorkerResponseMessage(message)) {
1874
+ return message.data;
1875
+ }
1876
+ throw message.error;
1877
+ };
1878
+ }
1879
+ function worker(workerOptions) {
1880
+ const workerData = workerOptions.workerData;
1881
+ delete workerOptions.workerData;
1882
+ workerData.workerPort.on("message", handleIncomingResponses);
1883
+ const sendRequest = createSendRequest(
1884
+ workerData.workerPort,
1885
+ workerData.workerSyncPort
1886
+ );
1887
+ const waitFor = createWaitForPendingRequest(sendRequest);
1888
+ loaderImpl(workerOptions, sendRequest, waitFor).then(async (data) => {
1889
+ workerData.workerPort.postMessage({ type: "done", data });
1890
+ }).catch(async (err) => {
1891
+ workerData.workerPort.postMessage({
1892
+ type: "done-error",
1893
+ error: serializeError(err)
1894
+ });
1895
+ });
1896
+ }
1897
+ function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
1898
+ var _a;
1899
+ if (((_a = loaderContext.loaders) == null ? void 0 : _a.length) && index < loaderContext.loaders.length && index >= 0 && loaderContext.loaders[index]) {
1900
+ return loaderContext.loaders[index];
1901
+ }
1902
+ return null;
1903
+ }
1904
+ module.exports = worker;