@vitest/browser 2.0.0-beta.10 → 2.0.0-beta.12

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,371 @@
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) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import { c as channel, g as getBrowserState, a as client, b as globalChannel, d as getConfig, r as relative } from "./client-Dz5Ebwug.js";
8
+ import { http } from "/__virtual_vitest__?id=msw%2Fcore%2Fhttp";
9
+ import { setupWorker } from "/__virtual_vitest__?id=msw%2Fbrowser";
10
+ function generateHash(str) {
11
+ let hash = 0;
12
+ if (str.length === 0) {
13
+ return `${hash}`;
14
+ }
15
+ for (let i = 0; i < str.length; i++) {
16
+ const char = str.charCodeAt(i);
17
+ hash = (hash << 5) - hash + char;
18
+ hash = hash & hash;
19
+ }
20
+ return `${hash}`;
21
+ }
22
+ function getUiAPI() {
23
+ return window.__vitest_ui_api__;
24
+ }
25
+ function createModuleMocker() {
26
+ const mocks = /* @__PURE__ */ new Map();
27
+ const worker = setupWorker(
28
+ http.get(/.+/, async ({ request }) => {
29
+ const path = removeTimestamp(request.url.slice(location.origin.length));
30
+ if (!mocks.has(path)) {
31
+ return passthrough();
32
+ }
33
+ const mock = mocks.get(path);
34
+ if (mock === void 0) {
35
+ const exports = await getFactoryExports(path);
36
+ const module = `const module = __vitest_mocker__.get('${path}');`;
37
+ const keys = exports.map((name) => {
38
+ if (name === "default") {
39
+ return `export default module['default'];`;
40
+ }
41
+ return `export const ${name} = module['${name}'];`;
42
+ }).join("\n");
43
+ const text = `${module}
44
+ ${keys}`;
45
+ return new Response(text, {
46
+ headers: {
47
+ "Content-Type": "application/javascript"
48
+ }
49
+ });
50
+ }
51
+ if (typeof mock === "string") {
52
+ return Response.redirect(mock);
53
+ }
54
+ return Response.redirect(injectQuery(path, "mock=auto"));
55
+ })
56
+ );
57
+ let started = false;
58
+ let startPromise;
59
+ async function init() {
60
+ if (started) {
61
+ return;
62
+ }
63
+ if (startPromise) {
64
+ return startPromise;
65
+ }
66
+ startPromise = worker.start({
67
+ serviceWorker: {
68
+ url: "/__vitest_msw__"
69
+ },
70
+ quiet: true
71
+ }).finally(() => {
72
+ started = true;
73
+ startPromise = void 0;
74
+ });
75
+ await startPromise;
76
+ }
77
+ return {
78
+ async mock(event) {
79
+ await init();
80
+ event.paths.forEach((path) => mocks.set(path, event.mock));
81
+ channel.postMessage({ type: "mock:done" });
82
+ },
83
+ async unmock(event) {
84
+ await init();
85
+ event.paths.forEach((path) => mocks.delete(path));
86
+ channel.postMessage({ type: "unmock:done" });
87
+ },
88
+ invalidate() {
89
+ mocks.clear();
90
+ }
91
+ };
92
+ }
93
+ function getFactoryExports(id) {
94
+ channel.postMessage({
95
+ type: "mock-factory:request",
96
+ id
97
+ });
98
+ return new Promise((resolve, reject) => {
99
+ channel.addEventListener(
100
+ "message",
101
+ function onMessage(e) {
102
+ if (e.data.type === "mock-factory:response") {
103
+ resolve(e.data.exports);
104
+ channel.removeEventListener("message", onMessage);
105
+ }
106
+ if (e.data.type === "mock-factory:error") {
107
+ reject(e.data.error);
108
+ channel.removeEventListener("message", onMessage);
109
+ }
110
+ }
111
+ );
112
+ });
113
+ }
114
+ const timestampRegexp = /(\?|&)t=\d{13}/;
115
+ function removeTimestamp(url2) {
116
+ return url2.replace(timestampRegexp, "");
117
+ }
118
+ function passthrough() {
119
+ return new Response(null, {
120
+ status: 302,
121
+ statusText: "Passthrough",
122
+ headers: {
123
+ "x-msw-intention": "passthrough"
124
+ }
125
+ });
126
+ }
127
+ const postfixRE = /[?#].*$/;
128
+ function cleanUrl(url2) {
129
+ return url2.replace(postfixRE, "");
130
+ }
131
+ const replacePercentageRE = /%/g;
132
+ function injectQuery(url2, queryToInject) {
133
+ const resolvedUrl = new URL(
134
+ url2.replace(replacePercentageRE, "%25"),
135
+ location.href
136
+ );
137
+ const { search, hash } = resolvedUrl;
138
+ const pathname = cleanUrl(url2);
139
+ return `${pathname}?${queryToInject}${search ? `&${search.slice(1)}` : ""}${hash ?? ""}`;
140
+ }
141
+ const url = new URL(location.href);
142
+ const ID_ALL = "__vitest_all__";
143
+ class IframeOrchestrator {
144
+ constructor() {
145
+ __publicField(this, "cancelled", false);
146
+ __publicField(this, "runningFiles", /* @__PURE__ */ new Set());
147
+ __publicField(this, "mocker", createModuleMocker());
148
+ __publicField(this, "iframes", /* @__PURE__ */ new Map());
149
+ }
150
+ async init() {
151
+ const testFiles = getBrowserState().files;
152
+ debug("test files", testFiles.join(", "));
153
+ this.runningFiles.clear();
154
+ testFiles.forEach((file) => this.runningFiles.add(file));
155
+ channel.addEventListener(
156
+ "message",
157
+ (e) => this.onIframeEvent(e)
158
+ );
159
+ globalChannel.addEventListener(
160
+ "message",
161
+ (e) => this.onGlobalChannelEvent(e)
162
+ );
163
+ }
164
+ async createTesters(testFiles) {
165
+ this.cancelled = false;
166
+ this.runningFiles.clear();
167
+ testFiles.forEach((file) => this.runningFiles.add(file));
168
+ const config = getConfig();
169
+ const container = await getContainer(config);
170
+ if (config.browser.ui) {
171
+ container.className = "scrolls";
172
+ container.textContent = "";
173
+ }
174
+ const { width, height } = config.browser.viewport;
175
+ this.iframes.forEach((iframe) => iframe.remove());
176
+ this.iframes.clear();
177
+ if (config.isolate === false) {
178
+ const iframe = this.createIframe(container, ID_ALL);
179
+ await setIframeViewport(iframe, width, height);
180
+ return;
181
+ }
182
+ for (const file of testFiles) {
183
+ if (this.cancelled) {
184
+ done();
185
+ return;
186
+ }
187
+ const iframe = this.createIframe(container, file);
188
+ await setIframeViewport(iframe, width, height);
189
+ await new Promise((resolve) => {
190
+ channel.addEventListener(
191
+ "message",
192
+ function handler(e) {
193
+ if (e.data.type === "done" || e.data.type === "error") {
194
+ channel.removeEventListener("message", handler);
195
+ resolve();
196
+ }
197
+ }
198
+ );
199
+ });
200
+ }
201
+ }
202
+ createIframe(container, file) {
203
+ if (this.iframes.has(file)) {
204
+ this.iframes.get(file).remove();
205
+ this.iframes.delete(file);
206
+ }
207
+ const iframe = document.createElement("iframe");
208
+ iframe.setAttribute("loading", "eager");
209
+ iframe.setAttribute(
210
+ "src",
211
+ `${url.pathname}__vitest_test__/__test__/${getBrowserState().contextId}/${encodeURIComponent(file)}`
212
+ );
213
+ iframe.setAttribute("data-vitest", "true");
214
+ iframe.style.display = "block";
215
+ iframe.style.border = "none";
216
+ iframe.style.zIndex = "1";
217
+ iframe.style.position = "relative";
218
+ iframe.setAttribute("allowfullscreen", "true");
219
+ iframe.setAttribute("allow", "clipboard-write;");
220
+ iframe.setAttribute("name", "vitest-iframe");
221
+ this.iframes.set(file, iframe);
222
+ container.appendChild(iframe);
223
+ return iframe;
224
+ }
225
+ async onGlobalChannelEvent(e) {
226
+ debug("global channel event", JSON.stringify(e.data));
227
+ switch (e.data.type) {
228
+ case "cancel": {
229
+ this.cancelled = true;
230
+ break;
231
+ }
232
+ }
233
+ }
234
+ async onIframeEvent(e) {
235
+ var _a;
236
+ debug("iframe event", JSON.stringify(e.data));
237
+ switch (e.data.type) {
238
+ case "viewport": {
239
+ const { width, height, id } = e.data;
240
+ const iframe = this.iframes.get(id);
241
+ if (!iframe) {
242
+ const error = new Error(`Cannot find iframe with id ${id}`);
243
+ channel.postMessage({
244
+ type: "viewport:fail",
245
+ id,
246
+ error: error.message
247
+ });
248
+ await client.rpc.onUnhandledError(
249
+ {
250
+ name: "Teardown Error",
251
+ message: error.message
252
+ },
253
+ "Teardown Error"
254
+ );
255
+ return;
256
+ }
257
+ await setIframeViewport(iframe, width, height);
258
+ channel.postMessage({ type: "viewport:done", id });
259
+ break;
260
+ }
261
+ case "done": {
262
+ const filenames = e.data.filenames;
263
+ filenames.forEach((filename) => this.runningFiles.delete(filename));
264
+ if (!this.runningFiles.size) {
265
+ const ui = getUiAPI();
266
+ if (ui && filenames.length > 1) {
267
+ const id = generateFileId(filenames[filenames.length - 1]);
268
+ ui.setCurrentFileId(id);
269
+ }
270
+ await done();
271
+ } else {
272
+ const iframeId = e.data.id;
273
+ (_a = this.iframes.get(iframeId)) == null ? void 0 : _a.remove();
274
+ this.iframes.delete(iframeId);
275
+ }
276
+ break;
277
+ }
278
+ case "error": {
279
+ const iframeId = e.data.id;
280
+ this.iframes.delete(iframeId);
281
+ await client.rpc.onUnhandledError(e.data.error, e.data.errorType);
282
+ if (iframeId === ID_ALL) {
283
+ this.runningFiles.clear();
284
+ } else {
285
+ this.runningFiles.delete(iframeId);
286
+ }
287
+ if (!this.runningFiles.size) {
288
+ await done();
289
+ }
290
+ break;
291
+ }
292
+ case "mock:invalidate":
293
+ this.mocker.invalidate();
294
+ break;
295
+ case "unmock":
296
+ await this.mocker.unmock(e.data);
297
+ break;
298
+ case "mock":
299
+ await this.mocker.mock(e.data);
300
+ break;
301
+ case "mock-factory:error":
302
+ case "mock-factory:response":
303
+ break;
304
+ default: {
305
+ e.data;
306
+ await client.rpc.onUnhandledError(
307
+ {
308
+ name: "Unexpected Event",
309
+ message: `Unexpected event: ${e.data.type}`
310
+ },
311
+ "Unexpected Event"
312
+ );
313
+ await done();
314
+ }
315
+ }
316
+ }
317
+ }
318
+ const orchestrator = new IframeOrchestrator();
319
+ let promiseTesters;
320
+ getBrowserState().createTesters = async (files) => {
321
+ await promiseTesters;
322
+ promiseTesters = orchestrator.createTesters(files).finally(() => {
323
+ promiseTesters = void 0;
324
+ });
325
+ await promiseTesters;
326
+ };
327
+ async function done() {
328
+ await client.rpc.finishBrowserTests(getBrowserState().contextId);
329
+ }
330
+ async function getContainer(config) {
331
+ if (config.browser.ui) {
332
+ const element = document.querySelector("#tester-ui");
333
+ if (!element) {
334
+ return new Promise((resolve) => {
335
+ setTimeout(() => {
336
+ resolve(getContainer(config));
337
+ }, 30);
338
+ });
339
+ }
340
+ return element;
341
+ }
342
+ return document.querySelector("#vitest-tester");
343
+ }
344
+ client.ws.addEventListener("open", async () => {
345
+ const testFiles = getBrowserState().files;
346
+ await orchestrator.init();
347
+ if (testFiles.length) {
348
+ await orchestrator.createTesters(testFiles);
349
+ }
350
+ });
351
+ function generateFileId(file) {
352
+ const config = getConfig();
353
+ const project = config.name || "";
354
+ const path = relative(config.root, file);
355
+ return generateHash(`${path}${project}`);
356
+ }
357
+ async function setIframeViewport(iframe, width, height) {
358
+ const ui = getUiAPI();
359
+ if (ui) {
360
+ await ui.setIframeViewport(width, height);
361
+ } else {
362
+ iframe.style.width = `${width}px`;
363
+ iframe.style.height = `${height}px`;
364
+ }
365
+ }
366
+ function debug(...args) {
367
+ const debug2 = getConfig().env.VITEST_BROWSER_DEBUG;
368
+ if (debug2 && debug2 !== "false") {
369
+ client.rpc.debug(...args.map(String));
370
+ }
371
+ }