@cloudflare/vitest-pool-workers 0.12.20 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/codemods/vitest-v3-to-v4.mjs +45 -0
  2. package/dist/codemods/vitest-v3-to-v4.mjs.map +1 -0
  3. package/dist/pool/index.d.mts +133 -0
  4. package/dist/pool/index.mjs +2784 -7847
  5. package/dist/pool/index.mjs.map +1 -6
  6. package/dist/worker/index.mjs +753 -792
  7. package/dist/worker/index.mjs.map +1 -6
  8. package/dist/worker/lib/cloudflare/snapshot.mjs +39 -0
  9. package/dist/worker/lib/cloudflare/snapshot.mjs.map +1 -0
  10. package/dist/worker/lib/cloudflare/test-internal.mjs +788 -1276
  11. package/dist/worker/lib/cloudflare/test-internal.mjs.map +1 -6
  12. package/dist/worker/lib/cloudflare/test.mjs +3 -36
  13. package/dist/worker/node/console.mjs +95 -116
  14. package/dist/worker/node/console.mjs.map +1 -6
  15. package/dist/worker/node/vm.mjs +10 -11
  16. package/dist/worker/node/vm.mjs.map +1 -6
  17. package/package.json +25 -21
  18. package/types/cloudflare-test.d.ts +5 -30
  19. package/dist/config/d1.d.ts +0 -7
  20. package/dist/config/index.cjs +0 -230
  21. package/dist/config/index.cjs.map +0 -6
  22. package/dist/config/index.d.ts +0 -27
  23. package/dist/config/pages.d.ts +0 -2
  24. package/dist/pool/config.d.ts +0 -112
  25. package/dist/pool/helpers.d.ts +0 -5
  26. package/dist/shared/builtin-modules.d.ts +0 -1
  27. package/dist/shared/d1.d.ts +0 -4
  28. package/dist/worker/lib/cloudflare/empty-internal.cjs +0 -27
  29. package/dist/worker/lib/cloudflare/empty-internal.cjs.map +0 -6
  30. package/dist/worker/lib/cloudflare/mock-agent.cjs +0 -3433
  31. package/dist/worker/lib/cloudflare/mock-agent.cjs.map +0 -6
  32. package/dist/worker/lib/cloudflare/test-runner.mjs +0 -246
  33. package/dist/worker/lib/cloudflare/test-runner.mjs.map +0 -6
  34. package/dist/worker/lib/cloudflare/test.mjs.map +0 -6
  35. package/dist/worker/lib/debug.mjs +0 -9
  36. package/dist/worker/lib/debug.mjs.map +0 -6
  37. package/dist/worker/lib/mlly.mjs +0 -48
  38. package/dist/worker/lib/mlly.mjs.map +0 -6
  39. package/dist/worker/lib/tinypool.mjs +0 -6
  40. package/dist/worker/lib/tinypool.mjs.map +0 -6
@@ -1,858 +1,819 @@
1
- // src/worker/index.ts
2
- import assert3 from "node:assert";
3
- import { Buffer as Buffer3 } from "node:buffer";
4
- import events from "node:events";
5
- import process from "node:process";
1
+ import assert from "node:assert";
6
2
  import * as vm from "node:vm";
7
3
  import defines from "__VITEST_POOL_WORKERS_DEFINES";
8
- import {
9
- createWorkerEntrypointWrapper,
10
- internalEnv,
11
- maybeHandleRunRequest,
12
- registerHandlerAndGlobalWaitUntil,
13
- runInRunnerObject,
14
- setEnv
15
- } from "cloudflare:test-internal";
4
+ import { createWorkerEntrypointWrapper, maybeHandleRunRequest, registerHandlerAndGlobalWaitUntil, runInRunnerObject } from "cloudflare:test-internal";
5
+ import { DurableObject } from "cloudflare:workers";
6
+ import { Buffer } from "node:buffer";
16
7
 
17
- // ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/utils.js
8
+ export * from "__VITEST_POOL_WORKERS_USER_OBJECT"
9
+
10
+ //#region ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/utils.js
18
11
  var DevalueError = class extends Error {
19
- /**
20
- * @param {string} message
21
- * @param {string[]} keys
22
- */
23
- constructor(message, keys) {
24
- super(message);
25
- this.name = "DevalueError";
26
- this.path = keys.join("");
27
- }
12
+ /**
13
+ * @param {string} message
14
+ * @param {string[]} keys
15
+ * @param {any} [value] - The value that failed to be serialized
16
+ * @param {any} [root] - The root value being serialized
17
+ */
18
+ constructor(message, keys, value, root) {
19
+ super(message);
20
+ this.name = "DevalueError";
21
+ this.path = keys.join("");
22
+ this.value = value;
23
+ this.root = root;
24
+ }
28
25
  };
26
+ /** @param {any} thing */
29
27
  function is_primitive(thing) {
30
- return Object(thing) !== thing;
28
+ return Object(thing) !== thing;
31
29
  }
32
- var object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(
33
- Object.prototype
34
- ).sort().join("\0");
30
+ const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
31
+ /** @param {any} thing */
35
32
  function is_plain_object(thing) {
36
- const proto = Object.getPrototypeOf(thing);
37
- return proto === Object.prototype || proto === null || Object.getPrototypeOf(proto) === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names;
33
+ const proto = Object.getPrototypeOf(thing);
34
+ return proto === Object.prototype || proto === null || Object.getPrototypeOf(proto) === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names;
38
35
  }
36
+ /** @param {any} thing */
39
37
  function get_type(thing) {
40
- return Object.prototype.toString.call(thing).slice(8, -1);
38
+ return Object.prototype.toString.call(thing).slice(8, -1);
41
39
  }
40
+ /** @param {string} char */
42
41
  function get_escaped_char(char) {
43
- switch (char) {
44
- case '"':
45
- return '\\"';
46
- case "<":
47
- return "\\u003C";
48
- case "\\":
49
- return "\\\\";
50
- case "\n":
51
- return "\\n";
52
- case "\r":
53
- return "\\r";
54
- case " ":
55
- return "\\t";
56
- case "\b":
57
- return "\\b";
58
- case "\f":
59
- return "\\f";
60
- case "\u2028":
61
- return "\\u2028";
62
- case "\u2029":
63
- return "\\u2029";
64
- default:
65
- return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
66
- }
42
+ switch (char) {
43
+ case "\"": return "\\\"";
44
+ case "<": return "\\u003C";
45
+ case "\\": return "\\\\";
46
+ case "\n": return "\\n";
47
+ case "\r": return "\\r";
48
+ case " ": return "\\t";
49
+ case "\b": return "\\b";
50
+ case "\f": return "\\f";
51
+ case "\u2028": return "\\u2028";
52
+ case "\u2029": return "\\u2029";
53
+ default: return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
54
+ }
67
55
  }
56
+ /** @param {string} str */
68
57
  function stringify_string(str) {
69
- let result = "";
70
- let last_pos = 0;
71
- const len = str.length;
72
- for (let i = 0; i < len; i += 1) {
73
- const char = str[i];
74
- const replacement = get_escaped_char(char);
75
- if (replacement) {
76
- result += str.slice(last_pos, i) + replacement;
77
- last_pos = i + 1;
78
- }
79
- }
80
- return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
58
+ let result = "";
59
+ let last_pos = 0;
60
+ const len = str.length;
61
+ for (let i = 0; i < len; i += 1) {
62
+ const char = str[i];
63
+ const replacement = get_escaped_char(char);
64
+ if (replacement) {
65
+ result += str.slice(last_pos, i) + replacement;
66
+ last_pos = i + 1;
67
+ }
68
+ }
69
+ return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
81
70
  }
