@vitest/browser 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,299 @@
1
+ (function polyfill() {
2
+ const relList = document.createElement("link").relList;
3
+ if (relList && relList.supports && relList.supports("modulepreload")) {
4
+ return;
5
+ }
6
+ for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
7
+ processPreload(link);
8
+ }
9
+ new MutationObserver((mutations) => {
10
+ for (const mutation of mutations) {
11
+ if (mutation.type !== "childList") {
12
+ continue;
13
+ }
14
+ for (const node of mutation.addedNodes) {
15
+ if (node.tagName === "LINK" && node.rel === "modulepreload")
16
+ processPreload(node);
17
+ }
18
+ }
19
+ }).observe(document, { childList: true, subtree: true });
20
+ function getFetchOpts(link) {
21
+ const fetchOpts = {};
22
+ if (link.integrity) fetchOpts.integrity = link.integrity;
23
+ if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
24
+ if (link.crossOrigin === "use-credentials")
25
+ fetchOpts.credentials = "include";
26
+ else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
27
+ else fetchOpts.credentials = "same-origin";
28
+ return fetchOpts;
29
+ }
30
+ function processPreload(link) {
31
+ if (link.ep)
32
+ return;
33
+ link.ep = true;
34
+ const fetchOpts = getFetchOpts(link);
35
+ fetch(link.href, fetchOpts);
36
+ }
37
+ })();
38
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
39
+ function normalizeWindowsPath(input = "") {
40
+ if (!input) {
41
+ return input;
42
+ }
43
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
44
+ }
45
+ const _UNC_REGEX = /^[/\\]{2}/;
46
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
47
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
48
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
49
+ const normalize = function(path) {
50
+ if (path.length === 0) {
51
+ return ".";
52
+ }
53
+ path = normalizeWindowsPath(path);
54
+ const isUNCPath = path.match(_UNC_REGEX);
55
+ const isPathAbsolute = isAbsolute(path);
56
+ const trailingSeparator = path[path.length - 1] === "/";
57
+ path = normalizeString(path, !isPathAbsolute);
58
+ if (path.length === 0) {
59
+ if (isPathAbsolute) {
60
+ return "/";
61
+ }
62
+ return trailingSeparator ? "./" : ".";
63
+ }
64
+ if (trailingSeparator) {
65
+ path += "/";
66
+ }
67
+ if (_DRIVE_LETTER_RE.test(path)) {
68
+ path += "/";
69
+ }
70
+ if (isUNCPath) {
71
+ if (!isPathAbsolute) {
72
+ return `//./${path}`;
73
+ }
74
+ return `//${path}`;
75
+ }
76
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
77
+ };
78
+ const join = function(...arguments_) {
79
+ if (arguments_.length === 0) {
80
+ return ".";
81
+ }
82
+ let joined;
83
+ for (const argument of arguments_) {
84
+ if (argument && argument.length > 0) {
85
+ if (joined === void 0) {
86
+ joined = argument;
87
+ } else {
88
+ joined += `/${argument}`;
89
+ }
90
+ }
91
+ }
92
+ if (joined === void 0) {
93
+ return ".";
94
+ }
95
+ return normalize(joined.replace(/\/\/+/g, "/"));
96
+ };
97
+ function cwd() {
98
+ if (typeof process !== "undefined" && typeof process.cwd === "function") {
99
+ return process.cwd().replace(/\\/g, "/");
100
+ }
101
+ return "/";
102
+ }
103
+ const resolve = function(...arguments_) {
104
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
105
+ let resolvedPath = "";
106
+ let resolvedAbsolute = false;
107
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
108
+ const path = index >= 0 ? arguments_[index] : cwd();
109
+ if (!path || path.length === 0) {
110
+ continue;
111
+ }
112
+ resolvedPath = `${path}/${resolvedPath}`;
113
+ resolvedAbsolute = isAbsolute(path);
114
+ }
115
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
116
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
117
+ return `/${resolvedPath}`;
118
+ }
119
+ return resolvedPath.length > 0 ? resolvedPath : ".";
120
+ };
121
+ function normalizeString(path, allowAboveRoot) {
122
+ let res = "";
123
+ let lastSegmentLength = 0;
124
+ let lastSlash = -1;
125
+ let dots = 0;
126
+ let char = null;
127
+ for (let index = 0; index <= path.length; ++index) {
128
+ if (index < path.length) {
129
+ char = path[index];
130
+ } else if (char === "/") {
131
+ break;
132
+ } else {
133
+ char = "/";
134
+ }
135
+ if (char === "/") {
136
+ if (lastSlash === index - 1 || dots === 1) ;
137
+ else if (dots === 2) {
138
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
139
+ if (res.length > 2) {
140
+ const lastSlashIndex = res.lastIndexOf("/");
141
+ if (lastSlashIndex === -1) {
142
+ res = "";
143
+ lastSegmentLength = 0;
144
+ } else {
145
+ res = res.slice(0, lastSlashIndex);
146
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
147
+ }
148
+ lastSlash = index;
149
+ dots = 0;
150
+ continue;
151
+ } else if (res.length > 0) {
152
+ res = "";
153
+ lastSegmentLength = 0;
154
+ lastSlash = index;
155
+ dots = 0;
156
+ continue;
157
+ }
158
+ }
159
+ if (allowAboveRoot) {
160
+ res += res.length > 0 ? "/.." : "..";
161
+ lastSegmentLength = 2;
162
+ }
163
+ } else {
164
+ if (res.length > 0) {
165
+ res += `/${path.slice(lastSlash + 1, index)}`;
166
+ } else {
167
+ res = path.slice(lastSlash + 1, index);
168
+ }
169
+ lastSegmentLength = index - lastSlash - 1;
170
+ }
171
+ lastSlash = index;
172
+ dots = 0;
173
+ } else if (char === "." && dots !== -1) {
174
+ ++dots;
175
+ } else {
176
+ dots = -1;
177
+ }
178
+ }
179
+ return res;
180
+ }
181
+ const isAbsolute = function(p) {
182
+ return _IS_ABSOLUTE_RE.test(p);
183
+ };
184
+ const _EXTNAME_RE = /.(\.[^./]+)$/;
185
+ const extname = function(p) {
186
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
187
+ return match && match[1] || "";
188
+ };
189
+ const relative = function(from, to) {
190
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
191
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
192
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
193
+ return _to.join("/");
194
+ }
195
+ const _fromCopy = [..._from];
196
+ for (const segment of _fromCopy) {
197
+ if (_to[0] !== segment) {
198
+ break;
199
+ }
200
+ _from.shift();
201
+ _to.shift();
202
+ }
203
+ return [..._from.map(() => ".."), ..._to].join("/");
204
+ };
205
+ async function importId(id) {
206
+ const name = `/@id/${id}`.replace(/\\/g, "/");
207
+ return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
208
+ /* @vite-ignore */
209
+ name
210
+ ));
211
+ }
212
+ async function importFs(id) {
213
+ const name = `/@fs/${id}`.replace(/\\/g, "/");
214
+ return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
215
+ /* @vite-ignore */
216
+ name
217
+ ));
218
+ }
219
+ function getConfig() {
220
+ return (/* @__PURE__ */ getBrowserState()).config;
221
+ }
222
+ // @__NO_SIDE_EFFECTS__
223
+ function getBrowserState() {
224
+ return window.__vitest_browser_runner__;
225
+ }
226
+ // @__NO_SIDE_EFFECTS__
227
+ function getWorkerState() {
228
+ const state = window.__vitest_worker__;
229
+ if (!state) {
230
+ throw new Error("Worker state is not found. This is an issue with Vitest. Please, open an issue.");
231
+ }
232
+ return state;
233
+ }
234
+ const scriptRel = "modulepreload";
235
+ const assetsURL = function(dep) {
236
+ return "/" + dep;
237
+ };
238
+ const seen = {};
239
+ const __vitePreload = function preload(baseModule, deps, importerUrl) {
240
+ let promise = Promise.resolve();
241
+ if (deps && deps.length > 0) {
242
+ document.getElementsByTagName("link");
243
+ const cspNonceMeta = document.querySelector(
244
+ "meta[property=csp-nonce]"
245
+ );
246
+ const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
247
+ promise = Promise.all(
248
+ deps.map((dep) => {
249
+ dep = assetsURL(dep);
250
+ if (dep in seen) return;
251
+ seen[dep] = true;
252
+ const isCss = dep.endsWith(".css");
253
+ const cssSelector = isCss ? '[rel="stylesheet"]' : "";
254
+ if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
255
+ return;
256
+ }
257
+ const link = document.createElement("link");
258
+ link.rel = isCss ? "stylesheet" : scriptRel;
259
+ if (!isCss) {
260
+ link.as = "script";
261
+ link.crossOrigin = "";
262
+ }
263
+ link.href = dep;
264
+ if (cspNonce) {
265
+ link.setAttribute("nonce", cspNonce);
266
+ }
267
+ document.head.appendChild(link);
268
+ if (isCss) {
269
+ return new Promise((res, rej) => {
270
+ link.addEventListener("load", res);
271
+ link.addEventListener(
272
+ "error",
273
+ () => rej(new Error(`Unable to preload CSS for ${dep}`))
274
+ );
275
+ });
276
+ }
277
+ })
278
+ );
279
+ }
280
+ return promise.then(() => baseModule()).catch((err) => {
281
+ const e = new Event("vite:preloadError", { cancelable: true });
282
+ e.payload = err;
283
+ window.dispatchEvent(e);
284
+ if (!e.defaultPrevented) {
285
+ throw err;
286
+ }
287
+ });
288
+ };
289
+ export {
290
+ __vitePreload as _,
291
+ getConfig as a,
292
+ importId as b,
293
+ getWorkerState as c,
294
+ extname as e,
295
+ getBrowserState as g,
296
+ importFs as i,
297
+ join as j,
298
+ relative as r
299
+ };
@@ -1,16 +1,13 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import { d as getConfig, b as globalChannel, i as importFs, e as importId, c as channel, f as extname, g as getBrowserState, w as waitForChannel, j as join, a as client, o as onCancel, h as getWorkerState } from "./client-dLyjuL0K.js";
5
- import { processError, loadDiffConfig, loadSnapshotSerializers, takeCoverageInsideWorker, setupCommonEnv, startTests, collectTests, SpyModule } from "/__virtual_vitest__?id=vitest%2Fbrowser";
6
- import { getSafeTimers, stringify, format, TraceMap, originalPositionFor } from "/__virtual_vitest__?id=vitest%2Futils";
7
- import { VitestTestRunner, NodeBenchmarkRunner } from "/__virtual_vitest__?id=vitest%2Frunners";
4
+ import { a as getConfig, i as importFs, b as importId, e as extname, g as getBrowserState, _ as __vitePreload, j as join, c as getWorkerState } from "./preload-helper-Btt6SgIy.js";
5
+ import { loadDiffConfig, loadSnapshotSerializers, takeCoverageInsideWorker, setupCommonEnv, startTests, collectTests, SpyModule } from "vitest/browser";
6
+ import { globalChannel, channel, waitForChannel, client, onCancel } from "@vitest/browser/client";
7
+ import { getSafeTimers, stringify, format, TraceMap, originalPositionFor } from "vitest/utils";
8
+ import { VitestTestRunner, NodeBenchmarkRunner } from "vitest/runners";
8
9
  import { page } from "@vitest/browser/context";
