@vitest/browser 2.1.3 → 2.1.4

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,81 @@
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
+ async function importId(id) {
39
+ const name = `/@id/${id}`.replace(/\\/g, "/");
40
+ return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
41
+ /* @vite-ignore */
42
+ name
43
+ ));
44
+ }
45
+ async function importFs(id) {
46
+ const name = `/@fs/${id}`.replace(/\\/g, "/");
47
+ return (/* @__PURE__ */ getBrowserState()).wrapModule(() => import(
48
+ /* @vite-ignore */
49
+ name
50
+ ));
51
+ }
52
+ const executor = {
53
+ isBrowser: true,
54
+ executeId: (id) => {
55
+ if (id[0] === "/" || id[1] === ":") {
56
+ return importFs(id);
57
+ }
58
+ return importId(id);
59
+ }
60
+ };
61
+ function getConfig() {
62
+ return (/* @__PURE__ */ getBrowserState()).config;
63
+ }
64
+ // @__NO_SIDE_EFFECTS__
65
+ function getBrowserState() {
66
+ return window.__vitest_browser_runner__;
67
+ }
68
+ // @__NO_SIDE_EFFECTS__
69
+ function getWorkerState() {
70
+ const state = window.__vitest_worker__;
71
+ if (!state) {
72
+ throw new Error("Worker state is not found. This is an issue with Vitest. Please, open an issue.");
73
+ }
74
+ return state;
75
+ }
76
+ export {
77
+ getConfig as a,
78
+ getWorkerState as b,
79
+ executor as e,
80
+ getBrowserState as g
81
+ };
@@ -56,7 +56,9 @@ async function reportUnexpectedError(
56
56
  error,
57
57
  ) {
58
58
  const processedError = serializeError(error)
59
- await client.rpc.onUnhandledError(processedError, type)
59
+ await client.waitForConnection().then(() => {
60
+ return client.rpc.onUnhandledError(processedError, type)
61
+ }).catch(console.error)
60
62
  const state = __vitest_browser_runner__
61
63
 
62
64
  if (state.type === 'orchestrator') {
@@ -1,50 +1,52 @@
1
- const moduleCache = new Map();
2
-
3
- function wrapModule(module) {
4
- if (typeof module === "function") {
5
- const promise = new Promise((resolve, reject) => {
6
- if (typeof __vitest_mocker__ === "undefined")
7
- return module().then(resolve, reject);
8
- __vitest_mocker__.prepare().finally(() => {
9
- module().then(resolve, reject);
1
+ (() => {
2
+ const moduleCache = new Map();
3
+
4
+ function wrapModule(module) {
5
+ if (typeof module === "function") {
6
+ const promise = new Promise((resolve, reject) => {
7
+ if (typeof __vitest_mocker__ === "undefined")
8
+ return module().then(resolve, reject);
9
+ __vitest_mocker__.prepare().finally(() => {
10
+ module().then(resolve, reject);
11
+ });
10
12
  });
11
- });
12
- moduleCache.set(promise, { promise, evaluated: false });
13
- return promise.finally(() => moduleCache.delete(promise));
13
+ moduleCache.set(promise, { promise, evaluated: false });
14
+ return promise.finally(() => moduleCache.delete(promise));
15
+ }
16
+ return module;
14
17
  }
15
- return module;
16
- }
17
-
18
- window.__vitest_browser_runner__ = {
19
- wrapModule,
20
- wrapDynamicImport: wrapModule,
21
- moduleCache,
22
- config: { __VITEST_CONFIG__ },
23
- viteConfig: { __VITEST_VITE_CONFIG__ },
24
- files: { __VITEST_FILES__ },
25
- type: { __VITEST_TYPE__ },
26
- contextId: { __VITEST_CONTEXT_ID__ },
27
- testerId: { __VITEST_TESTER_ID__ },
28
- provider: { __VITEST_PROVIDER__ },
29
- providedContext: { __VITEST_PROVIDED_CONTEXT__ },
30
- };
31
-
32
- const config = __vitest_browser_runner__.config;
33
-
34
- if (config.testNamePattern)
35
- config.testNamePattern = parseRegexp(config.testNamePattern);
36
-
37
- function parseRegexp(input) {
38
- // Parse input
39
- const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
40
-
41
- // match nothing
42
- if (!m) return /$^/;
43
-
44
- // Invalid flags
45
- if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3]))
46
- return RegExp(input);
47
-
48
- // Create the regular expression
49
- return new RegExp(m[2], m[3]);
50
- }
18
+
19
+ window.__vitest_browser_runner__ = {
20
+ wrapModule,
21
+ wrapDynamicImport: wrapModule,
22
+ moduleCache,
23
+ config: { __VITEST_CONFIG__ },
24
+ viteConfig: { __VITEST_VITE_CONFIG__ },
25
+ files: { __VITEST_FILES__ },
26
+ type: { __VITEST_TYPE__ },
27
+ contextId: { __VITEST_CONTEXT_ID__ },
28
+ testerId: { __VITEST_TESTER_ID__ },
29
+ provider: { __VITEST_PROVIDER__ },
30
+ providedContext: { __VITEST_PROVIDED_CONTEXT__ },
31
+ };
32
+
33
+ const config = __vitest_browser_runner__.config;
34
+
35
+ if (config.testNamePattern)
36
+ config.testNamePattern = parseRegexp(config.testNamePattern);
37
+
38
+ function parseRegexp(input) {
39
+ // Parse input
40
+ const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
41
+
42
+ // match nothing
43
+ if (!m) return /$^/;
44
+
45
+ // Invalid flags
46
+ if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3]))
47
+ return RegExp(input);
48
+
49
+ // Create the regular expression
50
+ return new RegExp(m[2], m[3]);
51
+ }
52
+ })();
@@ -26,8 +26,8 @@
26
26
  {__VITEST_INJECTOR__}