71
+ /** @param {Record<string | symbol, any>} object */
82
72
  function enumerable_symbols(object) {
83
- return Object.getOwnPropertySymbols(object).filter(
84
- (symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable
85
- );
73
+ return Object.getOwnPropertySymbols(object).filter((symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable);
86
74
  }
87
- var is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
75
+ const is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
76
+ /** @param {string} key */
88
77
  function stringify_key(key) {
89
- return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
78
+ return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
79
+ }
80
+ /** @param {string} s */
81
+ function is_valid_array_index(s) {
82
+ if (s.length === 0) return false;
83
+ if (s.length > 1 && s.charCodeAt(0) === 48) return false;
84
+ for (let i = 0; i < s.length; i++) {
85
+ const c = s.charCodeAt(i);
86
+ if (c < 48 || c > 57) return false;
87
+ }
88
+ const n = +s;
89
+ if (n >= 2 ** 32 - 1) return false;
90
+ if (n < 0) return false;
91
+ return true;
92
+ }
93
+ /**
94
+ * Finds the populated indices of an array.
95
+ * @param {unknown[]} array
96
+ */
97
+ function valid_array_indices(array) {
98
+ const keys = Object.keys(array);
99
+ for (var i = keys.length - 1; i >= 0; i--) if (is_valid_array_index(keys[i])) break;
100
+ keys.length = i + 1;
101
+ return keys;
90
102
  }
91
103
 
92
- // ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/base64.js
104
+ //#endregion
105
+ //#region ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/base64.js
106
+ /**
107
+ * Base64 Encodes an arraybuffer
108
+ * @param {ArrayBuffer} arraybuffer
109
+ * @returns {string}
110
+ */
93
111
  function encode64(arraybuffer) {
94
- const dv = new DataView(arraybuffer);
95
- let binaryString = "";
96
- for (let i = 0; i < arraybuffer.byteLength; i++) {
97
- binaryString += String.fromCharCode(dv.getUint8(i));
98
- }
99
- return binaryToAscii(binaryString);
112
+ const dv = new DataView(arraybuffer);
113
+ let binaryString = "";
114
+ for (let i = 0; i < arraybuffer.byteLength; i++) binaryString += String.fromCharCode(dv.getUint8(i));
115
+ return binaryToAscii(binaryString);
100
116
  }
117
+ /**
118
+ * Decodes a base64 string into an arraybuffer
119
+ * @param {string} string
120
+ * @returns {ArrayBuffer}
121
+ */
101
122
  function decode64(string) {
102
- const binaryString = asciiToBinary(string);
103
- const arraybuffer = new ArrayBuffer(binaryString.length);
104
- const dv = new DataView(arraybuffer);
105
- for (let i = 0; i < arraybuffer.byteLength; i++) {
106
- dv.setUint8(i, binaryString.charCodeAt(i));
107
- }
108
- return arraybuffer;
123
+ const binaryString = asciiToBinary(string);
124
+ const arraybuffer = new ArrayBuffer(binaryString.length);
125
+ const dv = new DataView(arraybuffer);
126
+ for (let i = 0; i < arraybuffer.byteLength; i++) dv.setUint8(i, binaryString.charCodeAt(i));
127
+ return arraybuffer;
109
128
  }
110
- var KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
129
+ const KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
130
+ /**
131
+ * Substitute for atob since it's deprecated in node.
132
+ * Does not do any input validation.
133
+ *
134
+ * @see https://github.com/jsdom/abab/blob/master/lib/atob.js
135
+ *
136
+ * @param {string} data
137
+ * @returns {string}
138
+ */
111
139
  function asciiToBinary(data) {
112
- if (data.length % 4 === 0) {
113
- data = data.replace(/==?$/, "");
114
- }
115
- let output = "";
116
- let buffer = 0;
117
- let accumulatedBits = 0;
118
- for (let i = 0; i < data.length; i++) {
119
- buffer <<= 6;
120
- buffer |= KEY_STRING.indexOf(data[i]);
121
- accumulatedBits += 6;
122
- if (accumulatedBits === 24) {
123
- output += String.fromCharCode((buffer & 16711680) >> 16);
124
- output += String.fromCharCode((buffer & 65280) >> 8);
125
- output += String.fromCharCode(buffer & 255);
126
- buffer = accumulatedBits = 0;
127
- }
128
- }
129
- if (accumulatedBits === 12) {
130
- buffer >>= 4;
131
- output += String.fromCharCode(buffer);
132
- } else if (accumulatedBits === 18) {
133
- buffer >>= 2;
134
- output += String.fromCharCode((buffer & 65280) >> 8);
135
- output += String.fromCharCode(buffer & 255);
136
- }
137
- return output;
140
+ if (data.length % 4 === 0) data = data.replace(/==?$/, "");
141
+ let output = "";
142
+ let buffer = 0;
143
+ let accumulatedBits = 0;
144
+ for (let i = 0; i < data.length; i++) {
145
+ buffer <<= 6;
146
+ buffer |= KEY_STRING.indexOf(data[i]);
147
+ accumulatedBits += 6;
148
+ if (accumulatedBits === 24) {
149
+ output += String.fromCharCode((buffer & 16711680) >> 16);
150
+ output += String.fromCharCode((buffer & 65280) >> 8);
151
+ output += String.fromCharCode(buffer & 255);
152
+ buffer = accumulatedBits = 0;
153
+ }
154
+ }
155
+ if (accumulatedBits === 12) {
156
+ buffer >>= 4;
157
+ output += String.fromCharCode(buffer);
158
+ } else if (accumulatedBits === 18) {
159
+ buffer >>= 2;
160
+ output += String.fromCharCode((buffer & 65280) >> 8);
161
+ output += String.fromCharCode(buffer & 255);
162
+ }
163
+ return output;
138
164
  }
165
+ /**
166
+ * Substitute for btoa since it's deprecated in node.
167
+ * Does not do any input validation.
168
+ *
169
+ * @see https://github.com/jsdom/abab/blob/master/lib/btoa.js
170
+ *
171
+ * @param {string} str
172
+ * @returns {string}
173
+ */
139
174
  function binaryToAscii(str) {
140
- let out = "";
141
- for (let i = 0; i < str.length; i += 3) {
142
- const groupsOfSix = [void 0, void 0, void 0, void 0];
143
- groupsOfSix[0] = str.charCodeAt(i) >> 2;
144
- groupsOfSix[1] = (str.charCodeAt(i) & 3) << 4;
145
- if (str.length > i + 1) {
146
- groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4;
147
- groupsOfSix[2] = (str.charCodeAt(i + 1) & 15) << 2;
148
- }
149
- if (str.length > i + 2) {
150
- groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6;
151
- groupsOfSix[3] = str.charCodeAt(i + 2) & 63;
152
- }
153
- for (let j = 0; j < groupsOfSix.length; j++) {
154
- if (typeof groupsOfSix[j] === "undefined") {
155
- out += "=";
156
- } else {
157
- out += KEY_STRING[groupsOfSix[j]];
158
- }
159
- }
160
- }
161
- return out;
175
+ let out = "";
176
+ for (let i = 0; i < str.length; i += 3) {
177
+ /** @type {[number, number, number, number]} */
178
+ const groupsOfSix = [
179
+ void 0,
180
+ void 0,
181
+ void 0,
182
+ void 0
183
+ ];
184
+ groupsOfSix[0] = str.charCodeAt(i) >> 2;
185
+ groupsOfSix[1] = (str.charCodeAt(i) & 3) << 4;
186
+ if (str.length > i + 1) {
187
+ groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4;
188
+ groupsOfSix[2] = (str.charCodeAt(i + 1) & 15) << 2;
189
+ }
190
+ if (str.length > i + 2) {
191
+ groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6;
192
+ groupsOfSix[3] = str.charCodeAt(i + 2) & 63;
193
+ }
194
+ for (let j = 0; j < groupsOfSix.length; j++) if (typeof groupsOfSix[j] === "undefined") out += "=";
195
+ else out += KEY_STRING[groupsOfSix[j]];
196
+ }
197
+ return out;
162
198
  }
163
199
 
164
- // ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/constants.js
165
- var UNDEFINED = -1;
166
- var HOLE = -2;
167
- var NAN = -3;
168
- var POSITIVE_INFINITY = -4;
169
- var NEGATIVE_INFINITY = -5;
170
- var NEGATIVE_ZERO = -6;
200
+ //#endregion
201
+ //#region ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/constants.js
202
+ const UNDEFINED = -1;
203
+ const HOLE = -2;
204
+ const NAN = -3;
205
+ const POSITIVE_INFINITY = -4;
206
+ const NEGATIVE_INFINITY = -5;
207
+ const NEGATIVE_ZERO = -6;
208
+ const SPARSE = -7;
171
209
 
172
- // ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/parse.js
210
+ //#endregion
211
+ //#region ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/parse.js
212
+ /**
213
+ * Revive a value serialized with `devalue.stringify`
214
+ * @param {string} serialized
215
+ * @param {Record<string, (value: any) => any>} [revivers]
216
+ */
173
217
  function parse(serialized, revivers) {
174
- return unflatten(JSON.parse(serialized), revivers);
218
+ return unflatten(JSON.parse(serialized), revivers);
175
219
  }
220
+ /**
221
+ * Revive a value flattened with `devalue.stringify`
222
+ * @param {number | any[]} parsed
223
+ * @param {Record<string, (value: any) => any>} [revivers]
224
+ */
176
225
  function unflatten(parsed, revivers) {
177
- if (typeof parsed === "number") return hydrate(parsed, true);
178
- if (!Array.isArray(parsed) || parsed.length === 0) {
179
- throw new Error("Invalid input");
180
- }
181
- const values = (
182
- /** @type {any[]} */
183
- parsed
184
- );
185
- const hydrated = Array(values.length);
186
- function hydrate(index, standalone = false) {
187
- if (index === UNDEFINED) return void 0;
188
- if (index === NAN) return NaN;
189
- if (index === POSITIVE_INFINITY) return Infinity;
190
- if (index === NEGATIVE_INFINITY) return -Infinity;
191
- if (index === NEGATIVE_ZERO) return -0;
192
- if (standalone || typeof index !== "number") {
193
- throw new Error(`Invalid input`);
194
- }
195
- if (index in hydrated) return hydrated[index];
196
- const value = values[index];
197
- if (!value || typeof value !== "object") {
198
- hydrated[index] = value;
199
- } else if (Array.isArray(value)) {
200
- if (typeof value[0] === "string") {
201
- const type = value[0];
202
- const reviver = revivers?.[type];
203
- if (reviver) {
204
- return hydrated[index] = reviver(hydrate(value[1]));
205
- }
206
- switch (type) {
207
- case "Date":
208
- hydrated[index] = new Date(value[1]);
209
- break;
210
- case "Set":
211
- const set = /* @__PURE__ */ new Set();
212
- hydrated[index] = set;
213
- for (let i = 1; i < value.length; i += 1) {
214
- set.add(hydrate(value[i]));
215
- }
216
- break;
217
- case "Map":
218
- const map = /* @__PURE__ */ new Map();
219
- hydrated[index] = map;
220
- for (let i = 1; i < value.length; i += 2) {
221
- map.set(hydrate(value[i]), hydrate(value[i + 1]));
222
- }
223
- break;
224
- case "RegExp":
225
- hydrated[index] = new RegExp(value[1], value[2]);
226
- break;
227
- case "Object":
228
- hydrated[index] = Object(value[1]);
229
- break;
230
- case "BigInt":
231
- hydrated[index] = BigInt(value[1]);
232
- break;
233
- case "null":
234
- const obj = /* @__PURE__ */ Object.create(null);
235
- hydrated[index] = obj;
236
- for (let i = 1; i < value.length; i += 2) {
237
- obj[value[i]] = hydrate(value[i + 1]);
238
- }
239
- break;
240
- case "Int8Array":
241
- case "Uint8Array":
242
- case "Uint8ClampedArray":
243
- case "Int16Array":
244
- case "Uint16Array":
245
- case "Int32Array":
246
- case "Uint32Array":
247
- case "Float32Array":
248
- case "Float64Array":
249
- case "BigInt64Array":
250
- case "BigUint64Array": {
251
- const TypedArrayConstructor = globalThis[type];
252
- const typedArray = new TypedArrayConstructor(hydrate(value[1]));
253
- hydrated[index] = value[2] !== void 0 ? typedArray.subarray(value[2], value[3]) : typedArray;
254
- break;
255
- }
256
- case "ArrayBuffer": {
257
- const base64 = value[1];
258
- const arraybuffer = decode64(base64);
259
- hydrated[index] = arraybuffer;
260
- break;
261
- }
262
- case "Temporal.Duration":
263
- case "Temporal.Instant":
264
- case "Temporal.PlainDate":
265
- case "Temporal.PlainTime":
266
- case "Temporal.PlainDateTime":
267
- case "Temporal.PlainMonthDay":
268
- case "Temporal.PlainYearMonth":
269
- case "Temporal.ZonedDateTime": {
270
- const temporalName = type.slice(9);
271
- hydrated[index] = Temporal[temporalName].from(value[1]);
272
- break;
273
- }
274
- case "URL": {
275
- const url = new URL(value[1]);
276
- hydrated[index] = url;
277
- break;
278
- }
279
- case "URLSearchParams": {
280
- const url = new URLSearchParams(value[1]);
281
- hydrated[index] = url;
282
- break;
283
- }
284
- default:
285
- throw new Error(`Unknown type ${type}`);
286
- }
287
- } else {
288
- const array = new Array(value.length);
289
- hydrated[index] = array;
290
- for (let i = 0; i < value.length; i += 1) {
291
- const n = value[i];
292
- if (n === HOLE) continue;
293
- array[i] = hydrate(n);
294
- }
295
- }
296
- } else {
297
- const object = {};
298
- hydrated[index] = object;
299
- for (const key in value) {
300
- if (key === "__proto__") {
301
- throw new Error("Cannot parse an object with a `__proto__` property");
302
- }
303
- const n = value[key];
304
- object[key] = hydrate(n);
305
- }
306
- }
307
- return hydrated[index];
308
- }
309
- return hydrate(0);
226
+ if (typeof parsed === "number") return hydrate(parsed, true);
227
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error("Invalid input");
228
+ const values = parsed;
229
+ const hydrated = Array(values.length);
230
+ /**
231
+ * A set of values currently being hydrated with custom revivers,
232
+ * used to detect invalid cyclical dependencies
233
+ * @type {Set<number> | null}
234
+ */
235
+ let hydrating = null;
236
+ /**
237
+ * @param {number} index
238
+ * @returns {any}
239
+ */
240
+ function hydrate(index, standalone = false) {
241
+ if (index === UNDEFINED) return void 0;
242
+ if (index === NAN) return NaN;
243
+ if (index === POSITIVE_INFINITY) return Infinity;
244
+ if (index === NEGATIVE_INFINITY) return -Infinity;
245
+ if (index === NEGATIVE_ZERO) return -0;
246
+ if (standalone || typeof index !== "number") throw new Error(`Invalid input`);
247
+ if (index in hydrated) return hydrated[index];
248
+ const value = values[index];
249
+ if (!value || typeof value !== "object") hydrated[index] = value;
250
+ else if (Array.isArray(value)) if (typeof value[0] === "string") {
251
+ const type = value[0];
252
+ const reviver = revivers && Object.hasOwn(revivers, type) ? revivers[type] : void 0;
253
+ if (reviver) {
254
+ let i = value[1];
255
+ if (typeof i !== "number") i = values.push(value[1]) - 1;
256
+ hydrating ??= /* @__PURE__ */ new Set();
257
+ if (hydrating.has(i)) throw new Error("Invalid circular reference");
258
+ hydrating.add(i);
259
+ hydrated[index] = reviver(hydrate(i));
260
+ hydrating.delete(i);
261
+ return hydrated[index];
262
+ }
263
+ switch (type) {
264
+ case "Date":
265
+ hydrated[index] = new Date(value[1]);
266
+ break;
267
+ case "Set":
268
+ const set = /* @__PURE__ */ new Set();
269
+ hydrated[index] = set;
270
+ for (let i = 1; i < value.length; i += 1) set.add(hydrate(value[i]));
271
+ break;
272
+ case "Map":
273
+ const map = /* @__PURE__ */ new Map();
274
+ hydrated[index] = map;
275
+ for (let i = 1; i < value.length; i += 2) map.set(hydrate(value[i]), hydrate(value[i + 1]));
276
+ break;
277
+ case "RegExp":
278
+ hydrated[index] = new RegExp(value[1], value[2]);
279
+ break;
280
+ case "Object":
281
+ hydrated[index] = Object(value[1]);
282
+ break;
283
+ case "BigInt":
284
+ hydrated[index] = BigInt(value[1]);
285
+ break;
286
+ case "null":
287
+ const obj = Object.create(null);
288
+ hydrated[index] = obj;
289
+ for (let i = 1; i < value.length; i += 2) obj[value[i]] = hydrate(value[i + 1]);
290
+ break;
291
+ case "Int8Array":
292
+ case "Uint8Array":
293
+ case "Uint8ClampedArray":
294
+ case "Int16Array":
295
+ case "Uint16Array":
296
+ case "Int32Array":
297
+ case "Uint32Array":
298
+ case "Float32Array":
299
+ case "Float64Array":
300
+ case "BigInt64Array":
301
+ case "BigUint64Array": {
302
+ if (values[value[1]][0] !== "ArrayBuffer") throw new Error("Invalid data");
303
+ const TypedArrayConstructor = globalThis[type];
304
+ const typedArray = new TypedArrayConstructor(hydrate(value[1]));
305
+ hydrated[index] = value[2] !== void 0 ? typedArray.subarray(value[2], value[3]) : typedArray;
306
+ break;
307
+ }
308
+ case "ArrayBuffer": {
309
+ const base64 = value[1];
310
+ if (typeof base64 !== "string") throw new Error("Invalid ArrayBuffer encoding");
311
+ hydrated[index] = decode64(base64);
312
+ break;
313
+ }
314
+ case "Temporal.Duration":
315
+ case "Temporal.Instant":
316
+ case "Temporal.PlainDate":
317
+ case "Temporal.PlainTime":
318
+ case "Temporal.PlainDateTime":
319
+ case "Temporal.PlainMonthDay":
320
+ case "Temporal.PlainYearMonth":
321
+ case "Temporal.ZonedDateTime": {
322
+ const temporalName = type.slice(9);
323
+ hydrated[index] = Temporal[temporalName].from(value[1]);
324
+ break;
325
+ }
326
+ case "URL":
327
+ hydrated[index] = new URL(value[1]);
328
+ break;
329
+ case "URLSearchParams":
330
+ hydrated[index] = new URLSearchParams(value[1]);
331
+ break;
332
+ default: throw new Error(`Unknown type ${type}`);
333
+ }
334
+ } else if (value[0] === SPARSE) {
335
+ const len = value[1];
336
+ const array = new Array(len);
337
+ hydrated[index] = array;
338
+ for (let i = 2; i < value.length; i += 2) {
339
+ const idx = value[i];
340
+ array[idx] = hydrate(value[i + 1]);
341
+ }
342
+ } else {
343
+ const array = new Array(value.length);
344
+ hydrated[index] = array;
345
+ for (let i = 0; i < value.length; i += 1) {
346
+ const n = value[i];
347
+ if (n === HOLE) continue;
348
+ array[i] = hydrate(n);
349
+ }
350
+ }
351
+ else {
352
+ /** @type {Record<string, any>} */
353
+ const object = {};
354
+ hydrated[index] = object;
355
+ for (const key of Object.keys(value)) {
356
+ if (key === "__proto__") throw new Error("Cannot parse an object with a `__proto__` property");
357
+ const n = value[key];
358
+ object[key] = hydrate(n);
359
+ }
360
+ }
361
+ return hydrated[index];
362
+ }
363
+ return hydrate(0);
310
364
  }
311
365
 
312
- // ../../node_modules/.pnpm/devalue@5.3.2/node_modules/devalue/src/stringify.js
366
+ //#endregion
367
+ //#region ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/stringify.js
368
+ /**
369
+ * Turn a value into a JSON string that can be parsed with `devalue.parse`
370
+ * @param {any} value
371
+ * @param {Record<string, (value: any) => any>} [reducers]
372
+ */
313
373
  function stringify(value, reducers) {
314
- const stringified = [];
315
- const indexes = /* @__PURE__ */ new Map();
316
- const custom = [];
317
- if (reducers) {
318
- for (const key of Object.getOwnPropertyNames(reducers)) {
319
- custom.push({ key, fn: reducers[key] });
320
- }
321
- }
322
- const keys = [];
323
- let p = 0;
324
- function flatten(thing) {
325
- if (typeof thing === "function") {
326
- throw new DevalueError(`Cannot stringify a function`, keys);
327
- }
328
- if (thing === void 0) return UNDEFINED;
329
- if (Number.isNaN(thing)) return NAN;
330
- if (thing === Infinity) return POSITIVE_INFINITY;
331
- if (thing === -Infinity) return NEGATIVE_INFINITY;
332
- if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO;
333
- if (indexes.has(thing)) return indexes.get(thing);
334
- const index2 = p++;
335
- indexes.set(thing, index2);
336
- for (const { key, fn } of custom) {
337
- const value2 = fn(thing);
338
- if (value2) {
339
- stringified[index2] = `["${key}",${flatten(value2)}]`;
340
- return index2;
341
- }
342
- }
343
- let str = "";
344
- if (is_primitive(thing)) {
345
- str = stringify_primitive(thing);
346
- } else {
347
- const type = get_type(thing);
348
- switch (type) {
349
- case "Number":
350
- case "String":
351
- case "Boolean":
352
- str = `["Object",${stringify_primitive(thing)}]`;
353
- break;
354
- case "BigInt":
355
- str = `["BigInt",${thing}]`;
356
- break;
357
- case "Date":
358
- const valid = !isNaN(thing.getDate());
359
- str = `["Date","${valid ? thing.toISOString() : ""}"]`;
360
- break;
361
- case "URL":
362
- str = `["URL",${stringify_string(thing.toString())}]`;
363
- break;
364
- case "URLSearchParams":
365
- str = `["URLSearchParams",${stringify_string(thing.toString())}]`;
366
- break;
367
- case "RegExp":
368
- const { source, flags } = thing;
369
- str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`;
370
- break;
371
- case "Array":
372
- str = "[";
373
- for (let i = 0; i < thing.length; i += 1) {
374
- if (i > 0) str += ",";
375
- if (i in thing) {
376
- keys.push(`[${i}]`);
377
- str += flatten(thing[i]);
378
- keys.pop();
379
- } else {
380
- str += HOLE;
381
- }
382
- }
383
- str += "]";
384
- break;
385
- case "Set":
386
- str = '["Set"';
387
- for (const value2 of thing) {
388
- str += `,${flatten(value2)}`;
389
- }
390
- str += "]";
391
- break;
392
- case "Map":
393
- str = '["Map"';
394
- for (const [key, value2] of thing) {
395
- keys.push(
396
- `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})`
397
- );
398
- str += `,${flatten(key)},${flatten(value2)}`;
399
- keys.pop();
400
- }
401
- str += "]";
402
- break;
403
- case "Int8Array":
404
- case "Uint8Array":
405
- case "Uint8ClampedArray":
406
- case "Int16Array":
407
- case "Uint16Array":
408
- case "Int32Array":
409
- case "Uint32Array":
410
- case "Float32Array":
411
- case "Float64Array":
412
- case "BigInt64Array":
413
- case "BigUint64Array": {
414
- const typedArray = thing;
415
- str = '["' + type + '",' + flatten(typedArray.buffer);
416
- const a = thing.byteOffset;
417
- const b = a + thing.byteLength;
418
- if (a > 0 || b !== typedArray.buffer.byteLength) {
419
- const m = +/(\d+)/.exec(type)[1] / 8;
420
- str += `,${a / m},${b / m}`;
421
- }
422
- str += "]";
423
- break;
424
- }
425
- case "ArrayBuffer": {
426
- const arraybuffer = thing;
427
- const base64 = encode64(arraybuffer);
428
- str = `["ArrayBuffer","${base64}"]`;
429
- break;
430
- }
431
- case "Temporal.Duration":
432
- case "Temporal.Instant":
433
- case "Temporal.PlainDate":
434
- case "Temporal.PlainTime":
435
- case "Temporal.PlainDateTime":
436
- case "Temporal.PlainMonthDay":
437
- case "Temporal.PlainYearMonth":
438
- case "Temporal.ZonedDateTime":
439
- str = `["${type}",${stringify_string(thing.toString())}]`;
440
- break;
441
- default:
442
- if (!is_plain_object(thing)) {
443
- throw new DevalueError(
444
- `Cannot stringify arbitrary non-POJOs`,
445
- keys
446
- );
447
- }
448
- if (enumerable_symbols(thing).length > 0) {
449
- throw new DevalueError(
450
- `Cannot stringify POJOs with symbolic keys`,
451
- keys
452
- );
453
- }
454
- if (Object.getPrototypeOf(thing) === null) {
455
- str = '["null"';
456
- for (const key in thing) {
457
- keys.push(stringify_key(key));
458
- str += `,${stringify_string(key)},${flatten(thing[key])}`;
459
- keys.pop();
460
- }
461
- str += "]";
462
- } else {
463
- str = "{";
464
- let started = false;
465
- for (const key in thing) {
466
- if (started) str += ",";
467
- started = true;
468
- keys.push(stringify_key(key));
469
- str += `${stringify_string(key)}:${flatten(thing[key])}`;
470
- keys.pop();
471
- }
472
- str += "}";
473
- }
474
- }
475
- }
476
- stringified[index2] = str;
477
- return index2;
478
- }
479
- const index = flatten(value);
480
- if (index < 0) return `${index}`;
481
- return `[${stringified.join(",")}]`;
374
+ /** @type {any[]} */
375
+ const stringified = [];
376
+ /** @type {Map<any, number>} */
377
+ const indexes = /* @__PURE__ */ new Map();
378
+ /** @type {Array<{ key: string, fn: (value: any) => any }>} */
379
+ const custom = [];
380
+ if (reducers) for (const key of Object.getOwnPropertyNames(reducers)) custom.push({
381
+ key,
382
+ fn: reducers[key]
383
+ });
384
+ /** @type {string[]} */
385
+ const keys = [];
386
+ let p = 0;
387
+ /** @param {any} thing */
388
+ function flatten(thing) {
389
+ if (thing === void 0) return UNDEFINED;
390
+ if (Number.isNaN(thing)) return NAN;
391
+ if (thing === Infinity) return POSITIVE_INFINITY;
392
+ if (thing === -Infinity) return NEGATIVE_INFINITY;
393
+ if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO;
394
+ if (indexes.has(thing)) return indexes.get(thing);
395
+ const index$1 = p++;
396
+ indexes.set(thing, index$1);
397
+ for (const { key, fn } of custom) {
398
+ const value$1 = fn(thing);
399
+ if (value$1) {
400
+ stringified[index$1] = `["${key}",${flatten(value$1)}]`;
401
+ return index$1;
402
+ }
403
+ }
404
+ if (typeof thing === "function") throw new DevalueError(`Cannot stringify a function`, keys, thing, value);
405
+ let str = "";
406
+ if (is_primitive(thing)) str = stringify_primitive(thing);
407
+ else {
408
+ const type = get_type(thing);
409
+ switch (type) {
410
+ case "Number":
411
+ case "String":
412
+ case "Boolean":
413
+ str = `["Object",${stringify_primitive(thing)}]`;
414
+ break;
415
+ case "BigInt":
416
+ str = `["BigInt",${thing}]`;
417
+ break;
418
+ case "Date":
419
+ str = `["Date","${!isNaN(thing.getDate()) ? thing.toISOString() : ""}"]`;
420
+ break;
421
+ case "URL":
422
+ str = `["URL",${stringify_string(thing.toString())}]`;
423
+ break;
424
+ case "URLSearchParams":
425
+ str = `["URLSearchParams",${stringify_string(thing.toString())}]`;
426
+ break;
427
+ case "RegExp":
428
+ const { source, flags } = thing;
429
+ str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`;
430
+ break;
431
+ case "Array": {
432
+ let mostly_dense = false;
433
+ str = "[";
434
+ for (let i = 0; i < thing.length; i += 1) {
435
+ if (i > 0) str += ",";
436
+ if (Object.hasOwn(thing, i)) {
437
+ keys.push(`[${i}]`);
438
+ str += flatten(thing[i]);
439
+ keys.pop();
440
+ } else if (mostly_dense) str += HOLE;
441
+ else {
442
+ const populated_keys = valid_array_indices(thing);
443
+ const population = populated_keys.length;
444
+ const d = String(thing.length).length;
445
+ if ((thing.length - population) * 3 > 4 + d + population * (d + 1)) {
446
+ str = "[" + SPARSE + "," + thing.length;
447
+ for (let j = 0; j < populated_keys.length; j++) {
448
+ const key = populated_keys[j];
449
+ keys.push(`[${key}]`);
450
+ str += "," + key + "," + flatten(thing[key]);
451
+ keys.pop();
452
+ }
453
+ break;
454
+ } else {
455
+ mostly_dense = true;
456
+ str += HOLE;
457
+ }
458
+ }
459
+ }
460
+ str += "]";
461
+ break;
462
+ }
463
+ case "Set":
464
+ str = "[\"Set\"";
465
+ for (const value$1 of thing) str += `,${flatten(value$1)}`;
466
+ str += "]";
467
+ break;
468
+ case "Map":
469
+ str = "[\"Map\"";
470
+ for (const [key, value$1] of thing) {
471
+ keys.push(`.get(${is_primitive(key) ? stringify_primitive(key) : "..."})`);
472
+ str += `,${flatten(key)},${flatten(value$1)}`;
473
+ keys.pop();
474
+ }
475
+ str += "]";
476
+ break;
477
+ case "Int8Array":
478
+ case "Uint8Array":
479
+ case "Uint8ClampedArray":
480
+ case "Int16Array":
481
+ case "Uint16Array":
482
+ case "Int32Array":
483
+ case "Uint32Array":
484
+ case "Float32Array":
485
+ case "Float64Array":
486
+ case "BigInt64Array":
487
+ case "BigUint64Array": {
488
+ /** @type {import("./types.js").TypedArray} */
489
+ const typedArray = thing;
490
+ str = "[\"" + type + "\"," + flatten(typedArray.buffer);
491
+ const a = thing.byteOffset;
492
+ const b = a + thing.byteLength;
493
+ if (a > 0 || b !== typedArray.buffer.byteLength) {
494
+ const m = +/(\d+)/.exec(type)[1] / 8;
495
+ str += `,${a / m},${b / m}`;
496
+ }
497
+ str += "]";
498
+ break;
499
+ }
500
+ case "ArrayBuffer":
501
+ str = `["ArrayBuffer","${encode64(thing)}"]`;
502
+ break;
503
+ case "Temporal.Duration":
504
+ case "Temporal.Instant":
505
+ case "Temporal.PlainDate":
506
+ case "Temporal.PlainTime":
507
+ case "Temporal.PlainDateTime":
508
+ case "Temporal.PlainMonthDay":
509
+ case "Temporal.PlainYearMonth":
510
+ case "Temporal.ZonedDateTime":
511
+ str = `["${type}",${stringify_string(thing.toString())}]`;
512
+ break;
513
+ default:
514
+ if (!is_plain_object(thing)) throw new DevalueError(`Cannot stringify arbitrary non-POJOs`, keys, thing, value);
515
+ if (enumerable_symbols(thing).length > 0) throw new DevalueError(`Cannot stringify POJOs with symbolic keys`, keys, thing, value);
516
+ if (Object.getPrototypeOf(thing) === null) {
517
+ str = "[\"null\"";
518
+ for (const key of Object.keys(thing)) {
519
+ if (key === "__proto__") throw new DevalueError(`Cannot stringify objects with __proto__ keys`, keys, thing, value);
520
+ keys.push(stringify_key(key));
521
+ str += `,${stringify_string(key)},${flatten(thing[key])}`;
522
+ keys.pop();
523
+ }
524
+ str += "]";
525
+ } else {
526
+ str = "{";
527
+ let started = false;
528
+ for (const key of Object.keys(thing)) {
529
+ if (key === "__proto__") throw new DevalueError(`Cannot stringify objects with __proto__ keys`, keys, thing, value);
530
+ if (started) str += ",";
531
+ started = true;
532
+ keys.push(stringify_key(key));
533
+ str += `${stringify_string(key)}:${flatten(thing[key])}`;
534
+ keys.pop();
535
+ }
536
+ str += "}";
537
+ }
538
+ }
539
+ }
540
+ stringified[index$1] = str;
541
+ return index$1;
542
+ }
543
+ const index = flatten(value);
544
+ if (index < 0) return `${index}`;
545
+ return `[${stringified.join(",")}]`;
482
546
  }