9
- import { expect } from "/__virtual_vitest__?id=vitest";
10
- var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
11
- function getDefaultExportFromCjs(x) {
12
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
13
- }
10
+ import { expect } from "vitest";
14
11
  function getType(value) {
15
12
  return Object.prototype.toString.apply(value).slice(8, -1);
16
13
  }
@@ -35,56 +32,6 @@ function setupDialogsSpy() {
35
32
  globalThis.confirm = showPopupWarning("confirm", false, true);
36
33
  globalThis.prompt = showPopupWarning("prompt", null, "your value");
37
34
  }
38
- function on(event, listener) {
39
- window.addEventListener(event, listener);
40
- return () => window.removeEventListener(event, listener);
41
- }
42
- function serializeError(unhandledError) {
43
- return {
44
- ...unhandledError,
45
- name: unhandledError.name,
46
- message: unhandledError.message,
47
- stack: String(unhandledError.stack)
48
- };
49
- }
50
- function catchWindowErrors(cb) {
51
- let userErrorListenerCount = 0;
52
- function throwUnhandlerError(e) {
53
- if (userErrorListenerCount === 0 && e.error != null) {
54
- cb(e);
55
- } else {
56
- console.error(e.error);
57
- }
58
- }
59
- const addEventListener = window.addEventListener.bind(window);
60
- const removeEventListener = window.removeEventListener.bind(window);
61
- window.addEventListener("error", throwUnhandlerError);
62
- window.addEventListener = function(...args) {
63
- if (args[0] === "error") {
64
- userErrorListenerCount++;
65
- }
66
- return addEventListener.apply(this, args);
67
- };
68
- window.removeEventListener = function(...args) {
69
- if (args[0] === "error" && userErrorListenerCount) {
70
- userErrorListenerCount--;
71
- }
72
- return removeEventListener.apply(this, args);
73
- };
74
- return function clearErrorHandlers() {
75
- window.removeEventListener("error", throwUnhandlerError);
76
- };
77
- }
78
- function registerUnexpectedErrors(rpc2) {
79
- catchWindowErrors(
80
- (event) => reportUnexpectedError(rpc2, "Error", event.error)
81
- );
82
- on("unhandledrejection", (event) => reportUnexpectedError(rpc2, "Unhandled Rejection", event.reason));
83
- }
84
- async function reportUnexpectedError(rpc2, type, error) {
85
- const processedError = processError(error);
86
- await rpc2.onUnhandledError(processedError, type);
87
- }
88
35
  const { get } = Reflect;
