@vitest/browser 4.0.0-beta.9 → 4.0.1

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 (42) hide show
  1. package/README.md +6 -14
  2. package/context.d.ts +86 -29
  3. package/context.js +3 -2
  4. package/dist/client/.vite/manifest.json +6 -6
  5. package/dist/client/__vitest__/assets/index-COTh6lXR.css +1 -0
  6. package/dist/client/__vitest__/assets/index-DOkKC3NI.js +53 -0
  7. package/dist/client/__vitest__/index.html +2 -2
  8. package/dist/client/__vitest_browser__/orchestrator-CFVVvVT1.js +313 -0
  9. package/dist/client/__vitest_browser__/tester-BNxij3za.js +2133 -0
  10. package/dist/client/__vitest_browser__/{utils-FY_Qin7d.js → utils-uxqdqUz8.js} +48 -24
  11. package/dist/client/orchestrator.html +2 -2
  12. package/dist/client/tester/tester.html +2 -2
  13. package/dist/client.js +1 -1
  14. package/dist/context.js +80 -19
  15. package/dist/expect-element.js +14 -14
  16. package/dist/index-BnLTaCRv.js +6 -0
  17. package/dist/index.d.ts +64 -165
  18. package/dist/index.js +572 -1431
  19. package/dist/{locators/index.d.ts → locators.d.ts} +27 -3
  20. package/dist/locators.js +1 -0
  21. package/dist/state.js +0 -1
  22. package/dist/types.d.ts +0 -1
  23. package/jest-dom.d.ts +5 -5
  24. package/matchers.d.ts +2 -2
  25. package/package.json +18 -54
  26. package/utils.d.ts +5 -5
  27. package/dist/client/__vitest__/assets/index-CBcuRGkf.js +0 -57
  28. package/dist/client/__vitest__/assets/index-KbpJLW--.css +0 -1
  29. package/dist/client/__vitest_browser__/orchestrator-C2rrmv36.js +0 -3198
  30. package/dist/client/__vitest_browser__/tester-mSVktQ7a.js +0 -3282
  31. package/dist/index-B7Hfmz-h.js +0 -1
  32. package/dist/locators/index.js +0 -1
  33. package/dist/locators/playwright.js +0 -1
  34. package/dist/locators/preview.js +0 -1
  35. package/dist/locators/webdriverio.js +0 -1
  36. package/dist/providers.js +0 -47
  37. package/dist/public-utils-Kx5DUGWa.js +0 -6
  38. package/dist/utils.js +0 -1
  39. package/dist/webdriver-AHRa6U3j.js +0 -517
  40. package/providers/playwright.d.ts +0 -97
  41. package/providers/webdriverio.d.ts +0 -35
  42. package/providers.d.ts +0 -7