547
+ /**
548
+ * @param {any} thing
549
+ * @returns {string}
550
+ */
483
551
  function stringify_primitive(thing) {
484
- const type = typeof thing;
485
- if (type === "string") return stringify_string(thing);
486
- if (thing instanceof String) return stringify_string(thing.toString());
487
- if (thing === void 0) return UNDEFINED.toString();
488
- if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO.toString();
489
- if (type === "bigint") return `["BigInt","${thing}"]`;
490
- return String(thing);
552
+ const type = typeof thing;
553
+ if (type === "string") return stringify_string(thing);
554
+ if (thing instanceof String) return stringify_string(thing.toString());
555
+ if (thing === void 0) return UNDEFINED.toString();
556
+ if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO.toString();
557
+ if (type === "bigint") return `["BigInt","${thing}"]`;
558
+ return String(thing);
491
559
  }
492
560
 
493
- // ../miniflare/src/workers/core/devalue.ts
494
- import assert from "node:assert";
495
- import { Buffer } from "node:buffer";
496
- var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [
497
- DataView,
498
- Int8Array,
499
- Uint8Array,
500
- Uint8ClampedArray,
501
- Int16Array,
502
- Uint16Array,
503
- Int32Array,
504
- Uint32Array,
505
- Float32Array,
506
- Float64Array,
507
- BigInt64Array,
508
- BigUint64Array
561
+ //#endregion
562
+ //#region ../miniflare/src/workers/core/devalue.ts
563
+ const ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [
564
+ DataView,
565
+ Int8Array,
566
+ Uint8Array,
567
+ Uint8ClampedArray,
568
+ Int16Array,
569
+ Uint16Array,
570
+ Int32Array,
571
+ Uint32Array,
572
+ Float32Array,
573
+ Float64Array,
574
+ BigInt64Array,
575
+ BigUint64Array
509
576
  ];
510
- var ALLOWED_ERROR_CONSTRUCTORS = [
511
- EvalError,
512
- RangeError,
513
- ReferenceError,
514
- SyntaxError,
515
- TypeError,
516
- URIError,
517
- Error
518
- // `Error` last so more specific error subclasses preferred
577
+ const ALLOWED_ERROR_CONSTRUCTORS = [
578
+ EvalError,
579
+ RangeError,
580
+ ReferenceError,
581
+ SyntaxError,
582
+ TypeError,
583
+ URIError,
584
+ Error
519
585
  ];
520
- var structuredSerializableReducers = {
521
- ArrayBuffer(value) {
522
- if (value instanceof ArrayBuffer) {
523
- return [Buffer.from(value).toString("base64")];
524
- }
525
- },
526
- ArrayBufferView(value) {
527
- if (ArrayBuffer.isView(value)) {
528
- return [
529
- value.constructor.name,
530
- value.buffer,
531
- value.byteOffset,
532
- value.byteLength
533
- ];
534
- }
535
- },
536
- RegExp(value) {
537
- if (value instanceof RegExp) {
538
- const { source, flags } = value;
539
- const encoded = Buffer.from(source).toString("base64");
540
- return flags ? ["RegExp", encoded, flags] : ["RegExp", encoded];
541
- }
542
- },
543
- Error(value) {
544
- for (const ctor of ALLOWED_ERROR_CONSTRUCTORS) {
545
- if (value instanceof ctor && value.name === ctor.name) {
546
- return [value.name, value.message, value.stack, value.cause];
547
- }
548
- }
549
- if (value instanceof Error) {
550
- return ["Error", value.message, value.stack, value.cause];
551
- }
552
- }
586
+ const structuredSerializableReducers = {
587
+ ArrayBuffer(value) {
588
+ if (value instanceof ArrayBuffer) return [Buffer.from(value).toString("base64")];
589
+ },
590
+ ArrayBufferView(value) {
591
+ if (ArrayBuffer.isView(value)) return [
592
+ value.constructor.name,
593
+ value.buffer,
594
+ value.byteOffset,
595
+ value.byteLength
596
+ ];
597
+ },
598
+ RegExp(value) {
599
+ if (value instanceof RegExp) {
600
+ const { source, flags } = value;
601
+ const encoded = Buffer.from(source).toString("base64");
602
+ return flags ? [
603
+ "RegExp",
604
+ encoded,
605
+ flags
606
+ ] : ["RegExp", encoded];
607
+ }
608
+ },
609
+ Error(value) {
610
+ for (const ctor of ALLOWED_ERROR_CONSTRUCTORS) if (value instanceof ctor && value.name === ctor.name) return [
611
+ value.name,
612
+ value.message,
613
+ value.stack,
614
+ value.cause
615
+ ];
616
+ if (value instanceof Error) return [
617
+ "Error",
618
+ value.message,
619
+ value.stack,
620
+ value.cause
621
+ ];
622
+ }
553
623
  };
554
- var structuredSerializableRevivers = {
555
- ArrayBuffer(value) {
556
- assert(Array.isArray(value));
557
- const [encoded] = value;
558
- assert(typeof encoded === "string");
559
- const view = Buffer.from(encoded, "base64");
560
- return view.buffer.slice(
561
- view.byteOffset,
562
- view.byteOffset + view.byteLength
563
- );
564
- },
565
- ArrayBufferView(value) {
566
- assert(Array.isArray(value));
567
- const [name, buffer, byteOffset, byteLength] = value;
568
- assert(typeof name === "string");
569
- assert(buffer instanceof ArrayBuffer);
570
- assert(typeof byteOffset === "number");
571
- assert(typeof byteLength === "number");
572
- const ctor = globalThis[name];
573
- assert(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor));
574
- let length = byteLength;
575
- if ("BYTES_PER_ELEMENT" in ctor) length /= ctor.BYTES_PER_ELEMENT;
576
- return new ctor(buffer, byteOffset, length);
577
- },
578
- RegExp(value) {
579
- assert(Array.isArray(value));
580
- const [name, encoded, flags] = value;
581
- assert(typeof name === "string");
582
- assert(typeof encoded === "string");
583
- const source = Buffer.from(encoded, "base64").toString("utf-8");
584
- return new RegExp(source, flags);
585
- },
586
- Error(value) {
587
- assert(Array.isArray(value));
588
- const [name, message, stack, cause] = value;
589
- assert(typeof name === "string");
590
- assert(typeof message === "string");
591
- assert(stack === void 0 || typeof stack === "string");
592
- const ctor = globalThis[name];
593
- assert(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor));
594
- const error = new ctor(message, { cause });
595
- error.stack = stack;
596
- return error;
597
- }
624
+ const structuredSerializableRevivers = {
625
+ ArrayBuffer(value) {
626
+ assert(Array.isArray(value));
627
+ const [encoded] = value;
628
+ assert(typeof encoded === "string");
629
+ const view = Buffer.from(encoded, "base64");
630
+ return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
631
+ },
632
+ ArrayBufferView(value) {
633
+ assert(Array.isArray(value));
634
+ const [name, buffer, byteOffset, byteLength] = value;
635
+ assert(typeof name === "string");
636
+ assert(buffer instanceof ArrayBuffer);
637
+ assert(typeof byteOffset === "number");
638
+ assert(typeof byteLength === "number");
639
+ const ctor = globalThis[name];
640
+ assert(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor));
641
+ let length = byteLength;
642
+ if ("BYTES_PER_ELEMENT" in ctor) length /= ctor.BYTES_PER_ELEMENT;
643
+ return new ctor(buffer, byteOffset, length);
644
+ },
645
+ RegExp(value) {
646
+ assert(Array.isArray(value));
647
+ const [name, encoded, flags] = value;
648
+ assert(typeof name === "string");
649
+ assert(typeof encoded === "string");
650
+ const source = Buffer.from(encoded, "base64").toString("utf-8");
651
+ return new RegExp(source, flags);
652
+ },
653
+ Error(value) {
654
+ assert(Array.isArray(value));
655
+ const [name, message, stack, cause] = value;
656
+ assert(typeof name === "string");
657
+ assert(typeof message === "string");
658
+ assert(stack === void 0 || typeof stack === "string");
659
+ const ctor = globalThis[name];
660
+ assert(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor));
661
+ const error = new ctor(message, { cause });
662
+ error.stack = stack;
663
+ return error;
664
+ }
598
665
  };