89
36
  function withSafeTimers(getTimers, fn) {
90
37
  const { setTimeout, clearTimeout, setImmediate, clearImmediate } = getTimers();
@@ -443,61 +390,6 @@ async function updateFilesLocations(files, sourceMaps) {
443
390
  });
444
391
  await Promise.all(promises2);
445
392
  }
446
- const scriptRel = "modulepreload";
447
- const assetsURL = function(dep) {
448
- return "/" + dep;
449
- };
450
- const seen = {};
451
- const __vitePreload = function preload(baseModule, deps, importerUrl) {
452
- let promise = Promise.resolve();
453
- if (deps && deps.length > 0) {
454
- document.getElementsByTagName("link");
455
- const cspNonceMeta = document.querySelector(
456
- "meta[property=csp-nonce]"
457
- );
458
- const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
459
- promise = Promise.all(
460
- deps.map((dep) => {
461
- dep = assetsURL(dep);
462
- if (dep in seen) return;
463
- seen[dep] = true;
464
- const isCss = dep.endsWith(".css");
465
- const cssSelector = isCss ? '[rel="stylesheet"]' : "";
466
- if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
467
- return;
468
- }
469
- const link = document.createElement("link");
470
- link.rel = isCss ? "stylesheet" : scriptRel;
471
- if (!isCss) {
472
- link.as = "script";
473
- link.crossOrigin = "";
474
- }
475
- link.href = dep;
476
- if (cspNonce) {
477
- link.setAttribute("nonce", cspNonce);
478
- }
479
- document.head.appendChild(link);
480
- if (isCss) {
481
- return new Promise((res, rej) => {
482
- link.addEventListener("load", res);
483
- link.addEventListener(
484
- "error",
485
- () => rej(new Error(`Unable to preload CSS for ${dep}`))
486
- );
487
- });
488
- }
489
- })
490
- );
491
- }
492
- return promise.then(() => baseModule()).catch((err) => {
493
- const e = new Event("vite:preloadError", { cancelable: true });
494
- e.payload = err;
495
- window.dispatchEvent(e);
496
- if (!e.defaultPrevented) {
497
- throw err;
498
- }
499
- });
500
- };
501
393
  const now = Date.now;