27
27
  {__VITEST_ERROR_CATCHER__}
28
28
  {__VITEST_SCRIPTS__}
29
- <script type="module" crossorigin src="/__vitest_browser__/orchestrator-BCPid0xo.js"></script>
30
- <link rel="modulepreload" crossorigin href="/__vitest_browser__/preload-helper-D-WYp1PK.js">
29
+ <script type="module" crossorigin src="/__vitest_browser__/orchestrator-NReaboR_.js"></script>
30
+ <link rel="modulepreload" crossorigin href="/__vitest_browser__/utils-CUwLt_eT.js">
31
31
  </head>
32
32
  <body>
33
33
  <div id="vitest-tester"></div>
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <link rel="icon" href="{__VITEST_FAVICON__}" type="image/svg+xml">
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>{__VITEST_TITLE__}</title>
7
+ <title>Vitest Browser Tester</title>
8
8
  <style>
9
9
  html {
10
10
  padding: 0;
@@ -16,14 +16,9 @@
16
16
  min-height: 100vh;
17
17
  }
18
18
  </style>
19
- {__VITEST_INJECTOR__}
20
- <script>{__VITEST_STATE__}</script>
21
- {__VITEST_INTERNAL_SCRIPTS__}
22
- {__VITEST_SCRIPTS__}
23
- <script type="module" crossorigin src="/__vitest_browser__/tester-DZCtFstH.js"></script>
24
- <link rel="modulepreload" crossorigin href="/__vitest_browser__/preload-helper-D-WYp1PK.js">
19
+ <script type="module" crossorigin src="/__vitest_browser__/tester-CAAquV6P.js"></script>
20
+ <link rel="modulepreload" crossorigin href="/__vitest_browser__/utils-CUwLt_eT.js">
25
21
  </head>
26
22
  <body>
27
- {__VITEST_APPEND__}
28
23
  </body>
29
24
  </html>