599
666
 
600
- // src/shared/chunking-socket.ts
601
- import assert2 from "node:assert";
602
- import { Buffer as Buffer2 } from "node:buffer";
603
- function createChunkingSocket(socket, maxChunkByteLength = 1048576) {
604
- const listeners = [];
605
- const decoder = new TextDecoder();
606
- let chunks;
607
- socket.on((message) => {
608
- if (typeof message === "string") {
609
- if (chunks !== void 0) {
610
- assert2.strictEqual(message, "", "Expected end-of-chunks");
611
- message = chunks + decoder.decode();
612
- chunks = void 0;
613
- }
614
- for (const listener of listeners) {
615
- listener(message);
616
- }
617
- } else {
618
- chunks ??= "";
619
- chunks += decoder.decode(message, { stream: true });
620
- }
621
- });
622
- return {
623
- post(value) {
624
- if (Buffer2.byteLength(value) > maxChunkByteLength) {
625
- const encoded = Buffer2.from(value);
626
- for (let i = 0; i < encoded.byteLength; i += maxChunkByteLength) {
627
- socket.post(encoded.subarray(i, i + maxChunkByteLength));
628
- }
629
- socket.post("");
630
- } else {
631
- socket.post(value);
632
- }
633
- },
634
- on(listener) {
635
- listeners.push(listener);
636
- }
637
- };
638
- }
639
-
640
- // src/worker/index.ts
641
- export * from "__VITEST_POOL_WORKERS_USER_OBJECT";
667
+ //#endregion
668
+ //#region src/worker/index.ts
642
669
  function structuredSerializableStringify(value) {
643
- return stringify(value, structuredSerializableReducers);
670
+ return stringify(value, structuredSerializableReducers);
644
671
  }