502
394
  class VitestBrowserClientMocker {
503
395
  constructor() {
@@ -521,12 +413,12 @@ class VitestBrowserClientMocker {
521
413
  exports
522
414
  });
523
415
  } catch (err) {
524
- const { processError: processError2 } = await importId(
416
+ const { processError } = await importId(
525
417
  "vitest/browser"
526
418
  );
527
419
  channel.postMessage({
528
420
  type: "mock-factory:error",
529
- error: processError2(err)
421
+ error: processError(err)
530
422
  });
531
423
  }
532
424
  }
@@ -841,6 +733,10 @@ const versionRegexp = /(\?|&)v=\w{8}/;
841
733
  function cleanVersion(url2) {
842
734
  return url2.replace(versionRegexp, "");
843
735
  }
736
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
737
+ function getDefaultExportFromCjs(x) {
738
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
739
+ }
844
740
  var minIndent$1 = (string) => {
845
741
  const match = string.match(/^[ \t]*(?=\S)/gm);
846
742
  if (!match) {
@@ -1829,8 +1725,8 @@ function getLabels(element) {
1829
1725
  if (!isLabelableElement(element)) {
1830
1726
  return null;
1831
1727
  }
1832
- var document2 = element.ownerDocument;
1833
- return arrayFrom(document2.querySelectorAll("label")).filter(function(label) {
1728
+ var document = element.ownerDocument;
1729
+ return arrayFrom(document.querySelectorAll("label")).filter(function(label) {
1834
1730
  return getControlOfLabel(label) === element;
1835
1731
  });
1836
1732
  }
@@ -10134,7 +10030,7 @@ function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) {
10134
10030
  if (arrStacked && othStacked) {
10135
10031
  return arrStacked == other && othStacked == array;
10136
10032
  }
10137
- var index = -1, result = true, seen2 = bitmask & COMPARE_UNORDERED_FLAG$1 ? new SetCache() : void 0;
10033
+ var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG$1 ? new SetCache() : void 0;
10138
10034
  stack.set(array, other);
10139
10035
  stack.set(other, array);
10140
10036
  while (++index < arrLength) {
@@ -10149,10 +10045,10 @@ function equalArrays$2(array, other, bitmask, customizer, equalFunc, stack) {
10149
10045
  result = false;
10150
10046
  break;
10151
10047
  }
10152
- if (seen2) {
10048
+ if (seen) {
10153
10049
  if (!arraySome(other, function(othValue2, othIndex) {
10154
- if (!cacheHas(seen2, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
10155
- return seen2.push(othIndex);
10050
+ if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
10051
+ return seen.push(othIndex);
10156
10052
  }
10157
10053
  })) {
10158
10054
  result = false;
@@ -11341,9 +11237,9 @@ function toHaveClass(htmlElement, ...params) {
11341
11237
  ].join("\n")
11342
11238
  };
11343
11239
  }
11344
- function getStyleDeclaration(document2, css) {
11240
+ function getStyleDeclaration(document, css) {
11345
11241
  const styles2 = {};
11346
- const copy = document2.createElement("div");
11242
+ const copy = document.createElement("div");
11347
11243
  Object.keys(css).forEach((property) => {
11348
11244
  copy.style[property] = css[property];
11349
11245
  styles2[property] = copy.style[property];
@@ -11873,8 +11769,8 @@ function toHaveDescription(htmlElement, checkWith) {
11873
11769
  const descriptionIDs = descriptionIDRaw.split(/\s+/).filter(Boolean);
11874
11770
  let description = "";
11875
11771
  if (descriptionIDs.length > 0) {
11876
- const document2 = htmlElement.ownerDocument;
11877
- const descriptionEls = descriptionIDs.map((descriptionID) => document2.getElementById(descriptionID)).filter(Boolean);
11772
+ const document = htmlElement.ownerDocument;
11773
+ const descriptionEls = descriptionIDs.map((descriptionID) => document.getElementById(descriptionID)).filter(Boolean);
11878
11774
  description = normalize(descriptionEls.map((el) => el.textContent).join(" "));
11879
11775
  }
11880
11776
  return {
@@ -11920,8 +11816,8 @@ function toHaveErrorMessage(htmlElement, checkWith) {
11920
11816
  const errormessageIDs = errormessageIDRaw.split(/\s+/).filter(Boolean);
11921
11817
  let errormessage = "";
11922
11818
  if (errormessageIDs.length > 0) {
11923
- const document2 = htmlElement.ownerDocument;
11924
- const errormessageEls = errormessageIDs.map((errormessageID) => document2.getElementById(errormessageID)).filter(Boolean);
11819
+ const document = htmlElement.ownerDocument;
11820
+ const errormessageEls = errormessageIDs.map((errormessageID) => document.getElementById(errormessageID)).filter(Boolean);
11925
11821
  errormessage = normalize(
11926
11822
  errormessageEls.map((el) => el.textContent).join(" ")
11927
11823
  );
@@ -12017,7 +11913,6 @@ async function prepareTestEnvironment(files) {
12017
11913
  var _a;
12018
11914
  (_a = runner.onCancel) == null ? void 0 : _a.call(runner, reason);
12019
11915
  });
12020
- registerUnexpectedErrors(rpc2);
12021
11916
  return {
12022
11917
  runner,
12023
11918
  config,
@@ -12039,7 +11934,11 @@ async function executeTests(method, files) {
12039
11934
  preparedData = await prepareTestEnvironment(files);
12040
11935
  } catch (error) {
12041
11936
  debug("runner cannot be loaded because it threw an error", error.stack || error.message);
12042
- await client.rpc.onUnhandledError(serializeError(error), "Preload Error");
11937
+ await client.rpc.onUnhandledError({
11938
+ name: error.name,
11939
+ message: error.message,
11940
+ stack: String(error.stack)
11941
+ }, "Preload Error");
12043
11942
  done(files);
12044
11943
  return;
12045
11944
  }
@@ -0,0 +1,81 @@
1
+ import { channel, client } from '@vitest/browser/client'
2
+
3
+ function on(event, listener) {
4
+ window.addEventListener(event, listener)
5
+ return () => window.removeEventListener(event, listener)
6
+ }
7
+
8
+ function serializeError(unhandledError) {
9
+ if (typeof unhandledError !== 'object' || !unhandledError) {
10
+ return {
11
+ message: String(unhandledError),
12
+ }
13
+ }
14
+
15
+ return {
16
+ name: unhandledError.name,
17
+ message: unhandledError.message,
18
+ stack: String(unhandledError.stack),
19
+ }
20
+ }
21
+
22
+ function catchWindowErrors(cb) {
23
+ let userErrorListenerCount = 0
24
+ function throwUnhandlerError(e) {
25
+ if (userErrorListenerCount === 0 && e.error != null) {
26
+ cb(e)
27
+ }
28
+ else {
29
+ console.error(e.error)
30
+ }
31
+ }
32
+ const addEventListener = window.addEventListener.bind(window)
33
+ const removeEventListener = window.removeEventListener.bind(window)
34
+ window.addEventListener('error', throwUnhandlerError)
35
+ window.addEventListener = function (...args) {
36
+ if (args[0] === 'error') {
37
+ userErrorListenerCount++
38
+ }
39
+ return addEventListener.apply(this, args)
40
+ }
41
+ window.removeEventListener = function (...args) {
42
+ if (args[0] === 'error' && userErrorListenerCount) {
43
+ userErrorListenerCount--
44
+ }
45
+ return removeEventListener.apply(this, args)
46
+ }
47
+ return function clearErrorHandlers() {
48
+ window.removeEventListener('error', throwUnhandlerError)
49
+ }
50
+ }
51
+
52
+ function registerUnexpectedErrors() {
53
+ catchWindowErrors(event =>
54
+ reportUnexpectedError('Error', event.error),
55
+ )
56
+ on('unhandledrejection', event =>
57
+ reportUnexpectedError('Unhandled Rejection', event.reason))
58
+ }
59
+
60
+ async function reportUnexpectedError(
61
+ type,
62
+ error,
63
+ ) {
64
+ const processedError = serializeError(error)
65
+ await client.rpc.onUnhandledError(processedError, type)
66
+ const state = __vitest_browser_runner__
67
+
68
+ if (state.type === 'orchestrator') {
69
+ return
70
+ }
71
+
72
+ if (!state.runTests || !__vitest_worker__.current) {
73
+ channel.postMessage({
74
+ type: 'done',
75
+ filenames: state.files,
76
+ id: state.iframeId,
77
+ })
78
+ }
79
+ }
80
+
81
+ registerUnexpectedErrors()
@@ -23,6 +23,7 @@ window.__vitest_browser_runner__ = {
23
23
  files: { __VITEST_FILES__ },
24
24
  type: { __VITEST_TYPE__ },
25
25
  contextId: { __VITEST_CONTEXT_ID__ },
26
+ testerId: { __VITEST_TESTER_ID__ },
26
27
  provider: { __VITEST_PROVIDER__ },
27
28
  providedContext: { __VITEST_PROVIDED_CONTEXT__ },
28
29
  };
@@ -23,10 +23,11 @@
23
23
  height: 100%;
24
24
  }
25
25
  </style>
26
- <script>{__VITEST_INJECTOR__}</script>
26
+ {__VITEST_INJECTOR__}
27
+ {__VITEST_ERROR_CATCHER__}
27
28
  {__VITEST_SCRIPTS__}
28
- <script type="module" crossorigin src="/__vitest_browser__/orchestrator-x0A1t8rC.js"></script>
29
- <link rel="modulepreload" crossorigin href="/__vitest_browser__/client-dLyjuL0K.js">
29
+ <script type="module" crossorigin src="/__vitest_browser__/orchestrator-BO1kzf5D.js"></script>
30
+ <link rel="modulepreload" crossorigin href="/__vitest_browser__/preload-helper-Btt6SgIy.js">
30
31
  </head>
31
32
  <body>
32
33
  <div id="vitest-tester"></div>
@@ -16,11 +16,12 @@
16
16
  min-height: 100vh;
17
17
  }
18
18
  </style>
19
- <script>{__VITEST_INJECTOR__}</script>
19
+ {__VITEST_INJECTOR__}
20
20
  <script>{__VITEST_STATE__}</script>
21
+ {__VITEST_ERROR_CATCHER__}
21
22
  {__VITEST_SCRIPTS__}
22
- <script type="module" crossorigin src="/__vitest_browser__/tester-BdcP5piS.js"></script>
23
- <link rel="modulepreload" crossorigin href="/__vitest_browser__/client-dLyjuL0K.js">
23
+ <script type="module" crossorigin src="/__vitest_browser__/tester-DoK-7PCe.js"></script>
24
+ <link rel="modulepreload" crossorigin href="/__vitest_browser__/preload-helper-Btt6SgIy.js">
24
25
  </head>
25
26
  <body
26
27
  data-vitest-body