@vitest/browser 0.29.7 → 0.29.8

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.
@@ -17,7 +17,7 @@
17
17
  })()
18
18
  </script>
19
19
  <!-- !LOAD_METADATA! -->
20
- <script type="module" crossorigin src="./assets/index-d8f092a0.js"></script>
20
+ <script type="module" crossorigin src="./assets/index-84967894.js"></script>
21
21
  <link rel="stylesheet" href="./assets/index-57d38fc4.css">
22
22
  </head>
23
23
  <body>
@@ -100,7 +100,7 @@ function createBirpc(functions, options) {
100
100
  timeout = DEFAULT_TIMEOUT
101
101
  } = options;
102
102
  const rpcPromiseMap = /* @__PURE__ */ new Map();
103
- const rpc = new Proxy({}, {
103
+ const rpc2 = new Proxy({}, {
104
104
  get(_, method) {
105
105
  const sendEvent = (...args) => {
106
106
  post(serialize({ m: method, a: args, t: "q" }));
@@ -132,7 +132,7 @@ function createBirpc(functions, options) {
132
132
  const { m: method, a: args } = msg;
133
133
  let result, error;
134
134
  try {
135
- result = await functions[method].apply(rpc, args);
135
+ result = await functions[method].apply(rpc2, args);
136
136
  } catch (e) {
137
137
  error = e;
138
138
  }
@@ -148,7 +148,7 @@ function createBirpc(functions, options) {
148
148
  rpcPromiseMap.delete(ack);
149
149
  }
150
150
  });
151
- return rpc;
151
+ return rpc2;
152
152
  }
153
153
  const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
154
154
  function nanoid(size = 21) {
@@ -239,6 +239,7 @@ class StateManager {
239
239
  this.filesMap = /* @__PURE__ */ new Map();
240
240
  this.pathsSet = /* @__PURE__ */ new Set();
241
241
  this.collectingPromise = void 0;
242
+ this.browserTestPromises = /* @__PURE__ */ new Map();
242
243
  this.idMap = /* @__PURE__ */ new Map();
243
244
  this.taskFileMap = /* @__PURE__ */ new WeakMap();
244
245
  this.errorsSet = /* @__PURE__ */ new Set();
@@ -402,16 +403,72 @@ function createClient(url2, options = {}) {
402
403
  }
403
404
  return ctx;
404
405
  }
405
- function createBrowserRunner(original) {
406
+ const { get } = Reflect;
407
+ const safeRandom = Math.random;
408
+ function withSafeTimers(getTimers, fn) {
409
+ const { setTimeout: setTimeout2, clearTimeout, nextTick, setImmediate, clearImmediate } = getTimers();
410
+ const currentSetTimeout = globalThis.setTimeout;
411
+ const currentClearTimeout = globalThis.clearTimeout;
412
+ const currentRandom = globalThis.Math.random;
413
+ const currentNextTick = globalThis.process.nextTick;
414
+ const currentSetImmediate = globalThis.setImmediate;
415
+ const currentClearImmediate = globalThis.clearImmediate;
416
+ try {
417
+ globalThis.setTimeout = setTimeout2;
418
+ globalThis.clearTimeout = clearTimeout;
419
+ globalThis.Math.random = safeRandom;
420
+ globalThis.process.nextTick = nextTick;
421
+ globalThis.setImmediate = setImmediate;
422
+ globalThis.clearImmediate = clearImmediate;
423
+ const result = fn();
424
+ return result;
425
+ } finally {
426
+ globalThis.setTimeout = currentSetTimeout;
427
+ globalThis.clearTimeout = currentClearTimeout;
428
+ globalThis.Math.random = currentRandom;
429
+ globalThis.setImmediate = currentSetImmediate;
430
+ globalThis.clearImmediate = currentClearImmediate;
431
+ nextTick(() => {
432
+ globalThis.process.nextTick = currentNextTick;
433
+ });
434
+ }
435
+ }
436
+ const promises = /* @__PURE__ */ new Set();
437
+ const rpcDone = async () => {
438
+ if (!promises.size)
439
+ return;
440
+ const awaitable = Array.from(promises);
441
+ return Promise.all(awaitable);
442
+ };
443
+ const createSafeRpc = (client2, getTimers) => {
444
+ return new Proxy(client2.rpc, {
445
+ get(target, p, handler) {
446
+ const sendCall = get(target, p, handler);
447
+ const safeSendCall = (...args) => withSafeTimers(getTimers, async () => {
448
+ const result = sendCall(...args);
449
+ promises.add(result);
450
+ try {
451
+ return await result;
452
+ } finally {
453
+ promises.delete(result);
454
+ }
455
+ });
456
+ safeSendCall.asEvent = sendCall.asEvent;
457
+ return safeSendCall;
458
+ }
459
+ });
460
+ };
461
+ const rpc = () => {
462
+ return globalThis.__vitest_worker__.safeRpc;
463
+ };
464
+ function createBrowserRunner(original, coverageModule) {
406
465
  return class BrowserTestRunner extends original {
407
466
  constructor(options) {
408
467
  super(options.config);
409
468
  __publicField(this, "config");
410
469
  __publicField(this, "hashMap", /* @__PURE__ */ new Map());
411
- __publicField(this, "client");
412
470
  this.config = options.config;
413
471
  this.hashMap = options.browserHashMap;
414
- this.client = options.client;
415
472
  }
416
473
  async onAfterRunTest(task) {
417
474
  var _a, _b, _c;
@@ -420,11 +477,17 @@ function createBrowserRunner(original) {
420
477
  console.error(error.message);
421
478
  });
422
479
  }
480
+ async onAfterRunSuite() {
481
+ var _a, _b;
482
+ await ((_a = super.onAfterRunSuite) == null ? void 0 : _a.call(this));
483
+ const coverage = await ((_b = coverageModule == null ? void 0 : coverageModule.takeCoverage) == null ? void 0 : _b.call(coverageModule));
484
+ await rpc().onAfterSuiteRun({ coverage });
485
+ }
423
486
  onCollected(files) {
424
- return this.client.rpc.onCollected(files);
487
+ return rpc().onCollected(files);
425
488
  }
426
489
  onTaskUpdate(task) {
427
- return this.client.rpc.onTaskUpdate(task);
490
+ return rpc().onTaskUpdate(task);
428
491
  }
429
492
  async importFile(filepath) {
430
493
  const match = filepath.match(/^(\w:\/)/);
@@ -439,25 +502,134 @@ function createBrowserRunner(original) {
439
502
  };
440
503
  }
441
504
  class BrowserSnapshotEnvironment {
442
- constructor(client2) {
443
- this.client = client2;
444
- }
445
505
  readSnapshotFile(filepath) {
446
- return this.client.rpc.readFile(filepath);
506
+ return rpc().readFile(filepath);
447
507
  }
448
508
  saveSnapshotFile(filepath, snapshot) {
449
- return this.client.rpc.writeFile(filepath, snapshot);
509
+ return rpc().writeFile(filepath, snapshot);
450
510
  }
451
511
  resolvePath(filepath) {
452
- return this.client.rpc.resolveSnapshotPath(filepath);
512
+ return rpc().resolveSnapshotPath(filepath);
453
513
  }
454
514
  removeSnapshotFile(filepath) {
455
- return this.client.rpc.removeFile(filepath);
515
+ return rpc().removeFile(filepath);
456
516
  }
457
517
  async prepareDirectory(filepath) {
458
- await this.client.rpc.createDirectory(filepath);
518
+ await rpc().createDirectory(filepath);
459
519
  }
460
520
  }
521
+ const importId = (id) => {
522
+ const name = `/@id/${id}`;
523
+ return __vitePreload(() => import(name), true ? [] : void 0);
524
+ };
525
+ const { Date: Date$1, console: console$1 } = globalThis;
526
+ const setupConsoleLogSpy = async () => {
527
+ const { stringify: stringify2, format, utilInspect } = await importId("vitest/utils");
528
+ const { log, info, error, dir, dirxml, trace, time, timeEnd, timeLog, warn, debug, count, countReset } = console$1;
529
+ const formatInput = (input) => {
530
+ if (input instanceof Node)
531
+ return stringify2(input);
532
+ return format(input);
533
+ };
534
+ const processLog = (args) => args.map(formatInput).join(" ");
535
+ const sendLog = (type, content) => {
536
+ var _a, _b;
537
+ if (content.startsWith("[vite]"))
538
+ return;
539
+ const unknownTestId = "__vitest__unknown_test__";
540
+ const taskId = ((_b = (_a = globalThis.__vitest_worker__) == null ? void 0 : _a.current) == null ? void 0 : _b.id) ?? unknownTestId;
541
+ rpc().sendLog({
542
+ content,
543
+ time: Date$1.now(),
544
+ taskId,
545
+ type,
546
+ size: content.length
547
+ });
548
+ };
549
+ const stdout = (base) => (...args) => {
550
+ sendLog("stdout", processLog(args));
551
+ return base(...args);
552
+ };
553
+ const stderr = (base) => (...args) => {
554
+ sendLog("stderr", processLog(args));
555
+ return base(...args);
556
+ };
557
+ console$1.log = stdout(log);
558
+ console$1.debug = stdout(debug);
559
+ console$1.info = stdout(info);
560
+ console$1.error = stderr(error);
561
+ console$1.warn = stderr(warn);
562
+ console$1.dir = (item, options) => {
563
+ sendLog("stdout", utilInspect(item, options));
564
+ return dir(item, options);
565
+ };
566
+ console$1.dirxml = (...args) => {
567
+ sendLog("stdout", processLog(args));
568
+ return dirxml(...args);
569
+ };
570
+ console$1.trace = (...args) => {
571
+ const content = processLog(args);
572
+ const error2 = new Error("Trace");
573
+ const stack = (error2.stack || "").split("\n").slice(2).join("\n");
574
+ sendLog("stdout", `${content}
575
+ ${stack}`);
576
+ return trace(...args);
577
+ };
578
+ const timeLabels = {};
579
+ console$1.time = (label = "default") => {
580
+ const now = performance.now();
581
+ time(label);
582
+ timeLabels[label] = now;
583
+ };
584
+ console$1.timeLog = (label = "default") => {
585
+ timeLog(label);
586
+ if (!(label in timeLabels))
587
+ sendLog("stderr", `Timer "${label}" does not exist`);
588
+ else
589
+ sendLog("stdout", `${label}: ${timeLabels[label]} ms`);
590
+ };
591
+ console$1.timeEnd = (label = "default") => {
592
+ const end = performance.now();
593
+ timeEnd(label);
594
+ const start = timeLabels[label];
595
+ if (!(label in timeLabels)) {
596
+ sendLog("stderr", `Timer "${label}" does not exist`);
597
+ } else if (start) {
598
+ const duration = end - start;
599
+ sendLog("stdout", `${label}: ${duration} ms`);
600
+ }
601
+ };
602
+ const countLabels = {};
603
+ console$1.count = (label = "default") => {
604
+ const counter = (countLabels[label] ?? 0) + 1;
605
+ countLabels[label] = counter;
606
+ sendLog("stdout", `${label}: ${counter}`);
607
+ return count(label);
608
+ };
609
+ console$1.countReset = (label = "default") => {
610
+ countLabels[label] = 0;
611
+ return countReset(label);
612
+ };
613
+ };
614
+ const showPopupWarning = (name, value, defaultValue) => (...params) => {
615
+ const formatedParams = params.map((p) => JSON.stringify(p)).join(", ");
616
+ console.warn(`Vitest encountered a \`${name}(${formatedParams})\` call that it cannot handle by default, so it returned \`${value}\`. Read more in https://vitest.dev/guide/browser#thread-blocking-dialogs.
617
+ If needed, mock the \`${name}\` call manually like:
618
+
619
+ \`\`\`
620
+ import { expect, vi } from "vitest"
621
+
622
+ vi.spyOn(window, "${name}")${defaultValue ? `.mockReturnValue(${JSON.stringify(defaultValue)})` : ""}
623
+ ${name}(${formatedParams})
624
+ expect(${name}).toHaveBeenCalledWith(${formatedParams})
625
+ \`\`\``);
626
+ return value;
627
+ };
628
+ const setupDialogsSpy = () => {
629
+ globalThis.alert = showPopupWarning("alert", void 0);
630
+ globalThis.confirm = showPopupWarning("confirm", false, true);
631
+ globalThis.prompt = showPopupWarning("prompt", null, "your value");
632
+ };
461
633
  globalThis.process = { env: {}, argv: [], cwd: () => "/", stdout: { write: () => {
462
634
  } }, nextTick: (cb) => cb() };
463
635
  globalThis.global = globalThis;
@@ -488,43 +660,56 @@ async function loadConfig() {
488
660
  }
489
661
  ws.addEventListener("open", async () => {
490
662
  await loadConfig();
663
+ const { getSafeTimers } = await importId("vitest/utils");
664
+ const safeRpc = createSafeRpc(client, getSafeTimers);
665
+ globalThis.__vitest_browser__ = true;
491
666
  globalThis.__vitest_worker__ = {
492
667
  config,
493
668
  browserHashMap,
494
669
  moduleCache: /* @__PURE__ */ new Map(),
495
- rpc: client.rpc
670
+ rpc: client.rpc,
671
+ safeRpc
496
672
  };
497
- globalThis.__vitest_mocker__ = {};
498
673
  const paths = getQueryPaths();
499
674
  const iFrame = document.getElementById("vitest-ui");
500
675
  iFrame.setAttribute("src", "/__vitest__/");
501
- await runTests(paths, config, client);
676
+ await setupConsoleLogSpy();
677
+ setupDialogsSpy();
678
+ await runTests(paths, config);
502
679
  });
503
680
  let hasSnapshot = false;
504
- async function runTests(paths, config2, client2) {
681
+ async function runTests(paths, config2) {
505
682
  const viteClientPath = "/@vite/client";
506
683
  await __vitePreload(() => import(viteClientPath), true ? [] : void 0);
507
- const path = "/__vitest_index__";
508
- const { startTests, setupCommonEnv, setupSnapshotEnvironment } = await __vitePreload(() => import(path), true ? [] : void 0);
684
+ const {
685
+ startTests,
686
+ setupCommonEnv,
687
+ setupSnapshotEnvironment,
688
+ takeCoverageInsideWorker
689
+ } = await importId("vitest/browser");
690
+ const executor = {
691
+ executeId: (id) => importId(id)
692
+ };
509
693
  if (!runner) {
510
- const runnerPath = "/__vitest_runners__";
511
- const { VitestTestRunner } = await __vitePreload(() => import(runnerPath), true ? [] : void 0);
512
- const BrowserRunner = createBrowserRunner(VitestTestRunner);
513
- runner = new BrowserRunner({ config: config2, client: client2, browserHashMap });
694
+ const { VitestTestRunner } = await importId("vitest/runners");
695
+ const BrowserRunner = createBrowserRunner(VitestTestRunner, { takeCoverage: () => takeCoverageInsideWorker(config2.coverage, executor) });
696
+ runner = new BrowserRunner({ config: config2, browserHashMap });
514
697
  }
515
698
  if (!hasSnapshot) {
516
- setupSnapshotEnvironment(new BrowserSnapshotEnvironment(client2));
699
+ setupSnapshotEnvironment(new BrowserSnapshotEnvironment());
517
700
  hasSnapshot = true;
518
701
  }
519
702
  try {
520
703
  await setupCommonEnv(config2);
521
- const files = paths.map((path2) => {
522
- return `${config2.root}/${path2}`.replace(/\/+/g, "/");
704
+ const files = paths.map((path) => {
705
+ return `${config2.root}/${path}`.replace(/\/+/g, "/");
523
706
  });
524
707
  const now = `${new Date().getTime()}`;
525
708
  files.forEach((i) => browserHashMap.set(i, now));
526
- await startTests(files, runner);
709
+ for (const file of files)
710
+ await startTests([file], runner);
527
711
  } finally {
528
- await client2.rpc.onDone(testId);
712
+ await rpcDone();
713
+ await rpc().onDone(testId);
529
714
  }
530
715
  }
@@ -21,7 +21,7 @@
21
21
  border: none;
22
22
  }
23
23
  </style>
24
- <script type="module" crossorigin src="/assets/index-ca7a263d.js"></script>
24
+ <script type="module" crossorigin src="/assets/index-a25c0b91.js"></script>
25
25
  </head>
26
26
  <body>
27
27
  <iframe id="vitest-ui" src=""></iframe>
package/dist/index.js CHANGED
@@ -14,16 +14,9 @@ var index = (base = "/") => {
14
14
  {
15
15
  enforce: "pre",
16
16
  name: "vitest:browser",
17
- async resolveId(id) {
18
- if (id === "/__vitest_index__")
19
- return this.resolve("vitest/browser");
20
- if (id === "/__vitest_runners__")
21
- return this.resolve("vitest/runners");
22
- if (id.startsWith("node:"))
23
- id = id.slice(5);
24
- if (polyfills.includes(id))
25
- return polyfillPath(normalizeId(id));
26
- return null;
17
+ async config(viteConfig) {
18
+ viteConfig.esbuild || (viteConfig.esbuild = {});
19
+ viteConfig.esbuild.legalComments = "inline";
27
20
  },
28
21
  async configureServer(server) {
29
22
  server.middlewares.use(
@@ -37,8 +30,16 @@ var index = (base = "/") => {
37
30
  },
38
31
  {
39
32
  name: "modern-node-polyfills",
33
+ enforce: "pre",
34
+ config() {
35
+ return {
36
+ optimizeDeps: {
37
+ exclude: [...polyfills, ...builtinModules]
38
+ }
39
+ };
40
+ },
40
41
  async resolveId(id) {
41
- if (!builtinModules.includes(id))
42
+ if (!builtinModules.includes(id) && !polyfills.includes(id) && !id.startsWith("node:"))
42
43
  return;
43
44
  id = normalizeId(id);
44
45
  return { id: await polyfillPath(id), moduleSideEffects: false };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vitest/browser",
3
3
  "type": "module",
4
- "version": "0.29.7",
4
+ "version": "0.29.8",
5
5
  "description": "Browser running for Vitest",
6
6
  "repository": {
7
7
  "type": "git",
@@ -32,14 +32,14 @@
32
32
  "modern-node-polyfills": "0.1.0",
33
33
  "rollup-plugin-node-polyfills": "^0.2.1",
34
34
  "sirv": "^2.0.2",
35
- "@vitest/runner": "0.29.7"
35
+ "@vitest/runner": "0.29.8"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/ws": "^8.5.4",
39
39
  "rollup": "^2.79.1",
40
- "@vitest/ws-client": "0.29.7",
41
- "@vitest/ui": "0.29.7",
42
- "vitest": "0.29.7"
40
+ "@vitest/ui": "0.29.8",
41
+ "@vitest/ws-client": "0.29.8",
42
+ "vitest": "0.29.8"
43
43
  },
44
44
  "scripts": {
45
45
  "build": "rimraf dist && pnpm build:node && pnpm build:client && pnpm copy",