645
672
  function structuredSerializableParse(value) {
646
- return parse(value, structuredSerializableRevivers);
673
+ return parse(value, structuredSerializableRevivers);
647
674
  }
648
- globalThis.Buffer = Buffer3;
649
- globalThis.process = process;
650
- process.argv = [];
651
- var cwd;
675
+ globalThis.BroadcastChannel = class {
676
+ constructor(name) {
677
+ this.name = name;
678
+ }
679
+ postMessage(_message) {}
680
+ close() {}
681
+ addEventListener(_type, _listener) {}
682
+ removeEventListener(_type, _listener) {}
683
+ onmessage = null;
684
+ onmessageerror = null;
685
+ };
686
+ let cwd;
652
687
  process.cwd = () => {
653
- assert3(cwd !== void 0, "Expected cwd to be set");
654
- return cwd;
688
+ assert(cwd !== void 0, "Expected cwd to be set");
689
+ return cwd;
655
690
  };
656
- Object.setPrototypeOf(process, events.EventEmitter.prototype);
657
691
  globalThis.__console = console;
658
692
  function getCallerFileName(of) {
659
- const originalStackTraceLimit = Error.stackTraceLimit;
660
- const originalPrepareStackTrace = Error.prepareStackTrace;
661
- try {
662
- let fileName = null;
663
- Error.stackTraceLimit = 1;
664
- Error.prepareStackTrace = (_error, callSites) => {
665
- fileName = callSites[0]?.getFileName();
666
- return "";
667
- };
668
- const error = {};
669
- Error.captureStackTrace(error, of);
670
- void error.stack;
671
- return fileName;
672
- } finally {
673
- Error.stackTraceLimit = originalStackTraceLimit;
674
- Error.prepareStackTrace = originalPrepareStackTrace;
675
- }
693
+ const originalStackTraceLimit = Error.stackTraceLimit;
694
+ const originalPrepareStackTrace = Error.prepareStackTrace;
695
+ try {
696
+ let fileName = null;
697
+ Error.stackTraceLimit = 1;
698
+ Error.prepareStackTrace = (_error, callSites) => {
699
+ fileName = callSites[0]?.getFileName();
700
+ return "";
701
+ };
702
+ const error = {};
703
+ Error.captureStackTrace(error, of);
704
+ error.stack;
705
+ return fileName;
706
+ } finally {
707
+ Error.stackTraceLimit = originalStackTraceLimit;
708
+ Error.prepareStackTrace = originalPrepareStackTrace;
709
+ }
676
710
  }