@@ -1,3198 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import { g as getDefaultExportFromCjs, a as getBrowserState, b as getConfig, r as relative } from "./utils-FY_Qin7d.js";
5
- import { channel, globalChannel, client } from "@vitest/browser/client";
6
- function toArray(array) {
7
- if (array === null || array === void 0) {
8
- array = [];
9
- }
10
- if (Array.isArray(array)) {
11
- return array;
12
- }
13
- return [array];
14
- }
15
- function isObject(item) {
16
- return item != null && typeof item === "object" && !Array.isArray(item);
17
- }
18
- function objectAttr(source, path, defaultValue = void 0) {
19
- const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
20
- let result = source;
21
- for (const p2 of paths) {
22
- result = new Object(result)[p2];
23
- if (result === void 0) {
24
- return defaultValue;
25
- }
26
- }
27
- return result;
28
- }
29
- function createDefer() {
30
- let resolve2 = null;
31
- let reject = null;
32
- const p2 = new Promise((_resolve, _reject) => {
33
- resolve2 = _resolve;
34
- reject = _reject;
35
- });
36
- p2.resolve = resolve2;
37
- p2.reject = reject;
38
- return p2;
39
- }
40
- function isNegativeNaN(val) {
41
- if (!Number.isNaN(val)) {
42
- return false;
43
- }
44
- const f64 = new Float64Array(1);
45
- f64[0] = val;
46
- const u32 = new Uint32Array(f64.buffer);
47
- const isNegative = u32[1] >>> 31 === 1;
48
- return isNegative;
49
- }
50
- var f = {
51
- reset: [0, 0],
52
- bold: [1, 22, "\x1B[22m\x1B[1m"],
53
- dim: [2, 22, "\x1B[22m\x1B[2m"],
54
- italic: [3, 23],
55
- underline: [4, 24],
56
- inverse: [7, 27],
57
- hidden: [8, 28],
58
- strikethrough: [9, 29],
59
- black: [30, 39],
60
- red: [31, 39],
61
- green: [32, 39],
62
- yellow: [33, 39],
63
- blue: [34, 39],
64
- magenta: [35, 39],
65
- cyan: [36, 39],
66
- white: [37, 39],
67
- gray: [90, 39],
68
- bgBlack: [40, 49],
69
- bgRed: [41, 49],
70
- bgGreen: [42, 49],
71
- bgYellow: [43, 49],
72
- bgBlue: [44, 49],
73
- bgMagenta: [45, 49],
74
- bgCyan: [46, 49],
75
- bgWhite: [47, 49],
76
- blackBright: [90, 39],
77
- redBright: [91, 39],
78
- greenBright: [92, 39],
79
- yellowBright: [93, 39],
80
- blueBright: [94, 39],
81
- magentaBright: [95, 39],
82
- cyanBright: [96, 39],
83
- whiteBright: [97, 39],
84
- bgBlackBright: [100, 49],
85
- bgRedBright: [101, 49],
86
- bgGreenBright: [102, 49],
87
- bgYellowBright: [103, 49],
88
- bgBlueBright: [104, 49],
89
- bgMagentaBright: [105, 49],
90
- bgCyanBright: [106, 49],
91
- bgWhiteBright: [107, 49]
92
- }, h = Object.entries(f);
93
- function a(n) {
94
- return String(n);
95
- }
96
- a.open = "";
97
- a.close = "";
98
- function C(n = false) {
99
- let e = typeof process != "undefined" ? process : void 0, i = (e == null ? void 0 : e.env) || {}, g = (e == null ? void 0 : e.argv) || [];
100
- return !("NO_COLOR" in i || g.includes("--no-color")) && ("FORCE_COLOR" in i || g.includes("--color") || (e == null ? void 0 : e.platform) === "win32" || n && i.TERM !== "dumb" || "CI" in i) || typeof window != "undefined" && !!window.chrome;
101
- }
102
- function p(n = false) {
103
- let e = C(n), i = (r, t, c, o) => {
104
- let l = "", s = 0;
105
- do
106
- l += r.substring(s, o) + c, s = o + t.length, o = r.indexOf(t, s);
107
- while (~o);
108
- return l + r.substring(s);
109
- }, g = (r, t, c = r) => {
110
- let o = (l) => {
111
- let s = String(l), b = s.indexOf(t, r.length);
112
- return ~b ? r + i(s, t, c, b) + t : r + s + t;
113
- };
114
- return o.open = r, o.close = t, o;
115
- }, u = {
116
- isColorSupported: e
117
- }, d = (r) => `\x1B[${r}m`;
118
- for (let [r, t] of h)
119
- u[r] = e ? g(
120
- d(t[0]),
121
- d(t[1]),
122
- t[2]
123
- ) : a;
124
- return u;
125
- }
126
- p();
127
- const ansiColors = {
128
- bold: ["1", "22"],
129
- dim: ["2", "22"],
130
- italic: ["3", "23"],
131
- underline: ["4", "24"],
132
- // 5 & 6 are blinking
133
- inverse: ["7", "27"],
134
- hidden: ["8", "28"],
135
- strike: ["9", "29"],
136
- // 10-20 are fonts
137
- // 21-29 are resets for 1-9
138
- black: ["30", "39"],
139
- red: ["31", "39"],
140
- green: ["32", "39"],
141
- yellow: ["33", "39"],
142
- blue: ["34", "39"],
143
- magenta: ["35", "39"],
144
- cyan: ["36", "39"],
145
- white: ["37", "39"],
146
- brightblack: ["30;1", "39"],
147
- brightred: ["31;1", "39"],
148
- brightgreen: ["32;1", "39"],
149
- brightyellow: ["33;1", "39"],
150
- brightblue: ["34;1", "39"],
151
- brightmagenta: ["35;1", "39"],
152
- brightcyan: ["36;1", "39"],
153
- brightwhite: ["37;1", "39"],
154
- grey: ["90", "39"]
155
- };
156
- const styles = {
157
- special: "cyan",
158
- number: "yellow",
159
- bigint: "yellow",
160
- boolean: "yellow",
161
- undefined: "grey",
162
- null: "bold",
163
- string: "green",
164
- symbol: "green",
165
- date: "magenta",
166
- regexp: "red"
167
- };
168
- const truncator = "…";
169
- function colorise(value, styleType) {
170
- const color = ansiColors[styles[styleType]] || ansiColors[styleType] || "";
171
- if (!color) {
172
- return String(value);
173
- }
174
- return `\x1B[${color[0]}m${String(value)}\x1B[${color[1]}m`;
175
- }
176
- function normaliseOptions({
177
- showHidden = false,
178
- depth = 2,
179
- colors = false,
180
- customInspect = true,
181
- showProxy = false,
182
- maxArrayLength = Infinity,
183
- breakLength = Infinity,
184
- seen = [],
185
- // eslint-disable-next-line no-shadow
186
- truncate: truncate2 = Infinity,
187
- stylize = String
188
- } = {}, inspect2) {
189
- const options = {
190
- showHidden: Boolean(showHidden),
191
- depth: Number(depth),
192
- colors: Boolean(colors),
193
- customInspect: Boolean(customInspect),
194
- showProxy: Boolean(showProxy),
195
- maxArrayLength: Number(maxArrayLength),
196
- breakLength: Number(breakLength),
197
- truncate: Number(truncate2),
198
- seen,
199
- inspect: inspect2,
200
- stylize
201
- };
202
- if (options.colors) {
203
- options.stylize = colorise;
204
- }
205
- return options;
206
- }
207
- function isHighSurrogate(char) {
208
- return char >= "\uD800" && char <= "\uDBFF";
209
- }
210
- function truncate(string, length, tail = truncator) {
211
- string = String(string);
212
- const tailLength = tail.length;
213
- const stringLength = string.length;
214
- if (tailLength > length && stringLength > tailLength) {
215
- return tail;
216
- }
217
- if (stringLength > length && stringLength > tailLength) {
218
- let end = length - tailLength;
219
- if (end > 0 && isHighSurrogate(string[end - 1])) {
220
- end = end - 1;
221
- }
222
- return `${string.slice(0, end)}${tail}`;
223
- }
224
- return string;
225
- }
226
- function inspectList(list, options, inspectItem, separator = ", ") {
227
- inspectItem = inspectItem || options.inspect;
228
- const size = list.length;
229
- if (size === 0)
230
- return "";
231
- const originalLength = options.truncate;
232
- let output = "";
233
- let peek = "";
234
- let truncated = "";
235
- for (let i = 0; i < size; i += 1) {
236
- const last = i + 1 === list.length;
237
- const secondToLast = i + 2 === list.length;
238
- truncated = `${truncator}(${list.length - i})`;
239
- const value = list[i];
240
- options.truncate = originalLength - output.length - (last ? 0 : separator.length);
241
- const string = peek || inspectItem(value, options) + (last ? "" : separator);
242
- const nextLength = output.length + string.length;
243
- const truncatedLength = nextLength + truncated.length;
244
- if (last && nextLength > originalLength && output.length + truncated.length <= originalLength) {
245
- break;
246
- }
247
- if (!last && !secondToLast && truncatedLength > originalLength) {
248
- break;
249
- }
250
- peek = last ? "" : inspectItem(list[i + 1], options) + (secondToLast ? "" : separator);
251
- if (!last && secondToLast && truncatedLength > originalLength && nextLength + peek.length > originalLength) {
252
- break;
253
- }
254
- output += string;
255
- if (!last && !secondToLast && nextLength + peek.length >= originalLength) {
256
- truncated = `${truncator}(${list.length - i - 1})`;
257
- break;
258
- }
259
- truncated = "";
260
- }
261
- return `${output}${truncated}`;
262
- }
263
- function quoteComplexKey(key) {
264
- if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) {
265
- return key;
266
- }
267
- return JSON.stringify(key).replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
268
- }
269
- function inspectProperty([key, value], options) {
270
- options.truncate -= 2;
271
- if (typeof key === "string") {
272
- key = quoteComplexKey(key);
273
- } else if (typeof key !== "number") {
274
- key = `[${options.inspect(key, options)}]`;
275
- }
276
- options.truncate -= key.length;
277
- value = options.inspect(value, options);
278
- return `${key}: ${value}`;
279
- }
280
- function inspectArray(array, options) {
281
- const nonIndexProperties = Object.keys(array).slice(array.length);
282
- if (!array.length && !nonIndexProperties.length)
283
- return "[]";
284
- options.truncate -= 4;
285
- const listContents = inspectList(array, options);
286
- options.truncate -= listContents.length;
287
- let propertyContents = "";
288
- if (nonIndexProperties.length) {
289
- propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty);
290
- }
291
- return `[ ${listContents}${propertyContents ? `, ${propertyContents}` : ""} ]`;
292
- }
293
- const getArrayName = (array) => {
294
- if (typeof Buffer === "function" && array instanceof Buffer) {
295
- return "Buffer";
296
- }
297
- if (array[Symbol.toStringTag]) {
298
- return array[Symbol.toStringTag];
299
- }
300
- return array.constructor.name;
301
- };
302
- function inspectTypedArray(array, options) {
303
- const name = getArrayName(array);
304
- options.truncate -= name.length + 4;
305
- const nonIndexProperties = Object.keys(array).slice(array.length);
306
- if (!array.length && !nonIndexProperties.length)
307
- return `${name}[]`;
308
- let output = "";
309
- for (let i = 0; i < array.length; i++) {
310
- const string = `${options.stylize(truncate(array[i], options.truncate), "number")}${i === array.length - 1 ? "" : ", "}`;
311
- options.truncate -= string.length;
312
- if (array[i] !== array.length && options.truncate <= 3) {
313
- output += `${truncator}(${array.length - array[i] + 1})`;
314
- break;
315
- }
316
- output += string;
317
- }
318
- let propertyContents = "";
319
- if (nonIndexProperties.length) {
320
- propertyContents = inspectList(nonIndexProperties.map((key) => [key, array[key]]), options, inspectProperty);
321
- }
322
- return `${name}[ ${output}${propertyContents ? `, ${propertyContents}` : ""} ]`;
323
- }
324
- function inspectDate(dateObject, options) {
325
- const stringRepresentation = dateObject.toJSON();
326
- if (stringRepresentation === null) {
327
- return "Invalid Date";
328
- }
329
- const split = stringRepresentation.split("T");
330
- const date = split[0];
331
- return options.stylize(`${date}T${truncate(split[1], options.truncate - date.length - 1)}`, "date");
332
- }
333
- function inspectFunction(func, options) {
334
- const functionType = func[Symbol.toStringTag] || "Function";
335
- const name = func.name;
336
- if (!name) {
337
- return options.stylize(`[${functionType}]`, "special");
338
- }
339
- return options.stylize(`[${functionType} ${truncate(name, options.truncate - 11)}]`, "special");
340
- }
341
- function inspectMapEntry([key, value], options) {
342
- options.truncate -= 4;
343
- key = options.inspect(key, options);
344
- options.truncate -= key.length;
345
- value = options.inspect(value, options);
346
- return `${key} => ${value}`;
347
- }
348
- function mapToEntries(map) {
349
- const entries = [];
350
- map.forEach((value, key) => {
351
- entries.push([key, value]);
352
- });
353
- return entries;
354
- }
355
- function inspectMap(map, options) {
356
- if (map.size === 0)
357
- return "Map{}";
358
- options.truncate -= 7;
359
- return `Map{ ${inspectList(mapToEntries(map), options, inspectMapEntry)} }`;
360
- }
361
- const isNaN = Number.isNaN || ((i) => i !== i);
362
- function inspectNumber(number, options) {
363
- if (isNaN(number)) {
364
- return options.stylize("NaN", "number");
365
- }
366
- if (number === Infinity) {
367
- return options.stylize("Infinity", "number");
368
- }
369
- if (number === -Infinity) {
370
- return options.stylize("-Infinity", "number");
371
- }
372
- if (number === 0) {
373
- return options.stylize(1 / number === Infinity ? "+0" : "-0", "number");
374
- }
375
- return options.stylize(truncate(String(number), options.truncate), "number");
376
- }
377
- function inspectBigInt(number, options) {
378
- let nums = truncate(number.toString(), options.truncate - 1);
379
- if (nums !== truncator)
380
- nums += "n";
381
- return options.stylize(nums, "bigint");
382
- }
383
- function inspectRegExp(value, options) {
384
- const flags = value.toString().split("/")[2];
385
- const sourceLength = options.truncate - (2 + flags.length);
386
- const source = value.source;
387
- return options.stylize(`/${truncate(source, sourceLength)}/${flags}`, "regexp");
388
- }
389
- function arrayFromSet(set) {
390
- const values = [];
391
- set.forEach((value) => {
392
- values.push(value);
393
- });
394
- return values;
395
- }
396
- function inspectSet(set, options) {
397
- if (set.size === 0)
398
- return "Set{}";
399
- options.truncate -= 7;
400
- return `Set{ ${inspectList(arrayFromSet(set), options)} }`;
401
- }
402
- const stringEscapeChars = new RegExp("['\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]", "g");
403
- const escapeCharacters = {
404
- "\b": "\\b",
405
- " ": "\\t",
406
- "\n": "\\n",
407
- "\f": "\\f",
408
- "\r": "\\r",
409
- "'": "\\'",
410
- "\\": "\\\\"
411
- };
412
- const hex = 16;
413
- function escape(char) {
414
- return escapeCharacters[char] || `\\u${`0000${char.charCodeAt(0).toString(hex)}`.slice(-4)}`;
415
- }
416
- function inspectString(string, options) {
417
- if (stringEscapeChars.test(string)) {
418
- string = string.replace(stringEscapeChars, escape);
419
- }
420
- return options.stylize(`'${truncate(string, options.truncate - 2)}'`, "string");
421
- }
422
- function inspectSymbol(value) {
423
- if ("description" in Symbol.prototype) {
424
- return value.description ? `Symbol(${value.description})` : "Symbol()";
425
- }
426
- return value.toString();
427
- }
428
- const getPromiseValue = () => "Promise{…}";
429
- function inspectObject$1(object, options) {
430
- const properties = Object.getOwnPropertyNames(object);
431
- const symbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(object) : [];
432
- if (properties.length === 0 && symbols.length === 0) {
433
- return "{}";
434
- }
435
- options.truncate -= 4;
436
- options.seen = options.seen || [];
437
- if (options.seen.includes(object)) {
438
- return "[Circular]";
439
- }
440
- options.seen.push(object);
441
- const propertyContents = inspectList(properties.map((key) => [key, object[key]]), options, inspectProperty);
442
- const symbolContents = inspectList(symbols.map((key) => [key, object[key]]), options, inspectProperty);
443
- options.seen.pop();
444
- let sep = "";
445
- if (propertyContents && symbolContents) {
446
- sep = ", ";
447
- }
448
- return `{ ${propertyContents}${sep}${symbolContents} }`;
449
- }
450
- const toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag ? Symbol.toStringTag : false;
451
- function inspectClass(value, options) {
452
- let name = "";
453
- if (toStringTag && toStringTag in value) {
454
- name = value[toStringTag];
455
- }
456
- name = name || value.constructor.name;
457
- if (!name || name === "_class") {
458
- name = "<Anonymous Class>";
459
- }
460
- options.truncate -= name.length;
461
- return `${name}${inspectObject$1(value, options)}`;
462
- }
463
- function inspectArguments(args, options) {
464
- if (args.length === 0)
465
- return "Arguments[]";
466
- options.truncate -= 13;
467
- return `Arguments[ ${inspectList(args, options)} ]`;
468
- }
469
- const errorKeys = [
470
- "stack",
471
- "line",
472
- "column",
473
- "name",
474
- "message",
475
- "fileName",
476
- "lineNumber",
477
- "columnNumber",
478
- "number",
479
- "description",
480
- "cause"
481
- ];
482
- function inspectObject(error, options) {
483
- const properties = Object.getOwnPropertyNames(error).filter((key) => errorKeys.indexOf(key) === -1);
484
- const name = error.name;
485
- options.truncate -= name.length;
486
- let message = "";
487
- if (typeof error.message === "string") {
488
- message = truncate(error.message, options.truncate);
489
- } else {
490
- properties.unshift("message");
491
- }
492
- message = message ? `: ${message}` : "";
493
- options.truncate -= message.length + 5;
494
- options.seen = options.seen || [];
495
- if (options.seen.includes(error)) {
496
- return "[Circular]";
497
- }
498
- options.seen.push(error);
499
- const propertyContents = inspectList(properties.map((key) => [key, error[key]]), options, inspectProperty);
500
- return `${name}${message}${propertyContents ? ` { ${propertyContents} }` : ""}`;
501
- }
502
- function inspectAttribute([key, value], options) {
503
- options.truncate -= 3;
504
- if (!value) {
505
- return `${options.stylize(String(key), "yellow")}`;
506
- }
507
- return `${options.stylize(String(key), "yellow")}=${options.stylize(`"${value}"`, "string")}`;
508
- }
509
- function inspectNodeCollection(collection, options) {
510
- return inspectList(collection, options, inspectNode, "\n");
511
- }
512
- function inspectNode(node, options) {
513
- switch (node.nodeType) {
514
- case 1:
515
- return inspectHTML(node, options);
516
- case 3:
517
- return options.inspect(node.data, options);
518
- default:
519
- return options.inspect(node, options);
520
- }
521
- }
522
- function inspectHTML(element, options) {
523
- const properties = element.getAttributeNames();
524
- const name = element.tagName.toLowerCase();
525
- const head = options.stylize(`<${name}`, "special");
526
- const headClose = options.stylize(`>`, "special");
527
- const tail = options.stylize(`</${name}>`, "special");
528
- options.truncate -= name.length * 2 + 5;
529
- let propertyContents = "";
530
- if (properties.length > 0) {
531
- propertyContents += " ";
532
- propertyContents += inspectList(properties.map((key) => [key, element.getAttribute(key)]), options, inspectAttribute, " ");
533
- }
534
- options.truncate -= propertyContents.length;
535
- const truncate2 = options.truncate;
536
- let children = inspectNodeCollection(element.children, options);
537
- if (children && children.length > truncate2) {
538
- children = `${truncator}(${element.children.length})`;
539
- }
540
- return `${head}${propertyContents}${headClose}${children}${tail}`;
541
- }
542
- const symbolsSupported = typeof Symbol === "function" && typeof Symbol.for === "function";
543
- const chaiInspect = symbolsSupported ? Symbol.for("chai/inspect") : "@@chai/inspect";
544
- const nodeInspect = Symbol.for("nodejs.util.inspect.custom");
545
- const constructorMap = /* @__PURE__ */ new WeakMap();
546
- const stringTagMap = {};
547
- const baseTypesMap = {
548
- undefined: (value, options) => options.stylize("undefined", "undefined"),
549
- null: (value, options) => options.stylize("null", "null"),
550
- boolean: (value, options) => options.stylize(String(value), "boolean"),
551
- Boolean: (value, options) => options.stylize(String(value), "boolean"),
552
- number: inspectNumber,
553
- Number: inspectNumber,
554
- bigint: inspectBigInt,
555
- BigInt: inspectBigInt,
556
- string: inspectString,
557
- String: inspectString,
558
- function: inspectFunction,
559
- Function: inspectFunction,
560
- symbol: inspectSymbol,
561
- // A Symbol polyfill will return `Symbol` not `symbol` from typedetect
562
- Symbol: inspectSymbol,
563
- Array: inspectArray,
564
- Date: inspectDate,
565
- Map: inspectMap,
566
- Set: inspectSet,
567
- RegExp: inspectRegExp,
568
- Promise: getPromiseValue,
569
- // WeakSet, WeakMap are totally opaque to us
570
- WeakSet: (value, options) => options.stylize("WeakSet{…}", "special"),
571
- WeakMap: (value, options) => options.stylize("WeakMap{…}", "special"),
572
- Arguments: inspectArguments,
573
- Int8Array: inspectTypedArray,
574
- Uint8Array: inspectTypedArray,
575
- Uint8ClampedArray: inspectTypedArray,
576
- Int16Array: inspectTypedArray,
577
- Uint16Array: inspectTypedArray,
578
- Int32Array: inspectTypedArray,
579
- Uint32Array: inspectTypedArray,
580
- Float32Array: inspectTypedArray,
581
- Float64Array: inspectTypedArray,
582
- Generator: () => "",
583
- DataView: () => "",
584
- ArrayBuffer: () => "",
585
- Error: inspectObject,
586
- HTMLCollection: inspectNodeCollection,
587
- NodeList: inspectNodeCollection
588
- };
589
- const inspectCustom = (value, options, type) => {
590
- if (chaiInspect in value && typeof value[chaiInspect] === "function") {
591
- return value[chaiInspect](options);
592
- }
593
- if (nodeInspect in value && typeof value[nodeInspect] === "function") {
594
- return value[nodeInspect](options.depth, options);
595
- }
596
- if ("inspect" in value && typeof value.inspect === "function") {
597
- return value.inspect(options.depth, options);
598
- }
599
- if ("constructor" in value && constructorMap.has(value.constructor)) {
600
- return constructorMap.get(value.constructor)(value, options);
601
- }
602
- if (stringTagMap[type]) {
603
- return stringTagMap[type](value, options);
604
- }
605
- return "";
606
- };
607
- const toString = Object.prototype.toString;
608
- function inspect$1(value, opts = {}) {
609
- const options = normaliseOptions(opts, inspect$1);
610
- const { customInspect } = options;
611
- let type = value === null ? "null" : typeof value;
612
- if (type === "object") {
613
- type = toString.call(value).slice(8, -1);
614
- }
615
- if (type in baseTypesMap) {
616
- return baseTypesMap[type](value, options);
617
- }
618
- if (customInspect && value) {
619
- const output = inspectCustom(value, options, type);
620
- if (output) {
621
- if (typeof output === "string")
622
- return output;
623
- return inspect$1(output, options);
624
- }
625
- }
626
- const proto = value ? Object.getPrototypeOf(value) : false;
627
- if (proto === Object.prototype || proto === null) {
628
- return inspectObject$1(value, options);
629
- }
630
- if (value && typeof HTMLElement === "function" && value instanceof HTMLElement) {
631
- return inspectHTML(value, options);
632
- }
633
- if ("constructor" in value) {
634
- if (value.constructor !== Object) {
635
- return inspectClass(value, options);
636
- }
637
- return inspectObject$1(value, options);
638
- }
639
- if (value === Object(value)) {
640
- return inspectObject$1(value, options);
641
- }
642
- return options.stylize(String(value), type);
643
- }
644
- const formatRegExp = /%[sdjifoOc%]/g;
645
- function format(...args) {
646
- if (typeof args[0] !== "string") {
647
- const objects = [];
648
- for (let i2 = 0; i2 < args.length; i2++) {
649
- objects.push(inspect(args[i2], {
650
- depth: 0,
651
- colors: false
652
- }));
653
- }
654
- return objects.join(" ");
655
- }
656
- const len = args.length;
657
- let i = 1;
658
- const template = args[0];
659
- let str = String(template).replace(formatRegExp, (x) => {
660
- if (x === "%%") {
661
- return "%";
662
- }
663
- if (i >= len) {
664
- return x;
665
- }
666
- switch (x) {
667
- case "%s": {
668
- const value = args[i++];
669
- if (typeof value === "bigint") {
670
- return `${value.toString()}n`;
671
- }
672
- if (typeof value === "number" && value === 0 && 1 / value < 0) {
673
- return "-0";
674
- }
675
- if (typeof value === "object" && value !== null) {
676
- if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) {
677
- return value.toString();
678
- }
679
- return inspect(value, {
680
- depth: 0,
681
- colors: false
682
- });
683
- }
684
- return String(value);
685
- }
686
- case "%d": {
687
- const value = args[i++];
688
- if (typeof value === "bigint") {
689
- return `${value.toString()}n`;
690
- }
691
- return Number(value).toString();
692
- }
693
- case "%i": {
694
- const value = args[i++];
695
- if (typeof value === "bigint") {
696
- return `${value.toString()}n`;
697
- }
698
- return Number.parseInt(String(value)).toString();
699
- }
700
- case "%f":
701
- return Number.parseFloat(String(args[i++])).toString();
702
- case "%o":
703
- return inspect(args[i++], {
704
- showHidden: true,
705
- showProxy: true
706
- });
707
- case "%O":
708
- return inspect(args[i++]);
709
- case "%c": {
710
- i++;
711
- return "";
712
- }
713
- case "%j":
714
- try {
715
- return JSON.stringify(args[i++]);
716
- } catch (err) {
717
- const m = err.message;
718
- if (m.includes("circular structure") || m.includes("cyclic structures") || m.includes("cyclic object")) {
719
- return "[Circular]";
720
- }
721
- throw err;
722
- }
723
- default:
724
- return x;
725
- }
726
- });
727
- for (let x = args[i]; i < len; x = args[++i]) {
728
- if (x === null || typeof x !== "object") {
729
- str += ` ${x}`;
730
- } else {
731
- str += ` ${inspect(x)}`;
732
- }
733
- }
734
- return str;
735
- }
736
- function inspect(obj, options = {}) {
737
- if (options.truncate === 0) {
738
- options.truncate = Number.POSITIVE_INFINITY;
739
- }
740
- return inspect$1(obj, options);
741
- }
742
- function objDisplay(obj, options = {}) {
743
- if (typeof options.truncate === "undefined") {
744
- options.truncate = 40;
745
- }
746
- const str = inspect(obj, options);
747
- const type = Object.prototype.toString.call(obj);
748
- if (options.truncate && str.length >= options.truncate) {
749
- if (type === "[object Function]") {
750
- const fn = obj;
751
- return !fn.name ? "[Function]" : `[Function: ${fn.name}]`;
752
- } else if (type === "[object Array]") {
753
- return `[ Array(${obj.length}) ]`;
754
- } else if (type === "[object Object]") {
755
- const keys = Object.keys(obj);
756
- const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(", ")}, ...` : keys.join(", ");
757
- return `{ Object (${kstr}) }`;
758
- } else {
759
- return str;
760
- }
761
- }
762
- return str;
763
- }
764
- var jsTokens_1$1;
765
- var hasRequiredJsTokens$1;
766
- function requireJsTokens$1() {
767
- if (hasRequiredJsTokens$1) return jsTokens_1$1;
768
- hasRequiredJsTokens$1 = 1;
769
- var Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
770
- RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\\]).|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
771
- Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
772
- Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
773
- StringLiteral = /(['"])(?:(?!\1)[^\\\n\r]|\\(?:\r\n|[^]))*(\1)?/y;
774
- NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
775
- Template = /[`}](?:[^`\\$]|\\[^]|\$(?!\{))*(`|\$\{)?/y;
776
- WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
777
- LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
778
- MultiLineComment = /\/\*(?:[^*]|\*(?!\/))*(\*\/)?/y;
779
- SingleLineComment = /\/\/.*/y;
780
- JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
781
- JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
782
- JSXString = /(['"])(?:(?!\1)[^])*(\1)?/y;
783
- JSXText = /[^<>{}]+/y;
784
- TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
785
- TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
786
- KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
787
- KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
788
- Newline = RegExp(LineTerminatorSequence.source);
789
- jsTokens_1$1 = function* (input, { jsx = false } = {}) {
790
- var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
791
- ({ length } = input);
792
- lastIndex = 0;
793
- lastSignificantToken = "";
794
- stack = [
795
- { tag: "JS" }
796
- ];
797
- braces = [];
798
- parenNesting = 0;
799
- postfixIncDec = false;
800
- while (lastIndex < length) {
801
- mode = stack[stack.length - 1];
802
- switch (mode.tag) {
803
- case "JS":
804
- case "JSNonExpressionParen":
805
- case "InterpolationInTemplate":
806
- case "InterpolationInJSX":
807
- if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
808
- RegularExpressionLiteral.lastIndex = lastIndex;
809
- if (match = RegularExpressionLiteral.exec(input)) {
810
- lastIndex = RegularExpressionLiteral.lastIndex;
811
- lastSignificantToken = match[0];
812
- postfixIncDec = true;
813
- yield {
814
- type: "RegularExpressionLiteral",
815
- value: match[0],
816
- closed: match[1] !== void 0 && match[1] !== "\\"
817
- };
818
- continue;
819
- }
820
- }
821
- Punctuator.lastIndex = lastIndex;
822
- if (match = Punctuator.exec(input)) {
823
- punctuator = match[0];
824
- nextLastIndex = Punctuator.lastIndex;
825
- nextLastSignificantToken = punctuator;
826
- switch (punctuator) {
827
- case "(":
828
- if (lastSignificantToken === "?NonExpressionParenKeyword") {
829
- stack.push({
830
- tag: "JSNonExpressionParen",
831
- nesting: parenNesting
832
- });
833
- }
834
- parenNesting++;
835
- postfixIncDec = false;
836
- break;
837
- case ")":
838
- parenNesting--;
839
- postfixIncDec = true;
840
- if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
841
- stack.pop();
842
- nextLastSignificantToken = "?NonExpressionParenEnd";
843
- postfixIncDec = false;
844
- }
845
- break;
846
- case "{":
847
- Punctuator.lastIndex = 0;
848
- isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
849
- braces.push(isExpression);
850
- postfixIncDec = false;
851
- break;
852
- case "}":
853
- switch (mode.tag) {
854
- case "InterpolationInTemplate":
855
- if (braces.length === mode.nesting) {
856
- Template.lastIndex = lastIndex;
857
- match = Template.exec(input);
858
- lastIndex = Template.lastIndex;
859
- lastSignificantToken = match[0];
860
- if (match[1] === "${") {
861
- lastSignificantToken = "?InterpolationInTemplate";
862
- postfixIncDec = false;
863
- yield {
864
- type: "TemplateMiddle",
865
- value: match[0]
866
- };
867
- } else {
868
- stack.pop();
869
- postfixIncDec = true;
870
- yield {
871
- type: "TemplateTail",
872
- value: match[0],
873
- closed: match[1] === "`"
874
- };
875
- }
876
- continue;
877
- }
878
- break;
879
- case "InterpolationInJSX":
880
- if (braces.length === mode.nesting) {
881
- stack.pop();
882
- lastIndex += 1;
883
- lastSignificantToken = "}";
884
- yield {
885
- type: "JSXPunctuator",
886
- value: "}"
887
- };
888
- continue;
889
- }
890
- }
891
- postfixIncDec = braces.pop();
892
- nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
893
- break;
894
- case "]":
895
- postfixIncDec = true;
896
- break;
897
- case "++":
898
- case "--":
899
- nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
900
- break;
901
- case "<":
902
- if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
903
- stack.push({ tag: "JSXTag" });
904
- lastIndex += 1;
905
- lastSignificantToken = "<";
906
- yield {
907
- type: "JSXPunctuator",
908
- value: punctuator
909
- };
910
- continue;
911
- }
912
- postfixIncDec = false;
913
- break;
914
- default:
915
- postfixIncDec = false;
916
- }
917
- lastIndex = nextLastIndex;
918
- lastSignificantToken = nextLastSignificantToken;
919
- yield {
920
- type: "Punctuator",
921
- value: punctuator
922
- };
923
- continue;
924
- }
925
- Identifier.lastIndex = lastIndex;
926
- if (match = Identifier.exec(input)) {
927
- lastIndex = Identifier.lastIndex;
928
- nextLastSignificantToken = match[0];
929
- switch (match[0]) {
930
- case "for":
931
- case "if":
932
- case "while":
933
- case "with":
934
- if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
935
- nextLastSignificantToken = "?NonExpressionParenKeyword";
936
- }
937
- }
938
- lastSignificantToken = nextLastSignificantToken;
939
- postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
940
- yield {
941
- type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
942
- value: match[0]
943
- };
944
- continue;
945
- }
946
- StringLiteral.lastIndex = lastIndex;
947
- if (match = StringLiteral.exec(input)) {
948
- lastIndex = StringLiteral.lastIndex;
949
- lastSignificantToken = match[0];
950
- postfixIncDec = true;
951
- yield {
952
- type: "StringLiteral",
953
- value: match[0],
954
- closed: match[2] !== void 0
955
- };
956
- continue;
957
- }
958
- NumericLiteral.lastIndex = lastIndex;
959
- if (match = NumericLiteral.exec(input)) {
960
- lastIndex = NumericLiteral.lastIndex;
961
- lastSignificantToken = match[0];
962
- postfixIncDec = true;
963
- yield {
964
- type: "NumericLiteral",
965
- value: match[0]
966
- };
967
- continue;
968
- }
969
- Template.lastIndex = lastIndex;
970
- if (match = Template.exec(input)) {
971
- lastIndex = Template.lastIndex;
972
- lastSignificantToken = match[0];
973
- if (match[1] === "${") {
974
- lastSignificantToken = "?InterpolationInTemplate";
975
- stack.push({
976
- tag: "InterpolationInTemplate",
977
- nesting: braces.length
978
- });
979
- postfixIncDec = false;
980
- yield {
981
- type: "TemplateHead",
982
- value: match[0]
983
- };
984
- } else {
985
- postfixIncDec = true;
986
- yield {
987
- type: "NoSubstitutionTemplate",
988
- value: match[0],
989
- closed: match[1] === "`"
990
- };
991
- }
992
- continue;
993
- }
994
- break;
995
- case "JSXTag":
996
- case "JSXTagEnd":
997
- JSXPunctuator.lastIndex = lastIndex;
998
- if (match = JSXPunctuator.exec(input)) {
999
- lastIndex = JSXPunctuator.lastIndex;
1000
- nextLastSignificantToken = match[0];
1001
- switch (match[0]) {
1002
- case "<":
1003
- stack.push({ tag: "JSXTag" });
1004
- break;
1005
- case ">":
1006
- stack.pop();
1007
- if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
1008
- nextLastSignificantToken = "?JSX";
1009
- postfixIncDec = true;
1010
- } else {
1011
- stack.push({ tag: "JSXChildren" });
1012
- }
1013
- break;
1014
- case "{":
1015
- stack.push({
1016
- tag: "InterpolationInJSX",
1017
- nesting: braces.length
1018
- });
1019
- nextLastSignificantToken = "?InterpolationInJSX";
1020
- postfixIncDec = false;
1021
- break;
1022
- case "/":
1023
- if (lastSignificantToken === "<") {
1024
- stack.pop();
1025
- if (stack[stack.length - 1].tag === "JSXChildren") {
1026
- stack.pop();
1027
- }
1028
- stack.push({ tag: "JSXTagEnd" });
1029
- }
1030
- }
1031
- lastSignificantToken = nextLastSignificantToken;
1032
- yield {
1033
- type: "JSXPunctuator",
1034
- value: match[0]
1035
- };
1036
- continue;
1037
- }
1038
- JSXIdentifier.lastIndex = lastIndex;
1039
- if (match = JSXIdentifier.exec(input)) {
1040
- lastIndex = JSXIdentifier.lastIndex;
1041
- lastSignificantToken = match[0];
1042
- yield {
1043
- type: "JSXIdentifier",
1044
- value: match[0]
1045
- };
1046
- continue;
1047
- }
1048
- JSXString.lastIndex = lastIndex;
1049
- if (match = JSXString.exec(input)) {
1050
- lastIndex = JSXString.lastIndex;
1051
- lastSignificantToken = match[0];
1052
- yield {
1053
- type: "JSXString",
1054
- value: match[0],
1055
- closed: match[2] !== void 0
1056
- };
1057
- continue;
1058
- }
1059
- break;
1060
- case "JSXChildren":
1061
- JSXText.lastIndex = lastIndex;
1062
- if (match = JSXText.exec(input)) {
1063
- lastIndex = JSXText.lastIndex;
1064
- lastSignificantToken = match[0];
1065
- yield {
1066
- type: "JSXText",
1067
- value: match[0]
1068
- };
1069
- continue;
1070
- }
1071
- switch (input[lastIndex]) {
1072
- case "<":
1073
- stack.push({ tag: "JSXTag" });
1074
- lastIndex++;
1075
- lastSignificantToken = "<";
1076
- yield {
1077
- type: "JSXPunctuator",
1078
- value: "<"
1079
- };
1080
- continue;
1081
- case "{":
1082
- stack.push({
1083
- tag: "InterpolationInJSX",
1084
- nesting: braces.length
1085
- });
1086
- lastIndex++;
1087
- lastSignificantToken = "?InterpolationInJSX";
1088
- postfixIncDec = false;
1089
- yield {
1090
- type: "JSXPunctuator",
1091
- value: "{"
1092
- };
1093
- continue;
1094
- }
1095
- }
1096
- WhiteSpace.lastIndex = lastIndex;
1097
- if (match = WhiteSpace.exec(input)) {
1098
- lastIndex = WhiteSpace.lastIndex;
1099
- yield {
1100
- type: "WhiteSpace",
1101
- value: match[0]
1102
- };
1103
- continue;
1104
- }
1105
- LineTerminatorSequence.lastIndex = lastIndex;
1106
- if (match = LineTerminatorSequence.exec(input)) {
1107
- lastIndex = LineTerminatorSequence.lastIndex;
1108
- postfixIncDec = false;
1109
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
1110
- lastSignificantToken = "?NoLineTerminatorHere";
1111
- }
1112
- yield {
1113
- type: "LineTerminatorSequence",
1114
- value: match[0]
1115
- };
1116
- continue;
1117
- }
1118
- MultiLineComment.lastIndex = lastIndex;
1119
- if (match = MultiLineComment.exec(input)) {
1120
- lastIndex = MultiLineComment.lastIndex;
1121
- if (Newline.test(match[0])) {
1122
- postfixIncDec = false;
1123
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
1124
- lastSignificantToken = "?NoLineTerminatorHere";
1125
- }
1126
- }
1127
- yield {
1128
- type: "MultiLineComment",
1129
- value: match[0],
1130
- closed: match[1] !== void 0
1131
- };
1132
- continue;
1133
- }
1134
- SingleLineComment.lastIndex = lastIndex;
1135
- if (match = SingleLineComment.exec(input)) {
1136
- lastIndex = SingleLineComment.lastIndex;
1137
- postfixIncDec = false;
1138
- yield {
1139
- type: "SingleLineComment",
1140
- value: match[0]
1141
- };
1142
- continue;
1143
- }
1144
- firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
1145
- lastIndex += firstCodePoint.length;
1146
- lastSignificantToken = firstCodePoint;
1147
- postfixIncDec = false;
1148
- yield {
1149
- type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
1150
- value: firstCodePoint
1151
- };
1152
- }
1153
- return void 0;
1154
- };
1155
- return jsTokens_1$1;
1156
- }
1157
- requireJsTokens$1();
1158
- var reservedWords = {
1159
- keyword: [
1160
- "break",
1161
- "case",
1162
- "catch",
1163
- "continue",
1164
- "debugger",
1165
- "default",
1166
- "do",
1167
- "else",
1168
- "finally",
1169
- "for",
1170
- "function",
1171
- "if",
1172
- "return",
1173
- "switch",
1174
- "throw",
1175
- "try",
1176
- "var",
1177
- "const",
1178
- "while",
1179
- "with",
1180
- "new",
1181
- "this",
1182
- "super",
1183
- "class",
1184
- "extends",
1185
- "export",
1186
- "import",
1187
- "null",
1188
- "true",
1189
- "false",
1190
- "in",
1191
- "instanceof",
1192
- "typeof",
1193
- "void",
1194
- "delete"
1195
- ],
1196
- strict: [
1197
- "implements",
1198
- "interface",
1199
- "let",
1200
- "package",
1201
- "private",
1202
- "protected",
1203
- "public",
1204
- "static",
1205
- "yield"
1206
- ]
1207
- };
1208
- new Set(reservedWords.keyword);
1209
- new Set(reservedWords.strict);
1210
- const SAFE_TIMERS_SYMBOL = Symbol("vitest:SAFE_TIMERS");
1211
- function getSafeTimers() {
1212
- const { setTimeout: safeSetTimeout, setInterval: safeSetInterval, clearInterval: safeClearInterval, clearTimeout: safeClearTimeout, setImmediate: safeSetImmediate, clearImmediate: safeClearImmediate, queueMicrotask: safeQueueMicrotask } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis;
1213
- const { nextTick: safeNextTick } = globalThis[SAFE_TIMERS_SYMBOL] || globalThis.process || {};
1214
- return {
1215
- nextTick: safeNextTick,
1216
- setTimeout: safeSetTimeout,
1217
- setInterval: safeSetInterval,
1218
- clearInterval: safeClearInterval,
1219
- clearTimeout: safeClearTimeout,
1220
- setImmediate: safeSetImmediate,
1221
- clearImmediate: safeClearImmediate,
1222
- queueMicrotask: safeQueueMicrotask
1223
- };
1224
- }
1225
- var jsTokens_1;
1226
- var hasRequiredJsTokens;
1227
- function requireJsTokens() {
1228
- if (hasRequiredJsTokens) return jsTokens_1;
1229
- hasRequiredJsTokens = 1;
1230
- var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
1231
- RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
1232
- Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
1233
- Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
1234
- StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
1235
- NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
1236
- Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
1237
- WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
1238
- LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
1239
- MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
1240
- SingleLineComment = /\/\/.*/y;
1241
- HashbangComment = /^#!.*/;
1242
- JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
1243
- JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
1244
- JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
1245
- JSXText = /[^<>{}]+/y;
1246
- TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
1247
- TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
1248
- KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
1249
- KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
1250
- Newline = RegExp(LineTerminatorSequence.source);
1251
- jsTokens_1 = function* (input, { jsx = false } = {}) {
1252
- var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
1253
- ({ length } = input);
1254
- lastIndex = 0;
1255
- lastSignificantToken = "";
1256
- stack = [
1257
- { tag: "JS" }
1258
- ];
1259
- braces = [];
1260
- parenNesting = 0;
1261
- postfixIncDec = false;
1262
- if (match = HashbangComment.exec(input)) {
1263
- yield {
1264
- type: "HashbangComment",
1265
- value: match[0]
1266
- };
1267
- lastIndex = match[0].length;
1268
- }
1269
- while (lastIndex < length) {
1270
- mode = stack[stack.length - 1];
1271
- switch (mode.tag) {
1272
- case "JS":
1273
- case "JSNonExpressionParen":
1274
- case "InterpolationInTemplate":
1275
- case "InterpolationInJSX":
1276
- if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
1277
- RegularExpressionLiteral.lastIndex = lastIndex;
1278
- if (match = RegularExpressionLiteral.exec(input)) {
1279
- lastIndex = RegularExpressionLiteral.lastIndex;
1280
- lastSignificantToken = match[0];
1281
- postfixIncDec = true;
1282
- yield {
1283
- type: "RegularExpressionLiteral",
1284
- value: match[0],
1285
- closed: match[1] !== void 0 && match[1] !== "\\"
1286
- };
1287
- continue;
1288
- }
1289
- }
1290
- Punctuator.lastIndex = lastIndex;
1291
- if (match = Punctuator.exec(input)) {
1292
- punctuator = match[0];
1293
- nextLastIndex = Punctuator.lastIndex;
1294
- nextLastSignificantToken = punctuator;
1295
- switch (punctuator) {
1296
- case "(":
1297
- if (lastSignificantToken === "?NonExpressionParenKeyword") {
1298
- stack.push({
1299
- tag: "JSNonExpressionParen",
1300
- nesting: parenNesting
1301
- });
1302
- }
1303
- parenNesting++;
1304
- postfixIncDec = false;
1305
- break;
1306
- case ")":
1307
- parenNesting--;
1308
- postfixIncDec = true;
1309
- if (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
1310
- stack.pop();
1311
- nextLastSignificantToken = "?NonExpressionParenEnd";
1312
- postfixIncDec = false;
1313
- }
1314
- break;
1315
- case "{":
1316
- Punctuator.lastIndex = 0;
1317
- isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
1318
- braces.push(isExpression);
1319
- postfixIncDec = false;
1320
- break;
1321
- case "}":
1322
- switch (mode.tag) {
1323
- case "InterpolationInTemplate":
1324
- if (braces.length === mode.nesting) {
1325
- Template.lastIndex = lastIndex;
1326
- match = Template.exec(input);
1327
- lastIndex = Template.lastIndex;
1328
- lastSignificantToken = match[0];
1329
- if (match[1] === "${") {
1330
- lastSignificantToken = "?InterpolationInTemplate";
1331
- postfixIncDec = false;
1332
- yield {
1333
- type: "TemplateMiddle",
1334
- value: match[0]
1335
- };
1336
- } else {
1337
- stack.pop();
1338
- postfixIncDec = true;
1339
- yield {
1340
- type: "TemplateTail",
1341
- value: match[0],
1342
- closed: match[1] === "`"
1343
- };
1344
- }
1345
- continue;
1346
- }
1347
- break;
1348
- case "InterpolationInJSX":
1349
- if (braces.length === mode.nesting) {
1350
- stack.pop();
1351
- lastIndex += 1;
1352
- lastSignificantToken = "}";
1353
- yield {
1354
- type: "JSXPunctuator",
1355
- value: "}"
1356
- };
1357
- continue;
1358
- }
1359
- }
1360
- postfixIncDec = braces.pop();
1361
- nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
1362
- break;
1363
- case "]":
1364
- postfixIncDec = true;
1365
- break;
1366
- case "++":
1367
- case "--":
1368
- nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
1369
- break;
1370
- case "<":
1371
- if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
1372
- stack.push({ tag: "JSXTag" });
1373
- lastIndex += 1;
1374
- lastSignificantToken = "<";
1375
- yield {
1376
- type: "JSXPunctuator",
1377
- value: punctuator
1378
- };
1379
- continue;
1380
- }
1381
- postfixIncDec = false;
1382
- break;
1383
- default:
1384
- postfixIncDec = false;
1385
- }
1386
- lastIndex = nextLastIndex;
1387
- lastSignificantToken = nextLastSignificantToken;
1388
- yield {
1389
- type: "Punctuator",
1390
- value: punctuator
1391
- };
1392
- continue;
1393
- }
1394
- Identifier.lastIndex = lastIndex;
1395
- if (match = Identifier.exec(input)) {
1396
- lastIndex = Identifier.lastIndex;
1397
- nextLastSignificantToken = match[0];
1398
- switch (match[0]) {
1399
- case "for":
1400
- case "if":
1401
- case "while":
1402
- case "with":
1403
- if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
1404
- nextLastSignificantToken = "?NonExpressionParenKeyword";
1405
- }
1406
- }
1407
- lastSignificantToken = nextLastSignificantToken;
1408
- postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
1409
- yield {
1410
- type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
1411
- value: match[0]
1412
- };
1413
- continue;
1414
- }
1415
- StringLiteral.lastIndex = lastIndex;
1416
- if (match = StringLiteral.exec(input)) {
1417
- lastIndex = StringLiteral.lastIndex;
1418
- lastSignificantToken = match[0];
1419
- postfixIncDec = true;
1420
- yield {
1421
- type: "StringLiteral",
1422
- value: match[0],
1423
- closed: match[2] !== void 0
1424
- };
1425
- continue;
1426
- }
1427
- NumericLiteral.lastIndex = lastIndex;
1428
- if (match = NumericLiteral.exec(input)) {
1429
- lastIndex = NumericLiteral.lastIndex;
1430
- lastSignificantToken = match[0];
1431
- postfixIncDec = true;
1432
- yield {
1433
- type: "NumericLiteral",
1434
- value: match[0]
1435
- };
1436
- continue;
1437
- }
1438
- Template.lastIndex = lastIndex;
1439
- if (match = Template.exec(input)) {
1440
- lastIndex = Template.lastIndex;
1441
- lastSignificantToken = match[0];
1442
- if (match[1] === "${") {
1443
- lastSignificantToken = "?InterpolationInTemplate";
1444
- stack.push({
1445
- tag: "InterpolationInTemplate",
1446
- nesting: braces.length
1447
- });
1448
- postfixIncDec = false;
1449
- yield {
1450
- type: "TemplateHead",
1451
- value: match[0]
1452
- };
1453
- } else {
1454
- postfixIncDec = true;
1455
- yield {
1456
- type: "NoSubstitutionTemplate",
1457
- value: match[0],
1458
- closed: match[1] === "`"
1459
- };
1460
- }
1461
- continue;
1462
- }
1463
- break;
1464
- case "JSXTag":
1465
- case "JSXTagEnd":
1466
- JSXPunctuator.lastIndex = lastIndex;
1467
- if (match = JSXPunctuator.exec(input)) {
1468
- lastIndex = JSXPunctuator.lastIndex;
1469
- nextLastSignificantToken = match[0];
1470
- switch (match[0]) {
1471
- case "<":
1472
- stack.push({ tag: "JSXTag" });
1473
- break;
1474
- case ">":
1475
- stack.pop();
1476
- if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
1477
- nextLastSignificantToken = "?JSX";
1478
- postfixIncDec = true;
1479
- } else {
1480
- stack.push({ tag: "JSXChildren" });
1481
- }
1482
- break;
1483
- case "{":
1484
- stack.push({
1485
- tag: "InterpolationInJSX",
1486
- nesting: braces.length
1487
- });
1488
- nextLastSignificantToken = "?InterpolationInJSX";
1489
- postfixIncDec = false;
1490
- break;
1491
- case "/":
1492
- if (lastSignificantToken === "<") {
1493
- stack.pop();
1494
- if (stack[stack.length - 1].tag === "JSXChildren") {
1495
- stack.pop();
1496
- }
1497
- stack.push({ tag: "JSXTagEnd" });
1498
- }
1499
- }
1500
- lastSignificantToken = nextLastSignificantToken;
1501
- yield {
1502
- type: "JSXPunctuator",
1503
- value: match[0]
1504
- };
1505
- continue;
1506
- }
1507
- JSXIdentifier.lastIndex = lastIndex;
1508
- if (match = JSXIdentifier.exec(input)) {
1509
- lastIndex = JSXIdentifier.lastIndex;
1510
- lastSignificantToken = match[0];
1511
- yield {
1512
- type: "JSXIdentifier",
1513
- value: match[0]
1514
- };
1515
- continue;
1516
- }
1517
- JSXString.lastIndex = lastIndex;
1518
- if (match = JSXString.exec(input)) {
1519
- lastIndex = JSXString.lastIndex;
1520
- lastSignificantToken = match[0];
1521
- yield {
1522
- type: "JSXString",
1523
- value: match[0],
1524
- closed: match[2] !== void 0
1525
- };
1526
- continue;
1527
- }
1528
- break;
1529
- case "JSXChildren":
1530
- JSXText.lastIndex = lastIndex;
1531
- if (match = JSXText.exec(input)) {
1532
- lastIndex = JSXText.lastIndex;
1533
- lastSignificantToken = match[0];
1534
- yield {
1535
- type: "JSXText",
1536
- value: match[0]
1537
- };
1538
- continue;
1539
- }
1540
- switch (input[lastIndex]) {
1541
- case "<":
1542
- stack.push({ tag: "JSXTag" });
1543
- lastIndex++;
1544
- lastSignificantToken = "<";
1545
- yield {
1546
- type: "JSXPunctuator",
1547
- value: "<"
1548
- };
1549
- continue;
1550
- case "{":
1551
- stack.push({
1552
- tag: "InterpolationInJSX",
1553
- nesting: braces.length
1554
- });
1555
- lastIndex++;
1556
- lastSignificantToken = "?InterpolationInJSX";
1557
- postfixIncDec = false;
1558
- yield {
1559
- type: "JSXPunctuator",
1560
- value: "{"
1561
- };
1562
- continue;
1563
- }
1564
- }
1565
- WhiteSpace.lastIndex = lastIndex;
1566
- if (match = WhiteSpace.exec(input)) {
1567
- lastIndex = WhiteSpace.lastIndex;
1568
- yield {
1569
- type: "WhiteSpace",
1570
- value: match[0]
1571
- };
1572
- continue;
1573
- }
1574
- LineTerminatorSequence.lastIndex = lastIndex;
1575
- if (match = LineTerminatorSequence.exec(input)) {
1576
- lastIndex = LineTerminatorSequence.lastIndex;
1577
- postfixIncDec = false;
1578
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
1579
- lastSignificantToken = "?NoLineTerminatorHere";
1580
- }
1581
- yield {
1582
- type: "LineTerminatorSequence",
1583
- value: match[0]
1584
- };
1585
- continue;
1586
- }
1587
- MultiLineComment.lastIndex = lastIndex;
1588
- if (match = MultiLineComment.exec(input)) {
1589
- lastIndex = MultiLineComment.lastIndex;
1590
- if (Newline.test(match[0])) {
1591
- postfixIncDec = false;
1592
- if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
1593
- lastSignificantToken = "?NoLineTerminatorHere";
1594
- }
1595
- }
1596
- yield {
1597
- type: "MultiLineComment",
1598
- value: match[0],
1599
- closed: match[1] !== void 0
1600
- };
1601
- continue;
1602
- }
1603
- SingleLineComment.lastIndex = lastIndex;
1604
- if (match = SingleLineComment.exec(input)) {
1605
- lastIndex = SingleLineComment.lastIndex;
1606
- postfixIncDec = false;
1607
- yield {
1608
- type: "SingleLineComment",
1609
- value: match[0]
1610
- };
1611
- continue;
1612
- }
1613
- firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
1614
- lastIndex += firstCodePoint.length;
1615
- lastSignificantToken = firstCodePoint;
1616
- postfixIncDec = false;
1617
- yield {
1618
- type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
1619
- value: firstCodePoint
1620
- };
1621
- }
1622
- return void 0;
1623
- };
1624
- return jsTokens_1;
1625
- }
1626
- var jsTokensExports = requireJsTokens();
1627
- const jsTokens = /* @__PURE__ */ getDefaultExportFromCjs(jsTokensExports);
1628
- function stripLiteralJsTokens(code, options) {
1629
- const FILL = " ";
1630
- const FILL_COMMENT = " ";
1631
- let result = "";
1632
- const tokens = [];
1633
- for (const token of jsTokens(code, { jsx: false })) {
1634
- tokens.push(token);
1635
- if (token.type === "SingleLineComment") {
1636
- result += FILL_COMMENT.repeat(token.value.length);
1637
- continue;
1638
- }
1639
- if (token.type === "MultiLineComment") {
1640
- result += token.value.replace(/[^\n]/g, FILL_COMMENT);
1641
- continue;
1642
- }
1643
- if (token.type === "StringLiteral") {
1644
- if (!token.closed) {
1645
- result += token.value;
1646
- continue;
1647
- }
1648
- const body = token.value.slice(1, -1);
1649
- {
1650
- result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
1651
- continue;
1652
- }
1653
- }
1654
- if (token.type === "NoSubstitutionTemplate") {
1655
- const body = token.value.slice(1, -1);
1656
- {
1657
- result += `\`${body.replace(/[^\n]/g, FILL)}\``;
1658
- continue;
1659
- }
1660
- }
1661
- if (token.type === "RegularExpressionLiteral") {
1662
- const body = token.value;
1663
- {
1664
- result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
1665
- continue;
1666
- }
1667
- }
1668
- if (token.type === "TemplateHead") {
1669
- const body = token.value.slice(1, -2);
1670
- {
1671
- result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
1672
- continue;
1673
- }
1674
- }
1675
- if (token.type === "TemplateTail") {
1676
- const body = token.value.slice(0, -2);
1677
- {
1678
- result += `}${body.replace(/[^\n]/g, FILL)}\``;
1679
- continue;
1680
- }
1681
- }
1682
- if (token.type === "TemplateMiddle") {
1683
- const body = token.value.slice(1, -2);
1684
- {
1685
- result += `}${body.replace(/[^\n]/g, FILL)}\${`;
1686
- continue;
1687
- }
1688
- }
1689
- result += token.value;
1690
- }
1691
- return {
1692
- result,
1693
- tokens
1694
- };
1695
- }
1696
- function stripLiteral(code, options) {
1697
- return stripLiteralDetailed(code).result;
1698
- }
1699
- function stripLiteralDetailed(code, options) {
1700
- return stripLiteralJsTokens(code);
1701
- }
1702
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
1703
- function normalizeWindowsPath(input = "") {
1704
- if (!input) {
1705
- return input;
1706
- }
1707
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
1708
- }
1709
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
1710
- function cwd() {
1711
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
1712
- return process.cwd().replace(/\\/g, "/");
1713
- }
1714
- return "/";
1715
- }
1716
- const resolve = function(...arguments_) {
1717
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
1718
- let resolvedPath = "";
1719
- let resolvedAbsolute = false;
1720
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
1721
- const path = index >= 0 ? arguments_[index] : cwd();
1722
- if (!path || path.length === 0) {
1723
- continue;
1724
- }
1725
- resolvedPath = `${path}/${resolvedPath}`;
1726
- resolvedAbsolute = isAbsolute(path);
1727
- }
1728
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
1729
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
1730
- return `/${resolvedPath}`;
1731
- }
1732
- return resolvedPath.length > 0 ? resolvedPath : ".";
1733
- };
1734
- function normalizeString(path, allowAboveRoot) {
1735
- let res = "";
1736
- let lastSegmentLength = 0;
1737
- let lastSlash = -1;
1738
- let dots = 0;
1739
- let char = null;
1740
- for (let index = 0; index <= path.length; ++index) {
1741
- if (index < path.length) {
1742
- char = path[index];
1743
- } else if (char === "/") {
1744
- break;
1745
- } else {
1746
- char = "/";
1747
- }
1748
- if (char === "/") {
1749
- if (lastSlash === index - 1 || dots === 1) ;
1750
- else if (dots === 2) {
1751
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
1752
- if (res.length > 2) {
1753
- const lastSlashIndex = res.lastIndexOf("/");
1754
- if (lastSlashIndex === -1) {
1755
- res = "";
1756
- lastSegmentLength = 0;
1757
- } else {
1758
- res = res.slice(0, lastSlashIndex);
1759
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
1760
- }
1761
- lastSlash = index;
1762
- dots = 0;
1763
- continue;
1764
- } else if (res.length > 0) {
1765
- res = "";
1766
- lastSegmentLength = 0;
1767
- lastSlash = index;
1768
- dots = 0;
1769
- continue;
1770
- }
1771
- }
1772
- if (allowAboveRoot) {
1773
- res += res.length > 0 ? "/.." : "..";
1774
- lastSegmentLength = 2;
1775
- }
1776
- } else {
1777
- if (res.length > 0) {
1778
- res += `/${path.slice(lastSlash + 1, index)}`;
1779
- } else {
1780
- res = path.slice(lastSlash + 1, index);
1781
- }
1782
- lastSegmentLength = index - lastSlash - 1;
1783
- }
1784
- lastSlash = index;
1785
- dots = 0;
1786
- } else if (char === "." && dots !== -1) {
1787
- ++dots;
1788
- } else {
1789
- dots = -1;
1790
- }
1791
- }
1792
- return res;
1793
- }
1794
- const isAbsolute = function(p2) {
1795
- return _IS_ABSOLUTE_RE.test(p2);
1796
- };
1797
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1798
- const intToChar = new Uint8Array(64);
1799
- const charToInt = new Uint8Array(128);
1800
- for (let i = 0; i < chars.length; i++) {
1801
- const c = chars.charCodeAt(i);
1802
- intToChar[i] = c;
1803
- charToInt[c] = i;
1804
- }
1805
- var UrlType;
1806
- (function(UrlType2) {
1807
- UrlType2[UrlType2["Empty"] = 1] = "Empty";
1808
- UrlType2[UrlType2["Hash"] = 2] = "Hash";
1809
- UrlType2[UrlType2["Query"] = 3] = "Query";
1810
- UrlType2[UrlType2["RelativePath"] = 4] = "RelativePath";
1811
- UrlType2[UrlType2["AbsolutePath"] = 5] = "AbsolutePath";
1812
- UrlType2[UrlType2["SchemeRelative"] = 6] = "SchemeRelative";
1813
- UrlType2[UrlType2["Absolute"] = 7] = "Absolute";
1814
- })(UrlType || (UrlType = {}));
1815
- const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
1816
- const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
1817
- function extractLocation(urlLike) {
1818
- if (!urlLike.includes(":")) {
1819
- return [urlLike];
1820
- }
1821
- const regExp = /(.+?)(?::(\d+))?(?::(\d+))?$/;
1822
- const parts = regExp.exec(urlLike.replace(/^\(|\)$/g, ""));
1823
- if (!parts) {
1824
- return [urlLike];
1825
- }
1826
- let url = parts[1];
1827
- if (url.startsWith("async ")) {
1828
- url = url.slice(6);
1829
- }
1830
- if (url.startsWith("http:") || url.startsWith("https:")) {
1831
- const urlObj = new URL(url);
1832
- urlObj.searchParams.delete("import");
1833
- urlObj.searchParams.delete("browserv");
1834
- url = urlObj.pathname + urlObj.hash + urlObj.search;
1835
- }
1836
- if (url.startsWith("/@fs/")) {
1837
- const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
1838
- url = url.slice(isWindows ? 5 : 4);
1839
- }
1840
- return [
1841
- url,
1842
- parts[2] || void 0,
1843
- parts[3] || void 0
1844
- ];
1845
- }
1846
- function parseSingleFFOrSafariStack(raw) {
1847
- let line = raw.trim();
1848
- if (SAFARI_NATIVE_CODE_REGEXP.test(line)) {
1849
- return null;
1850
- }
1851
- if (line.includes(" > eval")) {
1852
- line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
1853
- }
1854
- if (!line.includes("@") && !line.includes(":")) {
1855
- return null;
1856
- }
1857
- const functionNameRegex = /((.*".+"[^@]*)?[^@]*)(@)/;
1858
- const matches = line.match(functionNameRegex);
1859
- const functionName = matches && matches[1] ? matches[1] : void 0;
1860
- const [url, lineNumber, columnNumber] = extractLocation(line.replace(functionNameRegex, ""));
1861
- if (!url || !lineNumber || !columnNumber) {
1862
- return null;
1863
- }
1864
- return {
1865
- file: url,
1866
- method: functionName || "",
1867
- line: Number.parseInt(lineNumber),
1868
- column: Number.parseInt(columnNumber)
1869
- };
1870
- }
1871
- function parseSingleStack(raw) {
1872
- const line = raw.trim();
1873
- if (!CHROME_IE_STACK_REGEXP.test(line)) {
1874
- return parseSingleFFOrSafariStack(line);
1875
- }
1876
- return parseSingleV8Stack(line);
1877
- }
1878
- function parseSingleV8Stack(raw) {
1879
- let line = raw.trim();
1880
- if (!CHROME_IE_STACK_REGEXP.test(line)) {
1881
- return null;
1882
- }
1883
- if (line.includes("(eval ")) {
1884
- line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
1885
- }
1886
- let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
1887
- const location = sanitizedLine.match(/ (\(.+\)$)/);
1888
- sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
1889
- const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
1890
- let method = location && sanitizedLine || "";
1891
- let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
1892
- if (!file || !lineNumber || !columnNumber) {
1893
- return null;
1894
- }
1895
- if (method.startsWith("async ")) {
1896
- method = method.slice(6);
1897
- }
1898
- if (file.startsWith("file://")) {
1899
- file = file.slice(7);
1900
- }
1901
- file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve(file);
1902
- if (method) {
1903
- method = method.replace(/__vite_ssr_import_\d+__\./g, "");
1904
- }
1905
- return {
1906
- method,
1907
- file,
1908
- line: Number.parseInt(lineNumber),
1909
- column: Number.parseInt(columnNumber)
1910
- };
1911
- }
1912
- class PendingError extends Error {
1913
- constructor(message, task, note) {
1914
- super(message);
1915
- __publicField(this, "code", "VITEST_PENDING");
1916
- __publicField(this, "taskId");
1917
- this.message = message;
1918
- this.note = note;
1919
- this.taskId = task.id;
1920
- }
1921
- }
1922
- const fnMap = /* @__PURE__ */ new WeakMap();
1923
- const testFixtureMap = /* @__PURE__ */ new WeakMap();
1924
- const hooksMap = /* @__PURE__ */ new WeakMap();
1925
- function setFn(key, fn) {
1926
- fnMap.set(key, fn);
1927
- }
1928
- function setTestFixture(key, fixture) {
1929
- testFixtureMap.set(key, fixture);
1930
- }
1931
- function getTestFixture(key) {
1932
- return testFixtureMap.get(key);
1933
- }
1934
- function setHooks(key, hooks) {
1935
- hooksMap.set(key, hooks);
1936
- }
1937
- function getHooks(key) {
1938
- return hooksMap.get(key);
1939
- }
1940
- function mergeScopedFixtures(testFixtures, scopedFixtures) {
1941
- const scopedFixturesMap = scopedFixtures.reduce((map, fixture) => {
1942
- map[fixture.prop] = fixture;
1943
- return map;
1944
- }, {});
1945
- const newFixtures = {};
1946
- testFixtures.forEach((fixture) => {
1947
- const useFixture = scopedFixturesMap[fixture.prop] || { ...fixture };
1948
- newFixtures[useFixture.prop] = useFixture;
1949
- });
1950
- for (const fixtureKep in newFixtures) {
1951
- var _fixture$deps;
1952
- const fixture = newFixtures[fixtureKep];
1953
- fixture.deps = (_fixture$deps = fixture.deps) === null || _fixture$deps === void 0 ? void 0 : _fixture$deps.map((dep) => newFixtures[dep.prop]);
1954
- }
1955
- return Object.values(newFixtures);
1956
- }
1957
- function mergeContextFixtures(fixtures, context, runner2) {
1958
- const fixtureOptionKeys = [
1959
- "auto",
1960
- "injected",
1961
- "scope"
1962
- ];
1963
- const fixtureArray = Object.entries(fixtures).map(([prop, value]) => {
1964
- const fixtureItem = { value };
1965
- if (Array.isArray(value) && value.length >= 2 && isObject(value[1]) && Object.keys(value[1]).some((key) => fixtureOptionKeys.includes(key))) {
1966
- var _runner$injectValue;
1967
- Object.assign(fixtureItem, value[1]);
1968
- const userValue = value[0];
1969
- fixtureItem.value = fixtureItem.injected ? ((_runner$injectValue = runner2.injectValue) === null || _runner$injectValue === void 0 ? void 0 : _runner$injectValue.call(runner2, prop)) ?? userValue : userValue;
1970
- }
1971
- fixtureItem.scope = fixtureItem.scope || "test";
1972
- if (fixtureItem.scope === "worker" && !runner2.getWorkerContext) {
1973
- fixtureItem.scope = "file";
1974
- }
1975
- fixtureItem.prop = prop;
1976
- fixtureItem.isFn = typeof fixtureItem.value === "function";
1977
- return fixtureItem;
1978
- });
1979
- if (Array.isArray(context.fixtures)) {
1980
- context.fixtures = context.fixtures.concat(fixtureArray);
1981
- } else {
1982
- context.fixtures = fixtureArray;
1983
- }
1984
- fixtureArray.forEach((fixture) => {
1985
- if (fixture.isFn) {
1986
- const usedProps = getUsedProps(fixture.value);
1987
- if (usedProps.length) {
1988
- fixture.deps = context.fixtures.filter(({ prop }) => prop !== fixture.prop && usedProps.includes(prop));
1989
- }
1990
- if (fixture.scope !== "test") {
1991
- var _fixture$deps2;
1992
- (_fixture$deps2 = fixture.deps) === null || _fixture$deps2 === void 0 ? void 0 : _fixture$deps2.forEach((dep) => {
1993
- if (!dep.isFn) {
1994
- return;
1995
- }
1996
- if (fixture.scope === "worker" && dep.scope === "worker") {
1997
- return;
1998
- }
1999
- if (fixture.scope === "file" && dep.scope !== "test") {
2000
- return;
2001
- }
2002
- throw new SyntaxError(`cannot use the ${dep.scope} fixture "${dep.prop}" inside the ${fixture.scope} fixture "${fixture.prop}"`);
2003
- });
2004
- }
2005
- }
2006
- });
2007
- return context;
2008
- }
2009
- const fixtureValueMaps = /* @__PURE__ */ new Map();
2010
- const cleanupFnArrayMap = /* @__PURE__ */ new Map();
2011
- function withFixtures(runner2, fn, testContext) {
2012
- return (hookContext) => {
2013
- const context = hookContext || testContext;
2014
- if (!context) {
2015
- return fn({});
2016
- }
2017
- const fixtures = getTestFixture(context);
2018
- if (!(fixtures === null || fixtures === void 0 ? void 0 : fixtures.length)) {
2019
- return fn(context);
2020
- }
2021
- const usedProps = getUsedProps(fn);
2022
- const hasAutoFixture = fixtures.some(({ auto }) => auto);
2023
- if (!usedProps.length && !hasAutoFixture) {
2024
- return fn(context);
2025
- }
2026
- if (!fixtureValueMaps.get(context)) {
2027
- fixtureValueMaps.set(context, /* @__PURE__ */ new Map());
2028
- }
2029
- const fixtureValueMap = fixtureValueMaps.get(context);
2030
- if (!cleanupFnArrayMap.has(context)) {
2031
- cleanupFnArrayMap.set(context, []);
2032
- }
2033
- const cleanupFnArray = cleanupFnArrayMap.get(context);
2034
- const usedFixtures = fixtures.filter(({ prop, auto }) => auto || usedProps.includes(prop));
2035
- const pendingFixtures = resolveDeps(usedFixtures);
2036
- if (!pendingFixtures.length) {
2037
- return fn(context);
2038
- }
2039
- async function resolveFixtures() {
2040
- for (const fixture of pendingFixtures) {
2041
- if (fixtureValueMap.has(fixture)) {
2042
- continue;
2043
- }
2044
- const resolvedValue = await resolveFixtureValue(runner2, fixture, context, cleanupFnArray);
2045
- context[fixture.prop] = resolvedValue;
2046
- fixtureValueMap.set(fixture, resolvedValue);
2047
- if (fixture.scope === "test") {
2048
- cleanupFnArray.unshift(() => {
2049
- fixtureValueMap.delete(fixture);
2050
- });
2051
- }
2052
- }
2053
- }
2054
- return resolveFixtures().then(() => fn(context));
2055
- };
2056
- }
2057
- const globalFixturePromise = /* @__PURE__ */ new WeakMap();
2058
- function resolveFixtureValue(runner2, fixture, context, cleanupFnArray) {
2059
- var _runner$getWorkerCont;
2060
- const fileContext = getFileContext(context.task.file);
2061
- const workerContext = (_runner$getWorkerCont = runner2.getWorkerContext) === null || _runner$getWorkerCont === void 0 ? void 0 : _runner$getWorkerCont.call(runner2);
2062
- if (!fixture.isFn) {
2063
- var _fixture$prop;
2064
- fileContext[_fixture$prop = fixture.prop] ?? (fileContext[_fixture$prop] = fixture.value);
2065
- if (workerContext) {
2066
- var _fixture$prop2;
2067
- workerContext[_fixture$prop2 = fixture.prop] ?? (workerContext[_fixture$prop2] = fixture.value);
2068
- }
2069
- return fixture.value;
2070
- }
2071
- if (fixture.scope === "test") {
2072
- return resolveFixtureFunction(fixture.value, context, cleanupFnArray);
2073
- }
2074
- if (globalFixturePromise.has(fixture)) {
2075
- return globalFixturePromise.get(fixture);
2076
- }
2077
- let fixtureContext;
2078
- if (fixture.scope === "worker") {
2079
- if (!workerContext) {
2080
- throw new TypeError("[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner.");
2081
- }
2082
- fixtureContext = workerContext;
2083
- } else {
2084
- fixtureContext = fileContext;
2085
- }
2086
- if (fixture.prop in fixtureContext) {
2087
- return fixtureContext[fixture.prop];
2088
- }
2089
- if (!cleanupFnArrayMap.has(fixtureContext)) {
2090
- cleanupFnArrayMap.set(fixtureContext, []);
2091
- }
2092
- const cleanupFnFileArray = cleanupFnArrayMap.get(fixtureContext);
2093
- const promise = resolveFixtureFunction(fixture.value, fixtureContext, cleanupFnFileArray).then((value) => {
2094
- fixtureContext[fixture.prop] = value;
2095
- globalFixturePromise.delete(fixture);
2096
- return value;
2097
- });
2098
- globalFixturePromise.set(fixture, promise);
2099
- return promise;
2100
- }
2101
- async function resolveFixtureFunction(fixtureFn, context, cleanupFnArray) {
2102
- const useFnArgPromise = createDefer();
2103
- let isUseFnArgResolved = false;
2104
- const fixtureReturn = fixtureFn(context, async (useFnArg) => {
2105
- isUseFnArgResolved = true;
2106
- useFnArgPromise.resolve(useFnArg);
2107
- const useReturnPromise = createDefer();
2108
- cleanupFnArray.push(async () => {
2109
- useReturnPromise.resolve();
2110
- await fixtureReturn;
2111
- });
2112
- await useReturnPromise;
2113
- }).catch((e) => {
2114
- if (!isUseFnArgResolved) {
2115
- useFnArgPromise.reject(e);
2116
- return;
2117
- }
2118
- throw e;
2119
- });
2120
- return useFnArgPromise;
2121
- }
2122
- function resolveDeps(fixtures, depSet = /* @__PURE__ */ new Set(), pendingFixtures = []) {
2123
- fixtures.forEach((fixture) => {
2124
- if (pendingFixtures.includes(fixture)) {
2125
- return;
2126
- }
2127
- if (!fixture.isFn || !fixture.deps) {
2128
- pendingFixtures.push(fixture);
2129
- return;
2130
- }
2131
- if (depSet.has(fixture)) {
2132
- throw new Error(`Circular fixture dependency detected: ${fixture.prop} <- ${[...depSet].reverse().map((d) => d.prop).join(" <- ")}`);
2133
- }
2134
- depSet.add(fixture);
2135
- resolveDeps(fixture.deps, depSet, pendingFixtures);
2136
- pendingFixtures.push(fixture);
2137
- depSet.clear();
2138
- });
2139
- return pendingFixtures;
2140
- }
2141
- function getUsedProps(fn) {
2142
- let fnString = stripLiteral(fn.toString());
2143
- if (/__async\((?:this|null), (?:null|arguments|\[[_0-9, ]*\]), function\*/.test(fnString)) {
2144
- fnString = fnString.split(/__async\((?:this|null),/)[1];
2145
- }
2146
- const match = fnString.match(/[^(]*\(([^)]*)/);
2147
- if (!match) {
2148
- return [];
2149
- }
2150
- const args = splitByComma(match[1]);
2151
- if (!args.length) {
2152
- return [];
2153
- }
2154
- let first = args[0];
2155
- if ("__VITEST_FIXTURE_INDEX__" in fn) {
2156
- first = args[fn.__VITEST_FIXTURE_INDEX__];
2157
- if (!first) {
2158
- return [];
2159
- }
2160
- }
2161
- if (!(first.startsWith("{") && first.endsWith("}"))) {
2162
- throw new Error(`The first argument inside a fixture must use object destructuring pattern, e.g. ({ test } => {}). Instead, received "${first}".`);
2163
- }
2164
- const _first = first.slice(1, -1).replace(/\s/g, "");
2165
- const props = splitByComma(_first).map((prop) => {
2166
- return prop.replace(/:.*|=.*/g, "");
2167
- });
2168
- const last = props.at(-1);
2169
- if (last && last.startsWith("...")) {
2170
- throw new Error(`Rest parameters are not supported in fixtures, received "${last}".`);
2171
- }
2172
- return props;
2173
- }
2174
- function splitByComma(s) {
2175
- const result = [];
2176
- const stack = [];
2177
- let start = 0;
2178
- for (let i = 0; i < s.length; i++) {
2179
- if (s[i] === "{" || s[i] === "[") {
2180
- stack.push(s[i] === "{" ? "}" : "]");
2181
- } else if (s[i] === stack[stack.length - 1]) {
2182
- stack.pop();
2183
- } else if (!stack.length && s[i] === ",") {
2184
- const token = s.substring(start, i).trim();
2185
- if (token) {
2186
- result.push(token);
2187
- }
2188
- start = i + 1;
2189
- }
2190
- }
2191
- const lastToken = s.substring(start).trim();
2192
- if (lastToken) {
2193
- result.push(lastToken);
2194
- }
2195
- return result;
2196
- }
2197
- function createChainable(keys, fn) {
2198
- function create(context) {
2199
- const chain2 = function(...args) {
2200
- return fn.apply(context, args);
2201
- };
2202
- Object.assign(chain2, fn);
2203
- chain2.withContext = () => chain2.bind(context);
2204
- chain2.setContext = (key, value) => {
2205
- context[key] = value;
2206
- };
2207
- chain2.mergeContext = (ctx) => {
2208
- Object.assign(context, ctx);
2209
- };
2210
- for (const key of keys) {
2211
- Object.defineProperty(chain2, key, { get() {
2212
- return create({
2213
- ...context,
2214
- [key]: true
2215
- });
2216
- } });
2217
- }
2218
- return chain2;
2219
- }
2220
- const chain = create({});
2221
- chain.fn = fn;
2222
- return chain;
2223
- }
2224
- function generateHash(str) {
2225
- let hash = 0;
2226
- if (str.length === 0) {
2227
- return `${hash}`;
2228
- }
2229
- for (let i = 0; i < str.length; i++) {
2230
- const char = str.charCodeAt(i);
2231
- hash = (hash << 5) - hash + char;
2232
- hash = hash & hash;
2233
- }
2234
- return `${hash}`;
2235
- }
2236
- function findTestFileStackTrace(testFilePath, error) {
2237
- const lines = error.split("\n").slice(1);
2238
- for (const line of lines) {
2239
- const stack = parseSingleStack(line);
2240
- if (stack && stack.file === testFilePath) {
2241
- return stack;
2242
- }
2243
- }
2244
- }
2245
- const suite = createSuite();
2246
- createTest(function(name, optionsOrFn, optionsOrTest) {
2247
- getCurrentSuite().test.fn.call(this, formatName(name), optionsOrFn, optionsOrTest);
2248
- });
2249
- let runner;
2250
- let defaultSuite;
2251
- let currentTestFilepath;
2252
- function assert(condition, message) {
2253
- if (!condition) {
2254
- throw new Error(`Vitest failed to find ${message}. This is a bug in Vitest. Please, open an issue with reproduction.`);
2255
- }
2256
- }
2257
- function getRunner() {
2258
- assert(runner, "the runner");
2259
- return runner;
2260
- }
2261
- function getCurrentSuite() {
2262
- const currentSuite = collectorContext.currentSuite || defaultSuite;
2263
- assert(currentSuite, "the current suite");
2264
- return currentSuite;
2265
- }
2266
- function createSuiteHooks() {
2267
- return {
2268
- beforeAll: [],
2269
- afterAll: [],
2270
- beforeEach: [],
2271
- afterEach: []
2272
- };
2273
- }
2274
- function parseArguments(optionsOrFn, optionsOrTest) {
2275
- let options = {};
2276
- let fn;
2277
- if (typeof optionsOrTest === "object") {
2278
- if (typeof optionsOrFn === "object") {
2279
- throw new TypeError("Cannot use two objects as arguments. Please provide options and a function callback in that order.");
2280
- }
2281
- console.warn("Using an object as a third argument is deprecated. Vitest 4 will throw an error if the third argument is not a timeout number. Please use the second argument for options. See more at https://vitest.dev/guide/migration");
2282
- options = optionsOrTest;
2283
- } else if (typeof optionsOrTest === "number") {
2284
- options = { timeout: optionsOrTest };
2285
- } else if (typeof optionsOrFn === "object") {
2286
- options = optionsOrFn;
2287
- }
2288
- if (typeof optionsOrFn === "function") {
2289
- if (typeof optionsOrTest === "function") {
2290
- throw new TypeError("Cannot use two functions as arguments. Please use the second argument for options.");
2291
- }
2292
- fn = optionsOrFn;
2293
- } else if (typeof optionsOrTest === "function") {
2294
- fn = optionsOrTest;
2295
- }
2296
- return {
2297
- options,
2298
- handler: fn
2299
- };
2300
- }
2301
- function createSuiteCollector(name, factory = () => {
2302
- }, mode, each, suiteOptions, parentCollectorFixtures) {
2303
- const tasks = [];
2304
- let suite2;
2305
- initSuite();
2306
- const task = function(name2 = "", options = {}) {
2307
- var _collectorContext$cur;
2308
- const timeout = (options === null || options === void 0 ? void 0 : options.timeout) ?? runner.config.testTimeout;
2309
- const task2 = {
2310
- id: "",
2311
- name: name2,
2312
- suite: (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.suite,
2313
- each: options.each,
2314
- fails: options.fails,
2315
- context: void 0,
2316
- type: "test",
2317
- file: void 0,
2318
- timeout,
2319
- retry: options.retry ?? runner.config.retry,
2320
- repeats: options.repeats,
2321
- mode: options.only ? "only" : options.skip ? "skip" : options.todo ? "todo" : "run",
2322
- meta: options.meta ?? /* @__PURE__ */ Object.create(null),
2323
- annotations: []
2324
- };
2325
- const handler = options.handler;
2326
- if (task2.mode === "run" && !handler) {
2327
- task2.mode = "todo";
2328
- }
2329
- if (options.concurrent || !options.sequential && runner.config.sequence.concurrent) {
2330
- task2.concurrent = true;
2331
- }
2332
- task2.shuffle = suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle;
2333
- const context = createTestContext(task2, runner);
2334
- Object.defineProperty(task2, "context", {
2335
- value: context,
2336
- enumerable: false
2337
- });
2338
- setTestFixture(context, options.fixtures);
2339
- const limit = Error.stackTraceLimit;
2340
- Error.stackTraceLimit = 15;
2341
- const stackTraceError = new Error("STACK_TRACE_ERROR");
2342
- Error.stackTraceLimit = limit;
2343
- if (handler) {
2344
- setFn(task2, withTimeout(withAwaitAsyncAssertions(withFixtures(runner, handler, context), task2), timeout, false, stackTraceError, (_, error) => abortIfTimeout([context], error)));
2345
- }
2346
- if (runner.config.includeTaskLocation) {
2347
- const error = stackTraceError.stack;
2348
- const stack = findTestFileStackTrace(currentTestFilepath, error);
2349
- if (stack) {
2350
- task2.location = {
2351
- line: stack.line,
2352
- column: stack.column
2353
- };
2354
- }
2355
- }
2356
- tasks.push(task2);
2357
- return task2;
2358
- };
2359
- const test = createTest(function(name2, optionsOrFn, optionsOrTest) {
2360
- let { options, handler } = parseArguments(optionsOrFn, optionsOrTest);
2361
- if (typeof suiteOptions === "object") {
2362
- options = Object.assign({}, suiteOptions, options);
2363
- }
2364
- options.concurrent = this.concurrent || !this.sequential && (options === null || options === void 0 ? void 0 : options.concurrent);
2365
- options.sequential = this.sequential || !this.concurrent && (options === null || options === void 0 ? void 0 : options.sequential);
2366
- const test2 = task(formatName(name2), {
2367
- ...this,
2368
- ...options,
2369
- handler
2370
- });
2371
- test2.type = "test";
2372
- });
2373
- let collectorFixtures = parentCollectorFixtures;
2374
- const collector = {
2375
- type: "collector",
2376
- name,
2377
- mode,
2378
- suite: suite2,
2379
- options: suiteOptions,
2380
- test,
2381
- tasks,
2382
- collect,
2383
- task,
2384
- clear,
2385
- on: addHook,
2386
- fixtures() {
2387
- return collectorFixtures;
2388
- },
2389
- scoped(fixtures) {
2390
- const parsed = mergeContextFixtures(fixtures, { fixtures: collectorFixtures }, runner);
2391
- if (parsed.fixtures) {
2392
- collectorFixtures = parsed.fixtures;
2393
- }
2394
- }
2395
- };
2396
- function addHook(name2, ...fn) {
2397
- getHooks(suite2)[name2].push(...fn);
2398
- }
2399
- function initSuite(includeLocation) {
2400
- var _collectorContext$cur2;
2401
- if (typeof suiteOptions === "number") {
2402
- suiteOptions = { timeout: suiteOptions };
2403
- }
2404
- suite2 = {
2405
- id: "",
2406
- type: "suite",
2407
- name,
2408
- suite: (_collectorContext$cur2 = collectorContext.currentSuite) === null || _collectorContext$cur2 === void 0 ? void 0 : _collectorContext$cur2.suite,
2409
- mode,
2410
- each,
2411
- file: void 0,
2412
- shuffle: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.shuffle,
2413
- tasks: [],
2414
- meta: /* @__PURE__ */ Object.create(null),
2415
- concurrent: suiteOptions === null || suiteOptions === void 0 ? void 0 : suiteOptions.concurrent
2416
- };
2417
- setHooks(suite2, createSuiteHooks());
2418
- }
2419
- function clear() {
2420
- tasks.length = 0;
2421
- initSuite();
2422
- }
2423
- async function collect(file) {
2424
- if (!file) {
2425
- throw new TypeError("File is required to collect tasks.");
2426
- }
2427
- if (factory) {
2428
- await runWithSuite(collector, () => factory(test));
2429
- }
2430
- const allChildren = [];
2431
- for (const i of tasks) {
2432
- allChildren.push(i.type === "collector" ? await i.collect(file) : i);
2433
- }
2434
- suite2.file = file;
2435
- suite2.tasks = allChildren;
2436
- allChildren.forEach((task2) => {
2437
- task2.file = file;
2438
- });
2439
- return suite2;
2440
- }
2441
- collectTask(collector);
2442
- return collector;
2443
- }
2444
- function withAwaitAsyncAssertions(fn, task) {
2445
- return async (...args) => {
2446
- const fnResult = await fn(...args);
2447
- if (task.promises) {
2448
- const result = await Promise.allSettled(task.promises);
2449
- const errors = result.map((r) => r.status === "rejected" ? r.reason : void 0).filter(Boolean);
2450
- if (errors.length) {
2451
- throw errors;
2452
- }
2453
- }
2454
- return fnResult;
2455
- };
2456
- }
2457
- function createSuite() {
2458
- function suiteFn(name, factoryOrOptions, optionsOrFactory) {
2459
- var _currentSuite$options;
2460
- let mode = this.only ? "only" : this.skip ? "skip" : this.todo ? "todo" : "run";
2461
- const currentSuite = collectorContext.currentSuite || defaultSuite;
2462
- let { options, handler: factory } = parseArguments(factoryOrOptions, optionsOrFactory);
2463
- if (mode === "run" && !factory) {
2464
- mode = "todo";
2465
- }
2466
- const isConcurrentSpecified = options.concurrent || this.concurrent || options.sequential === false;
2467
- const isSequentialSpecified = options.sequential || this.sequential || options.concurrent === false;
2468
- options = {
2469
- ...currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.options,
2470
- ...options,
2471
- shuffle: this.shuffle ?? options.shuffle ?? (currentSuite === null || currentSuite === void 0 || (_currentSuite$options = currentSuite.options) === null || _currentSuite$options === void 0 ? void 0 : _currentSuite$options.shuffle) ?? void 0
2472
- };
2473
- const isConcurrent = isConcurrentSpecified || options.concurrent && !isSequentialSpecified;
2474
- const isSequential = isSequentialSpecified || options.sequential && !isConcurrentSpecified;
2475
- options.concurrent = isConcurrent && !isSequential;
2476
- options.sequential = isSequential && !isConcurrent;
2477
- return createSuiteCollector(formatName(name), factory, mode, this.each, options, currentSuite === null || currentSuite === void 0 ? void 0 : currentSuite.fixtures());
2478
- }
2479
- suiteFn.each = function(cases, ...args) {
2480
- const suite2 = this.withContext();
2481
- this.setContext("each", true);
2482
- if (Array.isArray(cases) && args.length) {
2483
- cases = formatTemplateString(cases, args);
2484
- }
2485
- return (name, optionsOrFn, fnOrOptions) => {
2486
- const _name = formatName(name);
2487
- const arrayOnlyCases = cases.every(Array.isArray);
2488
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
2489
- const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
2490
- cases.forEach((i, idx) => {
2491
- const items = Array.isArray(i) ? i : [i];
2492
- if (fnFirst) {
2493
- if (arrayOnlyCases) {
2494
- suite2(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options);
2495
- } else {
2496
- suite2(formatTitle(_name, items, idx), handler ? () => handler(i) : void 0, options);
2497
- }
2498
- } else {
2499
- if (arrayOnlyCases) {
2500
- suite2(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0);
2501
- } else {
2502
- suite2(formatTitle(_name, items, idx), options, handler ? () => handler(i) : void 0);
2503
- }
2504
- }
2505
- });
2506
- this.setContext("each", void 0);
2507
- };
2508
- };
2509
- suiteFn.for = function(cases, ...args) {
2510
- if (Array.isArray(cases) && args.length) {
2511
- cases = formatTemplateString(cases, args);
2512
- }
2513
- return (name, optionsOrFn, fnOrOptions) => {
2514
- const name_ = formatName(name);
2515
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
2516
- cases.forEach((item, idx) => {
2517
- suite(formatTitle(name_, toArray(item), idx), options, handler ? () => handler(item) : void 0);
2518
- });
2519
- };
2520
- };
2521
- suiteFn.skipIf = (condition) => condition ? suite.skip : suite;
2522
- suiteFn.runIf = (condition) => condition ? suite : suite.skip;
2523
- return createChainable([
2524
- "concurrent",
2525
- "sequential",
2526
- "shuffle",
2527
- "skip",
2528
- "only",
2529
- "todo"
2530
- ], suiteFn);
2531
- }
2532
- function createTaskCollector(fn, context) {
2533
- const taskFn = fn;
2534
- taskFn.each = function(cases, ...args) {
2535
- const test = this.withContext();
2536
- this.setContext("each", true);
2537
- if (Array.isArray(cases) && args.length) {
2538
- cases = formatTemplateString(cases, args);
2539
- }
2540
- return (name, optionsOrFn, fnOrOptions) => {
2541
- const _name = formatName(name);
2542
- const arrayOnlyCases = cases.every(Array.isArray);
2543
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
2544
- const fnFirst = typeof optionsOrFn === "function" && typeof fnOrOptions === "object";
2545
- cases.forEach((i, idx) => {
2546
- const items = Array.isArray(i) ? i : [i];
2547
- if (fnFirst) {
2548
- if (arrayOnlyCases) {
2549
- test(formatTitle(_name, items, idx), handler ? () => handler(...items) : void 0, options);
2550
- } else {
2551
- test(formatTitle(_name, items, idx), handler ? () => handler(i) : void 0, options);
2552
- }
2553
- } else {
2554
- if (arrayOnlyCases) {
2555
- test(formatTitle(_name, items, idx), options, handler ? () => handler(...items) : void 0);
2556
- } else {
2557
- test(formatTitle(_name, items, idx), options, handler ? () => handler(i) : void 0);
2558
- }
2559
- }
2560
- });
2561
- this.setContext("each", void 0);
2562
- };
2563
- };
2564
- taskFn.for = function(cases, ...args) {
2565
- const test = this.withContext();
2566
- if (Array.isArray(cases) && args.length) {
2567
- cases = formatTemplateString(cases, args);
2568
- }
2569
- return (name, optionsOrFn, fnOrOptions) => {
2570
- const _name = formatName(name);
2571
- const { options, handler } = parseArguments(optionsOrFn, fnOrOptions);
2572
- cases.forEach((item, idx) => {
2573
- const handlerWrapper = handler ? (ctx) => handler(item, ctx) : void 0;
2574
- if (handlerWrapper) {
2575
- handlerWrapper.__VITEST_FIXTURE_INDEX__ = 1;
2576
- handlerWrapper.toString = () => handler.toString();
2577
- }
2578
- test(formatTitle(_name, toArray(item), idx), options, handlerWrapper);
2579
- });
2580
- };
2581
- };
2582
- taskFn.skipIf = function(condition) {
2583
- return condition ? this.skip : this;
2584
- };
2585
- taskFn.runIf = function(condition) {
2586
- return condition ? this : this.skip;
2587
- };
2588
- taskFn.scoped = function(fixtures) {
2589
- const collector = getCurrentSuite();
2590
- collector.scoped(fixtures);
2591
- };
2592
- taskFn.extend = function(fixtures) {
2593
- const _context = mergeContextFixtures(fixtures, context || {}, runner);
2594
- const originalWrapper = fn;
2595
- return createTest(function(name, optionsOrFn, optionsOrTest) {
2596
- var _collector$options;
2597
- const collector = getCurrentSuite();
2598
- const scopedFixtures = collector.fixtures();
2599
- const context2 = { ...this };
2600
- if (scopedFixtures) {
2601
- context2.fixtures = mergeScopedFixtures(context2.fixtures || [], scopedFixtures);
2602
- }
2603
- const { handler, options } = parseArguments(optionsOrFn, optionsOrTest);
2604
- const timeout = options.timeout ?? ((_collector$options = collector.options) === null || _collector$options === void 0 ? void 0 : _collector$options.timeout) ?? void 0;
2605
- originalWrapper.call(context2, formatName(name), handler, timeout);
2606
- }, _context);
2607
- };
2608
- const _test = createChainable([
2609
- "concurrent",
2610
- "sequential",
2611
- "skip",
2612
- "only",
2613
- "todo",
2614
- "fails"
2615
- ], taskFn);
2616
- if (context) {
2617
- _test.mergeContext(context);
2618
- }
2619
- return _test;
2620
- }
2621
- function createTest(fn, context) {
2622
- return createTaskCollector(fn, context);
2623
- }
2624
- function formatName(name) {
2625
- return typeof name === "string" ? name : typeof name === "function" ? name.name || "<anonymous>" : String(name);
2626
- }
2627
- function formatTitle(template, items, idx) {
2628
- if (template.includes("%#") || template.includes("%$")) {
2629
- template = template.replace(/%%/g, "__vitest_escaped_%__").replace(/%#/g, `${idx}`).replace(/%\$/g, `${idx + 1}`).replace(/__vitest_escaped_%__/g, "%%");
2630
- }
2631
- const count = template.split("%").length - 1;
2632
- if (template.includes("%f")) {
2633
- const placeholders = template.match(/%f/g) || [];
2634
- placeholders.forEach((_, i) => {
2635
- if (isNegativeNaN(items[i]) || Object.is(items[i], -0)) {
2636
- let occurrence = 0;
2637
- template = template.replace(/%f/g, (match) => {
2638
- occurrence++;
2639
- return occurrence === i + 1 ? "-%f" : match;
2640
- });
2641
- }
2642
- });
2643
- }
2644
- let formatted = format(template, ...items.slice(0, count));
2645
- const isObjectItem = isObject(items[0]);
2646
- formatted = formatted.replace(/\$([$\w.]+)/g, (_, key) => {
2647
- const isArrayKey = /^\d+$/.test(key);
2648
- if (!isObjectItem && !isArrayKey) {
2649
- return `$${key}`;
2650
- }
2651
- const arrayElement = isArrayKey ? objectAttr(items, key) : void 0;
2652
- const value = isObjectItem ? objectAttr(items[0], key, arrayElement) : arrayElement;
2653
- return objDisplay(value, { truncate: void 0 });
2654
- });
2655
- return formatted;
2656
- }
2657
- function formatTemplateString(cases, args) {
2658
- const header = cases.join("").trim().replace(/ /g, "").split("\n").map((i) => i.split("|"))[0];
2659
- const res = [];
2660
- for (let i = 0; i < Math.floor(args.length / header.length); i++) {
2661
- const oneCase = {};
2662
- for (let j = 0; j < header.length; j++) {
2663
- oneCase[header[j]] = args[i * header.length + j];
2664
- }
2665
- res.push(oneCase);
2666
- }
2667
- return res;
2668
- }
2669
- globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
2670
- globalThis.performance ? globalThis.performance.now.bind(globalThis.performance) : Date.now;
2671
- getSafeTimers();
2672
- const packs = /* @__PURE__ */ new Map();
2673
- const eventsPacks = [];
2674
- const pendingTasksUpdates = [];
2675
- function sendTasksUpdate(runner2) {
2676
- if (packs.size) {
2677
- var _runner$onTaskUpdate;
2678
- const taskPacks = Array.from(packs).map(([id, task]) => {
2679
- return [
2680
- id,
2681
- task[0],
2682
- task[1]
2683
- ];
2684
- });
2685
- const p2 = (_runner$onTaskUpdate = runner2.onTaskUpdate) === null || _runner$onTaskUpdate === void 0 ? void 0 : _runner$onTaskUpdate.call(runner2, taskPacks, eventsPacks);
2686
- if (p2) {
2687
- pendingTasksUpdates.push(p2);
2688
- p2.then(() => pendingTasksUpdates.splice(pendingTasksUpdates.indexOf(p2), 1), () => {
2689
- });
2690
- }
2691
- eventsPacks.length = 0;
2692
- packs.clear();
2693
- }
2694
- }
2695
- async function finishSendTasksUpdate(runner2) {
2696
- sendTasksUpdate(runner2);
2697
- await Promise.all(pendingTasksUpdates);
2698
- }
2699
- const now = Date.now;
2700
- const collectorContext = {
2701
- currentSuite: null
2702
- };
2703
- function collectTask(task) {
2704
- var _collectorContext$cur;
2705
- (_collectorContext$cur = collectorContext.currentSuite) === null || _collectorContext$cur === void 0 ? void 0 : _collectorContext$cur.tasks.push(task);
2706
- }
2707
- async function runWithSuite(suite2, fn) {
2708
- const prev = collectorContext.currentSuite;
2709
- collectorContext.currentSuite = suite2;
2710
- await fn();
2711
- collectorContext.currentSuite = prev;
2712
- }
2713
- function withTimeout(fn, timeout, isHook = false, stackTraceError, onTimeout) {
2714
- if (timeout <= 0 || timeout === Number.POSITIVE_INFINITY) {
2715
- return fn;
2716
- }
2717
- const { setTimeout, clearTimeout } = getSafeTimers();
2718
- return function runWithTimeout(...args) {
2719
- const startTime = now();
2720
- const runner2 = getRunner();
2721
- runner2._currentTaskStartTime = startTime;
2722
- runner2._currentTaskTimeout = timeout;
2723
- return new Promise((resolve_, reject_) => {
2724
- var _timer$unref;
2725
- const timer = setTimeout(() => {
2726
- clearTimeout(timer);
2727
- rejectTimeoutError();
2728
- }, timeout);
2729
- (_timer$unref = timer.unref) === null || _timer$unref === void 0 ? void 0 : _timer$unref.call(timer);
2730
- function rejectTimeoutError() {
2731
- const error = makeTimeoutError(isHook, timeout, stackTraceError);
2732
- onTimeout === null || onTimeout === void 0 ? void 0 : onTimeout(args, error);
2733
- reject_(error);
2734
- }
2735
- function resolve2(result) {
2736
- runner2._currentTaskStartTime = void 0;
2737
- runner2._currentTaskTimeout = void 0;
2738
- clearTimeout(timer);
2739
- if (now() - startTime >= timeout) {
2740
- rejectTimeoutError();
2741
- return;
2742
- }
2743
- resolve_(result);
2744
- }
2745
- function reject(error) {
2746
- runner2._currentTaskStartTime = void 0;
2747
- runner2._currentTaskTimeout = void 0;
2748
- clearTimeout(timer);
2749
- reject_(error);
2750
- }
2751
- try {
2752
- const result = fn(...args);
2753
- if (typeof result === "object" && result != null && typeof result.then === "function") {
2754
- result.then(resolve2, reject);
2755
- } else {
2756
- resolve2(result);
2757
- }
2758
- } catch (error) {
2759
- reject(error);
2760
- }
2761
- });
2762
- };
2763
- }
2764
- const abortControllers = /* @__PURE__ */ new WeakMap();
2765
- function abortIfTimeout([context], error) {
2766
- if (context) {
2767
- abortContextSignal(context, error);
2768
- }
2769
- }
2770
- function abortContextSignal(context, error) {
2771
- const abortController = abortControllers.get(context);
2772
- abortController === null || abortController === void 0 ? void 0 : abortController.abort(error);
2773
- }
2774
- function createTestContext(test, runner2) {
2775
- var _runner$extendTaskCon;
2776
- const context = function() {
2777
- throw new Error("done() callback is deprecated, use promise instead");
2778
- };
2779
- let abortController = abortControllers.get(context);
2780
- if (!abortController) {
2781
- abortController = new AbortController();
2782
- abortControllers.set(context, abortController);
2783
- }
2784
- context.signal = abortController.signal;
2785
- context.task = test;
2786
- context.skip = (condition, note) => {
2787
- if (condition === false) {
2788
- return void 0;
2789
- }
2790
- test.result ?? (test.result = { state: "skip" });
2791
- test.result.pending = true;
2792
- throw new PendingError("test is skipped; abort execution", test, typeof condition === "string" ? condition : note);
2793
- };
2794
- async function annotate(message, location, type, attachment) {
2795
- const annotation = {
2796
- message,
2797
- type: type || "notice"
2798
- };
2799
- if (attachment) {
2800
- if (!attachment.body && !attachment.path) {
2801
- throw new TypeError(`Test attachment requires body or path to be set. Both are missing.`);
2802
- }
2803
- if (attachment.body && attachment.path) {
2804
- throw new TypeError(`Test attachment requires only one of "body" or "path" to be set. Both are specified.`);
2805
- }
2806
- annotation.attachment = attachment;
2807
- if (attachment.body instanceof Uint8Array) {
2808
- attachment.body = encodeUint8Array(attachment.body);
2809
- }
2810
- }
2811
- if (location) {
2812
- annotation.location = location;
2813
- }
2814
- if (!runner2.onTestAnnotate) {
2815
- throw new Error(`Test runner doesn't support test annotations.`);
2816
- }
2817
- await finishSendTasksUpdate(runner2);
2818
- const resolvedAnnotation = await runner2.onTestAnnotate(test, annotation);
2819
- test.annotations.push(resolvedAnnotation);
2820
- return resolvedAnnotation;
2821
- }
2822
- context.annotate = (message, type, attachment) => {
2823
- if (test.result && test.result.state !== "run") {
2824
- throw new Error(`Cannot annotate tests outside of the test run. The test "${test.name}" finished running with the "${test.result.state}" state already.`);
2825
- }
2826
- const stack = findTestFileStackTrace(test.file.filepath, new Error("STACK_TRACE").stack);
2827
- let location;
2828
- if (stack) {
2829
- location = {
2830
- file: stack.file,
2831
- line: stack.line,
2832
- column: stack.column
2833
- };
2834
- }
2835
- if (typeof type === "object") {
2836
- return recordAsyncAnnotation(test, annotate(message, location, void 0, type));
2837
- } else {
2838
- return recordAsyncAnnotation(test, annotate(message, location, type, attachment));
2839
- }
2840
- };
2841
- context.onTestFailed = (handler, timeout) => {
2842
- test.onFailed || (test.onFailed = []);
2843
- test.onFailed.push(withTimeout(handler, timeout ?? runner2.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
2844
- };
2845
- context.onTestFinished = (handler, timeout) => {
2846
- test.onFinished || (test.onFinished = []);
2847
- test.onFinished.push(withTimeout(handler, timeout ?? runner2.config.hookTimeout, true, new Error("STACK_TRACE_ERROR"), (_, error) => abortController.abort(error)));
2848
- };
2849
- return ((_runner$extendTaskCon = runner2.extendTaskContext) === null || _runner$extendTaskCon === void 0 ? void 0 : _runner$extendTaskCon.call(runner2, context)) || context;
2850
- }
2851
- function makeTimeoutError(isHook, timeout, stackTraceError) {
2852
- const message = `${isHook ? "Hook" : "Test"} timed out in ${timeout}ms.
2853
- If this is a long-running ${isHook ? "hook" : "test"}, pass a timeout value as the last argument or configure it globally with "${isHook ? "hookTimeout" : "testTimeout"}".`;
2854
- const error = new Error(message);
2855
- if (stackTraceError === null || stackTraceError === void 0 ? void 0 : stackTraceError.stack) {
2856
- error.stack = stackTraceError.stack.replace(error.message, stackTraceError.message);
2857
- }
2858
- return error;
2859
- }
2860
- const fileContexts = /* @__PURE__ */ new WeakMap();
2861
- function getFileContext(file) {
2862
- const context = fileContexts.get(file);
2863
- if (!context) {
2864
- throw new Error(`Cannot find file context for ${file.name}`);
2865
- }
2866
- return context;
2867
- }
2868
- const table = [];
2869
- for (let i = 65; i < 91; i++) {
2870
- table.push(String.fromCharCode(i));
2871
- }
2872
- for (let i = 97; i < 123; i++) {
2873
- table.push(String.fromCharCode(i));
2874
- }
2875
- for (let i = 0; i < 10; i++) {
2876
- table.push(i.toString(10));
2877
- }
2878
- function encodeUint8Array(bytes) {
2879
- let base64 = "";
2880
- const len = bytes.byteLength;
2881
- for (let i = 0; i < len; i += 3) {
2882
- if (len === i + 1) {
2883
- const a2 = (bytes[i] & 252) >> 2;
2884
- const b = (bytes[i] & 3) << 4;
2885
- base64 += table[a2];
2886
- base64 += table[b];
2887
- base64 += "==";
2888
- } else if (len === i + 2) {
2889
- const a2 = (bytes[i] & 252) >> 2;
2890
- const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
2891
- const c = (bytes[i + 1] & 15) << 2;
2892
- base64 += table[a2];
2893
- base64 += table[b];
2894
- base64 += table[c];
2895
- base64 += "=";
2896
- } else {
2897
- const a2 = (bytes[i] & 252) >> 2;
2898
- const b = (bytes[i] & 3) << 4 | (bytes[i + 1] & 240) >> 4;
2899
- const c = (bytes[i + 1] & 15) << 2 | (bytes[i + 2] & 192) >> 6;
2900
- const d = bytes[i + 2] & 63;
2901
- base64 += table[a2];
2902
- base64 += table[b];
2903
- base64 += table[c];
2904
- base64 += table[d];
2905
- }
2906
- }
2907
- return base64;
2908
- }
2909
- function recordAsyncAnnotation(test, promise) {
2910
- promise = promise.finally(() => {
2911
- if (!test.promises) {
2912
- return;
2913
- }
2914
- const index = test.promises.indexOf(promise);
2915
- if (index !== -1) {
2916
- test.promises.splice(index, 1);
2917
- }
2918
- });
2919
- if (!test.promises) {
2920
- test.promises = [];
2921
- }
2922
- test.promises.push(promise);
2923
- return promise;
2924
- }
2925
- function getUiAPI() {
2926
- return window.__vitest_ui_api__;
2927
- }
2928
- const ID_ALL = "__vitest_all__";
2929
- class IframeOrchestrator {
2930
- constructor() {
2931
- __publicField(this, "cancelled", false);
2932
- __publicField(this, "recreateNonIsolatedIframe", false);
2933
- __publicField(this, "iframes", /* @__PURE__ */ new Map());
2934
- debug("init orchestrator", getBrowserState().sessionId);
2935
- channel.addEventListener(
2936
- "message",
2937
- (e) => this.onIframeEvent(e)
2938
- );
2939
- globalChannel.addEventListener(
2940
- "message",
2941
- (e) => this.onGlobalChannelEvent(e)
2942
- );
2943
- }
2944
- async createTesters(options) {
2945
- this.cancelled = false;
2946
- const config = getConfig();
2947
- debug("create testers", options.files.join(", "));
2948
- const container = await getContainer(config);
2949
- if (config.browser.ui) {
2950
- container.className = "absolute origin-top mt-[8px]";
2951
- container.parentElement.setAttribute("data-ready", "true");
2952
- if (container.textContent) {
2953
- container.textContent = "";
2954
- }
2955
- }
2956
- if (config.browser.isolate === false) {
2957
- await this.runNonIsolatedTests(container, options);
2958
- return;
2959
- }
2960
- this.iframes.forEach((iframe) => iframe.remove());
2961
- this.iframes.clear();
2962
- for (let i = 0; i < options.files.length; i++) {
2963
- if (this.cancelled) {
2964
- return;
2965
- }
2966
- const file = options.files[i];
2967
- debug("create iframe", file);
2968
- await this.runIsolatedTestInIframe(
2969
- container,
2970
- file,
2971
- options
2972
- );
2973
- }
2974
- }
2975
- async cleanupTesters() {
2976
- const config = getConfig();
2977
- if (config.browser.isolate) {
2978
- const files = Array.from(this.iframes.keys());
2979
- const ui = getUiAPI();
2980
- if (ui && files[0]) {
2981
- const id = generateFileId(files[0]);
2982
- ui.setCurrentFileId(id);
2983
- }
2984
- return;
2985
- }
2986
- const iframe = this.iframes.get(ID_ALL);
2987
- if (!iframe) {
2988
- return;
2989
- }
2990
- await sendEventToIframe({
2991
- event: "cleanup",
2992
- iframeId: ID_ALL
2993
- });
2994
- this.recreateNonIsolatedIframe = true;
2995
- }
2996
- async runNonIsolatedTests(container, options) {
2997
- if (this.recreateNonIsolatedIframe) {
2998
- this.recreateNonIsolatedIframe = false;
2999
- this.iframes.get(ID_ALL).remove();
3000
- this.iframes.delete(ID_ALL);
3001
- debug("recreate non-isolated iframe");
3002
- }
3003
- if (!this.iframes.has(ID_ALL)) {
3004
- debug("preparing non-isolated iframe");
3005
- await this.prepareIframe(container, ID_ALL, options.startTime);
3006
- }
3007
- const config = getConfig();
3008
- const { width, height } = config.browser.viewport;
3009
- const iframe = this.iframes.get(ID_ALL);
3010
- await setIframeViewport(iframe, width, height);
3011
- debug("run non-isolated tests", options.files.join(", "));
3012
- await sendEventToIframe({
3013
- event: "execute",
3014
- iframeId: ID_ALL,
3015
- files: options.files,
3016
- method: options.method,
3017
- context: options.providedContext
3018
- });
3019
- }
3020
- async runIsolatedTestInIframe(container, file, options) {
3021
- const config = getConfig();
3022
- const { width, height } = config.browser.viewport;
3023
- if (this.iframes.has(file)) {
3024
- this.iframes.get(file).remove();
3025
- this.iframes.delete(file);
3026
- }
3027
- const iframe = await this.prepareIframe(container, file, options.startTime);
3028
- await setIframeViewport(iframe, width, height);
3029
- await sendEventToIframe({
3030
- event: "execute",
3031
- files: [file],
3032
- method: options.method,
3033
- iframeId: file,
3034
- context: options.providedContext
3035
- });
3036
- await sendEventToIframe({
3037
- event: "cleanup",
3038
- iframeId: file
3039
- });
3040
- }
3041
- async prepareIframe(container, iframeId, startTime) {
3042
- const iframe = this.createTestIframe(iframeId);
3043
- container.appendChild(iframe);
3044
- await new Promise((resolve2, reject) => {
3045
- iframe.onload = () => {
3046
- this.iframes.set(iframeId, iframe);
3047
- sendEventToIframe({
3048
- event: "prepare",
3049
- iframeId,
3050
- startTime
3051
- }).then(resolve2, reject);
3052
- };
3053
- iframe.onerror = (e) => {
3054
- if (typeof e === "string") {
3055
- reject(new Error(e));
3056
- } else if (e instanceof ErrorEvent) {
3057
- reject(e.error);
3058
- } else {
3059
- reject(new Error(`Cannot load the iframe ${iframeId}.`));
3060
- }
3061
- };
3062
- });
3063
- return iframe;
3064
- }
3065
- createTestIframe(iframeId) {
3066
- const iframe = document.createElement("iframe");
3067
- const src = `/?sessionId=${getBrowserState().sessionId}&iframeId=${iframeId}`;
3068
- iframe.setAttribute("loading", "eager");
3069
- iframe.setAttribute("src", src);
3070
- iframe.setAttribute("data-vitest", "true");
3071
- iframe.style.border = "none";
3072
- iframe.style.width = "100%";
3073
- iframe.style.height = "100%";
3074
- iframe.setAttribute("allowfullscreen", "true");
3075
- iframe.setAttribute("allow", "clipboard-write;");
3076
- iframe.setAttribute("name", "vitest-iframe");
3077
- return iframe;
3078
- }
3079
- async onGlobalChannelEvent(e) {
3080
- debug("global channel event", JSON.stringify(e.data));
3081
- switch (e.data.type) {
3082
- case "cancel": {
3083
- this.cancelled = true;
3084
- break;
3085
- }
3086
- }
3087
- }
3088
- async onIframeEvent(e) {
3089
- debug("iframe event", JSON.stringify(e.data));
3090
- switch (e.data.event) {
3091
- case "viewport": {
3092
- const { width, height, iframeId: id } = e.data;
3093
- const iframe = this.iframes.get(id);
3094
- if (!iframe) {
3095
- const error = `Cannot find iframe with id ${id}`;
3096
- channel.postMessage({
3097
- event: "viewport:fail",
3098
- iframeId: id,
3099
- error
3100
- });
3101
- await client.rpc.onUnhandledError(
3102
- {
3103
- name: "Teardown Error",
3104
- message: error
3105
- },
3106
- "Teardown Error"
3107
- );
3108
- break;
3109
- }
3110
- await setIframeViewport(iframe, width, height);
3111
- channel.postMessage({ event: "viewport:done", iframeId: id });
3112
- break;
3113
- }
3114
- default: {
3115
- if (typeof e.data.event === "string" && e.data.event.startsWith("response:")) {
3116
- break;
3117
- }
3118
- await client.rpc.onUnhandledError(
3119
- {
3120
- name: "Unexpected Event",
3121
- message: `Unexpected event: ${e.data.event}`
3122
- },
3123
- "Unexpected Event"
3124
- );
3125
- }
3126
- }
3127
- }
3128
- }
3129
- getBrowserState().orchestrator = new IframeOrchestrator();
3130
- async function getContainer(config) {
3131
- if (config.browser.ui) {
3132
- const element = document.querySelector("#tester-ui");
3133
- if (!element) {
3134
- return new Promise((resolve2) => {
3135
- queueMicrotask(() => {
3136
- resolve2(getContainer(config));
3137
- });
3138
- });
3139
- }
3140
- return element;
3141
- }
3142
- return document.querySelector("#vitest-tester");
3143
- }
3144
- async function sendEventToIframe(event) {
3145
- channel.postMessage(event);
3146
- return new Promise((resolve2) => {
3147
- channel.addEventListener(
3148
- "message",
3149
- function handler(e) {
3150
- if (e.data.iframeId === event.iframeId && e.data.event === `response:${event.event}`) {
3151
- resolve2();
3152
- channel.removeEventListener("message", handler);
3153
- }
3154
- }
3155
- );
3156
- });
3157
- }
3158
- function generateFileId(file) {
3159
- const config = getConfig();
3160
- const project = config.name || "";
3161
- const path = relative(config.root, file);
3162
- return generateHash(`${path}${project}`);
3163
- }
3164
- async function setIframeViewport(iframe, width, height) {
3165
- var _a, _b;
3166
- const ui = getUiAPI();
3167
- if (ui) {
3168
- await ui.setIframeViewport(width, height);
3169
- } else if (getBrowserState().provider === "webdriverio") {
3170
- (_a = iframe.parentElement) == null ? void 0 : _a.setAttribute("data-scale", "1");
3171
- await client.rpc.triggerCommand(
3172
- getBrowserState().sessionId,
3173
- "__vitest_viewport",
3174
- void 0,
3175
- [{ width, height }]
3176
- );
3177
- } else {
3178
- const scale = Math.min(
3179
- 1,
3180
- iframe.parentElement.parentElement.clientWidth / width,
3181
- iframe.parentElement.parentElement.clientHeight / height
3182
- );
3183
- iframe.parentElement.style.cssText = `
3184
- width: ${width}px;
3185
- height: ${height}px;
3186
- transform: scale(${scale});
3187
- transform-origin: left top;
3188
- `;
3189
- (_b = iframe.parentElement) == null ? void 0 : _b.setAttribute("data-scale", String(scale));
3190
- await new Promise((r) => requestAnimationFrame(r));
3191
- }
3192
- }
3193
- function debug(...args) {
3194
- const debug2 = getConfig().env.VITEST_BROWSER_DEBUG;
3195
- if (debug2 && debug2 !== "false") {
3196
- client.rpc.debug(...args.map(String));
3197
- }
3198
- }