package/dist/client.js CHANGED
@@ -9,18 +9,24 @@ function createBirpc(functions, options) {
9
9
  const {
10
10
  post,
11
11
  on,
12
+ off = () => {
13
+ },
12
14
  eventNames = [],
13
15
  serialize = defaultSerialize,
14
16
  deserialize = defaultDeserialize,
15
17
  resolver,
18
+ bind = "rpc",
16
19
  timeout = DEFAULT_TIMEOUT
17
20
  } = options;
18
21
  const rpcPromiseMap = /* @__PURE__ */ new Map();
19
22
  let _promise;
23
+ let closed = false;
20
24
  const rpc = new Proxy({}, {
21
25
  get(_, method) {
22
26
  if (method === "$functions")
23
27
  return functions;
28
+ if (method === "$close")
29
+ return close;
24
30
  if (method === "then" && !eventNames.includes("then") && !("then" in functions))
25
31
  return void 0;
26
32
  const sendEvent = (...args) => {
@@ -31,7 +37,15 @@ function createBirpc(functions, options) {
31
37
  return sendEvent;
32
38
  }
33
39
  const sendCall = async (...args) => {
34
- await _promise;
40
+ if (closed)
41
+ throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
42
+ if (_promise) {
43
+ try {
44
+ await _promise;
45
+ } finally {
46
+ _promise = void 0;
47
+ }
48
+ }
35
49
  return new Promise((resolve, reject) => {
36
50
  const id = nanoid();
37
51
  let timeoutId;
@@ -48,7 +62,7 @@ function createBirpc(functions, options) {
48
62
  if (typeof timeoutId === "object")
49
63
  timeoutId = timeoutId.unref?.();
50
64
  }
51
- rpcPromiseMap.set(id, { resolve, reject, timeoutId });
65
+ rpcPromiseMap.set(id, { resolve, reject, timeoutId, method });
52
66
  post(serialize({ m: method, a: args, i: id, t: "q" }));
53
67
  });
54
68
  };
@@ -56,7 +70,15 @@ function createBirpc(functions, options) {
56
70
  return sendCall;
57
71
  }
58
72
  });
59
- _promise = on(async (data, ...extra) => {
73
+ function close() {
74
+ closed = true;
75
+ rpcPromiseMap.forEach(({ reject, method }) => {
76
+ reject(new Error(`[birpc] rpc is closed, cannot call "${method}"`));
77
+ });
78
+ rpcPromiseMap.clear();
79
+ off(onMessage);
80
+ }
81
+ async function onMessage(data, ...extra) {
60
82
  const msg = deserialize(data);
61
83
  if (msg.t === "q") {
62
84
  const { m: method, a: args } = msg;
@@ -66,7 +88,7 @@ function createBirpc(functions, options) {
66
88
  error = new Error(`[birpc] function "${method}" not found`);
67
89
  } else {
68
90
  try {
69
- result = await fn.apply(rpc, args);
91
+ result = await fn.apply(bind === "rpc" ? rpc : functions, args);
70
92
  } catch (e) {
71
93
  error = e;
72
94
  }
@@ -88,7 +110,8 @@ function createBirpc(functions, options) {
88
110
  }
89
111
  rpcPromiseMap.delete(ack);
90
112
  }
91
- });
113
+ }
114
+ _promise = on(onMessage);
92
115
  return rpc;
93
116
  }
94
117
  const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
package/dist/context.js CHANGED
@@ -90,22 +90,31 @@ const channel = new BroadcastChannel(`vitest:${contextId}`);
90
90
  function triggerCommand(command, ...args) {
91
91
  return rpc().triggerCommand(contextId, command, filepath(), args);
92
92
  }
93
- function createUserEvent(__tl_user_event__) {
93
+ function createUserEvent(__tl_user_event_base__, options) {
94
+ let __tl_user_event__ = __tl_user_event_base__?.setup(options ?? {});
94
95
  const keyboard = {
95
96
  unreleased: []
96
97
  };
97
98
  return {
98
- setup(options) {
99
- return createUserEvent(__tl_user_event__?.setup(options));
99
+ setup(options2) {
100
+ return createUserEvent(__tl_user_event_base__, options2);
100
101
  },
101
- click(element, options = {}) {
102
- return convertToLocator(element).click(processClickOptions(options));
102
+ async cleanup() {
103
+ if (typeof __tl_user_event_base__ !== "undefined") {
104
+ __tl_user_event__ = __tl_user_event_base__?.setup(options ?? {});
105
+ return;
106
+ }
107
+ await triggerCommand("__vitest_cleanup", keyboard);
108
+ keyboard.unreleased = [];
109
+ },
110
+ click(element, options2 = {}) {
111
+ return convertToLocator(element).click(processClickOptions(options2));
103
112
  },
104
- dblClick(element, options = {}) {
105
- return convertToLocator(element).dblClick(processClickOptions(options));
113
+ dblClick(element, options2 = {}) {
114
+ return convertToLocator(element).dblClick(processClickOptions(options2));
106
115
  },
107
- tripleClick(element, options = {}) {
108
- return convertToLocator(element).tripleClick(processClickOptions(options));
116
+ tripleClick(element, options2 = {}) {
117
+ return convertToLocator(element).tripleClick(processClickOptions(options2));
109
118
  },
110
119
  selectOptions(element, value) {
111
120
  return convertToLocator(element).selectOptions(value);
@@ -113,31 +122,31 @@ function createUserEvent(__tl_user_event__) {
113
122
  clear(element) {
114
123
  return convertToLocator(element).clear();
115
124
  },
116
- hover(element, options = {}) {
117
- return convertToLocator(element).hover(processHoverOptions(options));
125
+ hover(element, options2 = {}) {
126
+ return convertToLocator(element).hover(processHoverOptions(options2));
118
127
  },
119
- unhover(element, options = {}) {
120
- return convertToLocator(element).unhover(options);
128
+ unhover(element, options2 = {}) {
129
+ return convertToLocator(element).unhover(options2);
121
130
  },
122
131
  upload(element, files) {
123
132
  return convertToLocator(element).upload(files);
124
133
  },
125
134
  // non userEvent events, but still useful
126
- fill(element, text, options) {
127
- return convertToLocator(element).fill(text, options);
135
+ fill(element, text, options2) {
136
+ return convertToLocator(element).fill(text, options2);
128
137
  },
129
- dragAndDrop(source, target, options = {}) {
138
+ dragAndDrop(source, target, options2 = {}) {
130
139
  const sourceLocator = convertToLocator(source);
131
140
  const targetLocator = convertToLocator(target);
132
- return sourceLocator.dropTo(targetLocator, processDragAndDropOptions(options));
141
+ return sourceLocator.dropTo(targetLocator, processDragAndDropOptions(options2));
133
142
  },
134
143
  // testing-library user-event
135
- async type(element, text, options = {}) {
144
+ async type(element, text, options2 = {}) {
136
145
  if (typeof __tl_user_event__ !== "undefined") {
137
146
  return __tl_user_event__.type(
138
147
  element instanceof Element ? element : element.element(),
139
148
  text,
140
- options
149
+ options2
141
150
  );
142
151
  }
143
152
  const selector = convertToSelector(element);
@@ -145,15 +154,15 @@ function createUserEvent(__tl_user_event__) {
145
154
  "__vitest_type",
146
155
  selector,
147
156
  text,
148
- { ...options, unreleased: keyboard.unreleased }
157
+ { ...options2, unreleased: keyboard.unreleased }
149
158
  );
150
159
  keyboard.unreleased = unreleased;
151
160
  },
152
- tab(options = {}) {
161
+ tab(options2 = {}) {
153
162
  if (typeof __tl_user_event__ !== "undefined") {
154
- return __tl_user_event__.tab(options);
163
+ return __tl_user_event__.tab(options2);
155
164
  }
156
- return triggerCommand("__vitest_tab", options);
165
+ return triggerCommand("__vitest_tab", options2);
157
166
  },
158
167
  async keyboard(text) {
159
168
  if (typeof __tl_user_event__ !== "undefined") {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { CDPSession, BrowserServerState as BrowserServerState$1, BrowserServerStateContext, BrowserServer as BrowserServer$1, WorkspaceProject, Vite, BrowserProvider, BrowserScript, Vitest, ProcessPool } from 'vitest/node';
2
1
  import { Plugin } from 'vitest/config';
2
+ import { CDPSession, BrowserServerState as BrowserServerState$1, BrowserServerStateContext, BrowserServer as BrowserServer$1, WorkspaceProject, Vite, BrowserProvider, BrowserScript, Vitest, ProcessPool } from 'vitest/node';
3
3
  import * as vitest from 'vitest';
4
- import { RunnerTestFile, TaskResultPack, AfterSuiteRunMeta, CancelReason, UserConsoleLog, SnapshotResult, SerializedConfig } from 'vitest';
5
- import { ErrorWithDiff } from '@vitest/utils';
4
+ import { RunnerTestFile, TaskResultPack, AfterSuiteRunMeta, CancelReason, UserConsoleLog, SnapshotResult, SerializedConfig, ErrorWithDiff } from 'vitest';
5
+ import { HtmlTagDescriptor } from 'vite';
6
6
  import { StackTraceParserOptions } from '@vitest/utils/source-map';
7
7
  import { ServerIdResolution, ServerMockResolution } from '@vitest/mocker/node';
8
8
 
@@ -19,6 +19,7 @@ type BirpcReturn<RemoteFunctions, LocalFunctions = Record<string, never>> = {
19
19
  [K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>;
20
20
  } & {
21
21
  $functions: LocalFunctions;
22
+ $close: () => void;
22
23
  };
23
24
 
24
25
  interface WebSocketBrowserHandlers {
@@ -94,9 +95,10 @@ declare class BrowserServer implements BrowserServer$1 {
94
95
  faviconUrl: string;
95
96
  prefixTesterUrl: string;
96
97
  orchestratorScripts: string | undefined;
97
- testerScripts: string | undefined;
98
+ testerScripts: HtmlTagDescriptor[] | undefined;
98
99
  manifest: Promise<Vite.Manifest> | Vite.Manifest;
99
100
  testerHtml: Promise<string> | string;
101
+ testerFilepath: string;
100
102
  orchestratorHtml: Promise<string> | string;
101
103
  injectorJs: Promise<string> | string;
102
104
  errorCatcherUrl: string;
@@ -113,7 +115,7 @@ declare class BrowserServer implements BrowserServer$1 {
113
115
  contextId: string;
114
116
  testFile: string;
115
117
  };
116
- formatScripts(scripts: BrowserScript[] | undefined): Promise<string>;
118
+ formatScripts(scripts: BrowserScript[] | undefined): Promise<HtmlTagDescriptor[]>;
117
119
  initBrowserProvider(): Promise<void>;
118
120
  parseErrorStacktrace(e: ErrorWithDiff, options?: StackTraceParserOptions): vitest.ParsedStack[];
119
121
  parseStacktrace(trace: string, options?: StackTraceParserOptions): vitest.ParsedStack[];
@@ -122,8 +124,10 @@ declare class BrowserServer implements BrowserServer$1 {
122
124
  close(): Promise<void>;
123
125
  }
124
126
 
127
+ declare const distRoot: string;
128
+
125
129
  declare function createBrowserPool(ctx: Vitest): ProcessPool;
126
130
 
127
131
  declare function createBrowserServer(project: WorkspaceProject, configFile: string | undefined, prePlugins?: Plugin[], postPlugins?: Plugin[]): Promise<BrowserServer>;
128
132
 
129
- export { BrowserServer, createBrowserPool, createBrowserServer };
133
+ export { BrowserServer, createBrowserPool, createBrowserServer, distRoot };