677
- var originalSetTimeout = globalThis.setTimeout;
678
- var originalClearTimeout = globalThis.clearTimeout;
679
- var timeoutPromiseResolves = /* @__PURE__ */ new Map();
680
- var monkeypatchedSetTimeout = (...args) => {
681
- const [callback, delay, ...restArgs] = args;
682
- const callbackName = args[0]?.name ?? "";
683
- const callerFileName = getCallerFileName(monkeypatchedSetTimeout);
684
- const fromVitest = /\/node_modules\/(\.store\/)?vitest/.test(
685
- callerFileName ?? ""
686
- );
687
- if (!fromVitest || delay) {
688
- return originalSetTimeout.apply(globalThis, args);
689
- }
690
- if (callbackName === "NOOP") {
691
- return -0.5;
692
- }
693
- let promiseResolve;
694
- const promise = new Promise((resolve) => {
695
- promiseResolve = resolve;
696
- });
697
- assert3(promiseResolve !== void 0);
698
- registerHandlerAndGlobalWaitUntil(promise);
699
- const id = originalSetTimeout.call(globalThis, () => {
700
- promiseResolve?.();
701
- callback?.(...restArgs);
702
- });
703
- timeoutPromiseResolves.set(id, promiseResolve);
704
- return id;
711
+ const originalSetTimeout = globalThis.setTimeout;
712
+ const originalClearTimeout = globalThis.clearTimeout;
713
+ const timeoutPromiseResolves = /* @__PURE__ */ new Map();
714
+ const monkeypatchedSetTimeout = (...args) => {
715
+ const [callback, delay, ...restArgs] = args;
716
+ const callbackName = args[0]?.name ?? "";
717
+ const callerFileName = getCallerFileName(monkeypatchedSetTimeout);
718
+ if (!(/\/node_modules\/(\.pnpm\/|\.store\/)?vitest/.test(callerFileName ?? "") || /\/packages\/vitest\/dist/.test(callerFileName ?? "")) || delay) return originalSetTimeout.apply(globalThis, args);
719
+ if (callbackName === "NOOP") return -.5;
720
+ let promiseResolve;
721
+ const promise = new Promise((resolve) => {
722
+ promiseResolve = resolve;
723
+ });
724
+ assert(promiseResolve !== void 0);
725
+ registerHandlerAndGlobalWaitUntil(promise);
726
+ const id = originalSetTimeout.call(globalThis, () => {
727
+ promiseResolve?.();
728
+ callback?.(...restArgs);
729
+ });
730
+ timeoutPromiseResolves.set(id, promiseResolve);
731
+ return id;
705
732
  };
706
733
  globalThis.setTimeout = monkeypatchedSetTimeout;
707
734
  globalThis.clearTimeout = (...args) => {
708
- const id = args[0];
709
- if (id === -0.5) {
710
- return;
711
- }
712
- const maybePromiseResolve = timeoutPromiseResolves.get(id);
713
- timeoutPromiseResolves.delete(id);
714
- maybePromiseResolve?.();
715
- return originalClearTimeout.apply(globalThis, args);
735
+ const id = args[0];
736
+ if (id === -.5) return;
737
+ const maybePromiseResolve = timeoutPromiseResolves.get(id);
738
+ timeoutPromiseResolves.delete(id);
739
+ maybePromiseResolve?.();
740
+ return originalClearTimeout.apply(globalThis, args);
716
741
  };
717
742
  function isDifferentIOContextError(e) {
718
- return e instanceof Error && e.message.startsWith("Cannot perform I/O on behalf of a different");
743
+ return e instanceof Error && e.message.startsWith("Cannot perform I/O on behalf of a different");
719
744
  }
720
- var WebSocketMessagePort = class extends events.EventEmitter {
721
- constructor(socket) {
722
- super();
723
- this.socket = socket;
724
- this.#chunkingSocket = createChunkingSocket({
725
- post(message) {
726
- socket.send(message);
727
- },
728
- on(listener) {
729
- socket.addEventListener("message", (event) => {
730
- listener(event.data);
731
- });
732
- }
733
- });
734
- this.#chunkingSocket.on((message) => {
735
- const parsed = structuredSerializableParse(message);
736
- this.emit("message", parsed);
737
- });
738
- socket.accept();
739
- }
740
- #chunkingSocket;
741
- postMessage(data) {
742
- const stringified = structuredSerializableStringify(data);
743
- try {
744
- if (this.socket.readyState === WebSocket.READY_STATE_OPEN) {
745
- this.#chunkingSocket.post(stringified);
746
- }
747
- } catch (error) {
748
- if (isDifferentIOContextError(error)) {
749
- const promise = runInRunnerObject(internalEnv, () => {
750
- this.#chunkingSocket.post(stringified);
751
- }).catch((e) => {
752
- __console.error("Error sending to pool inside runner:", e, data);
753
- });
754
- registerHandlerAndGlobalWaitUntil(promise);
755
- } else {
756
- __console.error("Error sending to pool:", error, data);
757
- }
758
- }
759
- }
760
- };
761
- function reduceError(e) {
762
- return {
763
- name: e?.name,
764
- message: e?.message ?? String(e),
765
- stack: e?.stack,
766
- cause: e?.cause === void 0 ? void 0 : reduceError(e.cause)
767
- };
768
- }
769
- var patchedFunction = false;
745
+ let patchedFunction = false;
770
746
  function ensurePatchedFunction(unsafeEval) {
771
- if (patchedFunction) {
772
- return;
773
- }
774
- patchedFunction = true;
775
- globalThis.Function = new Proxy(globalThis.Function, {
776
- construct(_target, args, _newTarget) {
777
- const script = args.pop();
778
- return unsafeEval.newFunction(script, "anonymous", ...args);
779
- }
780
- });
747
+ if (patchedFunction) return;
748
+ patchedFunction = true;
749
+ globalThis.Function = new Proxy(globalThis.Function, { construct(_target, args, _newTarget) {
750
+ const script = args.pop();
751
+ return unsafeEval.newFunction(script, "anonymous", ...args);
752
+ } });
781
753
  }
782
754
  function applyDefines() {
783
- for (const [key, value] of Object.entries(defines)) {
784
- const segments = key.split(".");
785
- let target = globalThis;
786
- for (let i = 0; i < segments.length; i++) {
787
- const segment = segments[i];
788
- if (i === segments.length - 1) {
789
- target[segment] = value;
790
- } else {
791
- target = target[segment] ??= {};
792
- }
793
- }
794
- }
755
+ for (const [key, value] of Object.entries(defines)) {
756
+ const segments = key.split(".");
757
+ let target = globalThis;
758
+ for (let i = 0; i < segments.length; i++) {
759
+ const segment = segments[i];
760
+ if (i === segments.length - 1) target[segment] = value;
761
+ else target = target[segment] ??= {};
762
+ }
763
+ }
795
764
  }
796
- var __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__ = class {
797
- executor;
798
- constructor(_state, env) {
799
- vm._setUnsafeEval(env.__VITEST_POOL_WORKERS_UNSAFE_EVAL);
800
- ensurePatchedFunction(env.__VITEST_POOL_WORKERS_UNSAFE_EVAL);
801
- setEnv(env);
802
- applyDefines();
803
- }
804
- async handleVitestRunRequest(request) {
805
- assert3.strictEqual(request.headers.get("Upgrade"), "websocket");
806
- const { 0: poolSocket, 1: poolResponseSocket } = new WebSocketPair();
807
- const workerDataHeader = request.headers.get("MF-Vitest-Worker-Data");
808
- assert3(workerDataHeader !== null);
809
- const wd = structuredSerializableParse(workerDataHeader);
810
- assert3(typeof wd === "object" && wd !== null);
811
- assert3("filePath" in wd && typeof wd.filePath === "string");
812
- assert3("name" in wd && typeof wd.name === "string");
813
- assert3("data" in wd && typeof wd.data === "object" && wd.data !== null);
814
- assert3("cwd" in wd && typeof wd.cwd === "string");
815
- cwd = wd.cwd;
816
- const port = new WebSocketMessagePort(poolSocket);
817
- try {
818
- const module = await import(wd.filePath);
819
- const { VitestExecutor } = await import("vitest/execute");
820
- const originalResolveUrl = VitestExecutor.prototype.resolveUrl;
821
- const that = this;
822
- VitestExecutor.prototype.resolveUrl = function(...args) {
823
- that.executor = this;
824
- return originalResolveUrl.apply(this, args);
825
- };
826
- wd.data.port = port;
827
- module[wd.name](wd.data).then(() => {
828
- poolSocket.close(1e3, "Done");
829
- }).catch((e) => {
830
- port.postMessage({ vitestPoolWorkersError: e });
831
- const error = reduceError(e);
832
- __console.error("Error running worker:", error.stack);
833
- poolSocket.close(1011, "Internal Error");
834
- });
835
- } catch (e) {
836
- const error = reduceError(e);
837
- __console.error("Error initialising worker:", error.stack);
838
- return Response.json(error, {
839
- status: 500,
840
- headers: { "MF-Experimental-Error-Stack": "true" }
841
- });
842
- }
843
- return new Response(null, { status: 101, webSocket: poolResponseSocket });
844
- }
845
- async fetch(request) {
846
- const response = await maybeHandleRunRequest(request, this);
847
- if (response !== void 0) {
848
- return response;
849
- }
850
- return this.handleVitestRunRequest(request);
851
- }
765
+ var __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__ = class extends DurableObject {
766
+ constructor(_state, doEnv) {
767
+ super(_state, doEnv);
768
+ vm._setUnsafeEval(doEnv.__VITEST_POOL_WORKERS_UNSAFE_EVAL);
769
+ ensurePatchedFunction(doEnv.__VITEST_POOL_WORKERS_UNSAFE_EVAL);
770
+ applyDefines();
771
+ }
772
+ async handleVitestRunRequest(request) {
773
+ assert.strictEqual(request.headers.get("Upgrade"), "websocket");
774
+ const { 0: poolSocket, 1: poolResponseSocket } = new WebSocketPair();
775
+ const workerDataHeader = request.headers.get("MF-Vitest-Worker-Data");
776
+ assert(workerDataHeader);
777
+ const wd = structuredSerializableParse(workerDataHeader);
778
+ assert(wd && typeof wd === "object" && "cwd" in wd && typeof wd.cwd === "string");
779
+ cwd = wd.cwd;
780
+ const { init, runBaseTests, setupEnvironment } = await import("vitest/worker");
781
+ poolSocket.accept();
782
+ init({
783
+ post: (response) => {
784
+ try {
785
+ poolSocket.send(structuredSerializableStringify(response));
786
+ } catch (error) {
787
+ if (isDifferentIOContextError(error)) registerHandlerAndGlobalWaitUntil(runInRunnerObject(() => {
788
+ poolSocket.send(structuredSerializableStringify(response));
789
+ }).catch((e) => {
790
+ __console.error("Error sending to pool inside runner:", e, response);
791
+ }));
792
+ else __console.error("Error sending to pool:", error, response);
793
+ }
794
+ },
795
+ on: (callback) => {
796
+ poolSocket.addEventListener("message", (m) => {
797
+ callback(structuredSerializableParse(m.data));
798
+ });
799
+ },
800
+ runTests: (state, traces) => runBaseTests("run", state, traces),
801
+ collectTests: (state, traces) => runBaseTests("collect", state, traces),
802
+ setup: setupEnvironment
803
+ });
804
+ return new Response(null, {
805
+ status: 101,
806
+ webSocket: poolResponseSocket
807
+ });
808
+ }
809
+ async fetch(request) {
810
+ const response = await maybeHandleRunRequest(request, this);
811
+ if (response !== void 0) return response;
812
+ return this.handleVitestRunRequest(request);
813
+ }
852
814
  };
853
815
  var worker_default = createWorkerEntrypointWrapper("default");
854
- export {
855
- __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__,
856
- worker_default as default
857
- };
858
- //# sourceMappingURL=index.mjs.map
816
+
817
+ //#endregion
818
+ export { __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__, worker_default as default };
819
+ //# sourceMappingURL=index.mjs.map