vitest 1.1.2 → 1.2.0

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 (62) hide show
  1. package/dist/browser.d.ts +1 -1
  2. package/dist/browser.js +5 -31
  3. package/dist/chunks/{api-setup.mFKdEKxa.js → api-setup.MAoRkVWJ.js} +60 -6
  4. package/dist/chunks/{integrations-globals.tnKXwyh5.js → integrations-globals.VbxbZ7hn.js} +9 -8
  5. package/dist/{entry.js → chunks/runtime-runBaseTests.LWFmrzDk.js} +20 -18
  6. package/dist/cli-wrapper.js +1 -1
  7. package/dist/cli.js +14 -14
  8. package/dist/config.cjs +12 -1
  9. package/dist/config.d.ts +5 -2
  10. package/dist/config.js +12 -2
  11. package/dist/coverage.d.ts +1 -1
  12. package/dist/environments.d.ts +1 -1
  13. package/dist/environments.js +1 -1
  14. package/dist/execute.d.ts +8 -6
  15. package/dist/execute.js +4 -7
  16. package/dist/index.d.ts +4 -3
  17. package/dist/index.js +8 -7
  18. package/dist/node.d.ts +3 -3
  19. package/dist/node.js +12 -12
  20. package/dist/{reporters-xH8_lESK.d.ts → reporters-trlZlObr.d.ts} +113 -27
  21. package/dist/reporters.d.ts +1 -1
  22. package/dist/reporters.js +4 -4
  23. package/dist/runners.d.ts +1 -1
  24. package/dist/runners.js +7 -5
  25. package/dist/{suite-GoqTeX8s.d.ts → suite-6Pt_ep5V.d.ts} +1 -1
  26. package/dist/suite.d.ts +2 -2
  27. package/dist/suite.js +3 -3
  28. package/dist/vendor/base.8wUUWReP.js +38 -0
  29. package/dist/vendor/{base._79unx2z.js → base.dzu0Y6Hj.js} +10 -1
  30. package/dist/vendor/{benchmark.WVm6DARl.js → benchmark.IlKmJkUU.js} +1 -1
  31. package/dist/vendor/{constants.WSvnD_fn.js → constants.i1PoEnhr.js} +9 -1
  32. package/dist/vendor/{coverage.v6aD8iAh.js → coverage.E7sG1b3r.js} +1 -1
  33. package/dist/vendor/{environments.QJtma9XQ.js → environments.sU0TD7wX.js} +19 -7
  34. package/dist/vendor/execute.3_hyGknJ.js +589 -0
  35. package/dist/vendor/{global.L7JRz1qU.js → global.CkGT_TMy.js} +10 -1
  36. package/dist/vendor/{index.IhksUGLR.js → index.3iX2R_Z5.js} +6 -6
  37. package/dist/vendor/{index.h0j9y5vy.js → index.D-jOsMas.js} +5 -5
  38. package/dist/vendor/{index.XU72Rmy8.js → index.rJjbcrrp.js} +1 -1
  39. package/dist/vendor/{node.UBNKMR9Y.js → node.xyYo9ZvH.js} +660 -288
  40. package/dist/vendor/{reporters.oUR9etwS.js → reporters.2PaQ2peU.js} +11 -8
  41. package/dist/vendor/{rpc.Bl-ysZIr.js → rpc.w4v8oCkK.js} +23 -2
  42. package/dist/vendor/{run-once.X3E7xx3F.js → run-once.Olz_Zkd8.js} +2 -2
  43. package/dist/vendor/setup-common.j9IXYrbN.js +29 -0
  44. package/dist/vendor/utils.GbToHGHI.js +41 -0
  45. package/dist/vendor/{vi.DTC--YO5.js → vi.smj1Ggd4.js} +9 -5
  46. package/dist/vendor/vm.vFKXXdo0.js +696 -0
  47. package/dist/worker.js +109 -82
  48. package/dist/workers/forks.js +33 -0
  49. package/dist/{entry-vm.js → workers/runVmTests.js} +20 -16
  50. package/dist/workers/threads.js +26 -0
  51. package/dist/workers/vmForks.js +43 -0
  52. package/dist/workers/vmThreads.js +36 -0
  53. package/dist/workers.d.ts +36 -0
  54. package/dist/workers.js +30 -0
  55. package/package.json +11 -7
  56. package/workers.d.ts +1 -0
  57. package/dist/child.js +0 -125
  58. package/dist/vendor/execute.cedv4NLQ.js +0 -1235
  59. package/dist/vendor/inspector.lFAeuaAt.js +0 -26
  60. package/dist/vendor/loader.L9CYwKn1.js +0 -39
  61. package/dist/vm.js +0 -126
  62. /package/dist/{paths.js → path.js} +0 -0
@@ -0,0 +1,696 @@
1
+ import vm, { isContext } from 'node:vm';
2
+ import { pathToFileURL, fileURLToPath } from 'node:url';
3
+ import { dirname, basename, extname, normalize, join, resolve } from 'pathe';
4
+ import { createCustomConsole } from '../chunks/runtime-console.hf2msWA9.js';
5
+ import { g as getDefaultRequestStubs, s as startVitestExecutor } from './execute.3_hyGknJ.js';
6
+ import { distDir } from '../path.js';
7
+ import { dirname as dirname$1 } from 'node:path';
8
+ import { statSync, readFileSync } from 'node:fs';
9
+ import { isNodeBuiltin, isPrimitive, toArray, getCachedData, setCacheData } from 'vite-node/utils';
10
+ import { createRequire, Module } from 'node:module';
11
+ import { CSS_LANGS_RE, KNOWN_ASSET_RE } from 'vite-node/constants';
12
+ import './index.rJjbcrrp.js';
13
+ import { p as provideWorkerState } from './global.CkGT_TMy.js';
14
+
15
+ const _require = createRequire(import.meta.url);
16
+ const requiresCache = /* @__PURE__ */ new WeakMap();
17
+ class CommonjsExecutor {
18
+ context;
19
+ requireCache = /* @__PURE__ */ new Map();
20
+ publicRequireCache = this.createProxyCache();
21
+ moduleCache = /* @__PURE__ */ new Map();
22
+ builtinCache = /* @__PURE__ */ Object.create(null);
23
+ extensions = /* @__PURE__ */ Object.create(null);
24
+ fs;
25
+ Module;
26
+ constructor(options) {
27
+ this.context = options.context;
28
+ this.fs = options.fileMap;
29
+ const primitives = vm.runInContext("({ Object, Array, Error })", this.context);
30
+ const executor = this;
31
+ this.Module = class Module$1 {
32
+ exports;
33
+ isPreloading = false;
34
+ id;
35
+ filename;
36
+ loaded;
37
+ parent;
38
+ children = [];
39
+ path;
40
+ paths = [];
41
+ constructor(id = "", parent) {
42
+ this.exports = primitives.Object.create(Object.prototype);
43
+ this.path = dirname(id);
44
+ this.id = id;
45
+ this.filename = id;
46
+ this.loaded = false;
47
+ this.parent = parent;
48
+ }
49
+ get require() {
50
+ const require = requiresCache.get(this);
51
+ if (require)
52
+ return require;
53
+ const _require2 = Module$1.createRequire(this.id);
54
+ requiresCache.set(this, _require2);
55
+ return _require2;
56
+ }
57
+ _compile(code, filename) {
58
+ const cjsModule = Module$1.wrap(code);
59
+ const script = new vm.Script(cjsModule, {
60
+ filename,
61
+ importModuleDynamically: options.importModuleDynamically
62
+ });
63
+ script.identifier = filename;
64
+ const fn = script.runInContext(executor.context);
65
+ const __dirname = dirname(filename);
66
+ executor.requireCache.set(filename, this);
67
+ try {
68
+ fn(this.exports, this.require, this, filename, __dirname);
69
+ return this.exports;
70
+ } finally {
71
+ this.loaded = true;
72
+ }
73
+ }
74
+ // exposed for external use, Node.js does the opposite
75
+ static _load = (request, parent, _isMain) => {
76
+ const require = Module$1.createRequire((parent == null ? void 0 : parent.filename) ?? request);
77
+ return require(request);
78
+ };
79
+ static wrap = (script) => {
80
+ return Module$1.wrapper[0] + script + Module$1.wrapper[1];
81
+ };
82
+ static wrapper = new primitives.Array(
83
+ "(function (exports, require, module, __filename, __dirname) { ",
84
+ "\n});"
85
+ );
86
+ static builtinModules = Module.builtinModules;
87
+ static findSourceMap = Module.findSourceMap;
88
+ static SourceMap = Module.SourceMap;
89
+ static syncBuiltinESMExports = Module.syncBuiltinESMExports;
90
+ static _cache = executor.moduleCache;
91
+ static _extensions = executor.extensions;
92
+ static createRequire = (filename) => {
93
+ return executor.createRequire(filename);
94
+ };
95
+ static runMain = () => {
96
+ throw new primitives.Error('[vitest] "runMain" is not implemented.');
97
+ };
98
+ // @ts-expect-error not typed
99
+ static _resolveFilename = Module._resolveFilename;
100
+ // @ts-expect-error not typed
101
+ static _findPath = Module._findPath;
102
+ // @ts-expect-error not typed
103
+ static _initPaths = Module._initPaths;
104
+ // @ts-expect-error not typed
105
+ static _preloadModules = Module._preloadModules;
106
+ // @ts-expect-error not typed
107
+ static _resolveLookupPaths = Module._resolveLookupPaths;
108
+ // @ts-expect-error not typed
109
+ static globalPaths = Module.globalPaths;
110
+ static isBuiltin = Module.isBuiltin;
111
+ static Module = Module$1;
112
+ };
113
+ this.extensions[".js"] = this.requireJs;
114
+ this.extensions[".json"] = this.requireJson;
115
+ }
116
+ requireJs = (m, filename) => {
117
+ const content = this.fs.readFile(filename);
118
+ m._compile(content, filename);
119
+ };
120
+ requireJson = (m, filename) => {
121
+ const code = this.fs.readFile(filename);
122
+ m.exports = JSON.parse(code);
123
+ };
124
+ createRequire = (filename) => {
125
+ const _require2 = createRequire(filename);
126
+ const require = (id) => {
127
+ const resolved = _require2.resolve(id);
128
+ const ext = extname(resolved);
129
+ if (ext === ".node" || isNodeBuiltin(resolved))
130
+ return this.requireCoreModule(resolved);
131
+ const module = new this.Module(resolved);
132
+ return this.loadCommonJSModule(module, resolved);
133
+ };
134
+ require.resolve = _require2.resolve;
135
+ Object.defineProperty(require, "extensions", {
136
+ get: () => this.extensions,
137
+ set: () => {
138
+ },
139
+ configurable: true
140
+ });
141
+ require.main = void 0;
142
+ require.cache = this.publicRequireCache;
143
+ return require;
144
+ };
145
+ createProxyCache() {
146
+ return new Proxy(/* @__PURE__ */ Object.create(null), {
147
+ defineProperty: () => true,
148
+ deleteProperty: () => true,
149
+ set: () => true,
150
+ get: (_, key) => this.requireCache.get(key),
151
+ has: (_, key) => this.requireCache.has(key),
152
+ ownKeys: () => Array.from(this.requireCache.keys()),
153
+ getOwnPropertyDescriptor() {
154
+ return {
155
+ configurable: true,
156
+ enumerable: true
157
+ };
158
+ }
159
+ });
160
+ }
161
+ // very naive implementation for Node.js require
162
+ loadCommonJSModule(module, filename) {
163
+ const cached = this.requireCache.get(filename);
164
+ if (cached)
165
+ return cached.exports;
166
+ const extension = this.findLongestRegisteredExtension(filename);
167
+ const loader = this.extensions[extension] || this.extensions[".js"];
168
+ loader(module, filename);
169
+ return module.exports;
170
+ }
171
+ findLongestRegisteredExtension(filename) {
172
+ const name = basename(filename);
173
+ let currentExtension;
174
+ let index;
175
+ let startIndex = 0;
176
+ while ((index = name.indexOf(".", startIndex)) !== -1) {
177
+ startIndex = index + 1;
178
+ if (index === 0)
179
+ continue;
180
+ currentExtension = name.slice(index);
181
+ if (this.extensions[currentExtension])
182
+ return currentExtension;
183
+ }
184
+ return ".js";
185
+ }
186
+ require(identifier) {
187
+ const ext = extname(identifier);
188
+ if (ext === ".node" || isNodeBuiltin(identifier))
189
+ return this.requireCoreModule(identifier);
190
+ const module = new this.Module(identifier);
191
+ return this.loadCommonJSModule(module, identifier);
192
+ }
193
+ requireCoreModule(identifier) {
194
+ const normalized = identifier.replace(/^node:/, "");
195
+ if (this.builtinCache[normalized])
196
+ return this.builtinCache[normalized].exports;
197
+ const moduleExports = _require(identifier);
198
+ if (identifier === "node:module" || identifier === "module") {
199
+ const module = new this.Module("/module.js");
200
+ module.exports = this.Module;
201
+ this.builtinCache[normalized] = module;
202
+ return module.exports;
203
+ }
204
+ this.builtinCache[normalized] = _require.cache[normalized];
205
+ return moduleExports;
206
+ }
207
+ }
208
+
209
+ function interopCommonJsModule(interopDefault, mod) {
210
+ if (isPrimitive(mod) || Array.isArray(mod) || mod instanceof Promise) {
211
+ return {
212
+ keys: [],
213
+ moduleExports: {},
214
+ defaultExport: mod
215
+ };
216
+ }
217
+ if (interopDefault !== false && "__esModule" in mod && !isPrimitive(mod.default)) {
218
+ const defaultKets = Object.keys(mod.default);
219
+ const moduleKeys = Object.keys(mod);
220
+ const allKeys = /* @__PURE__ */ new Set([...defaultKets, ...moduleKeys]);
221
+ allKeys.delete("default");
222
+ return {
223
+ keys: Array.from(allKeys),
224
+ moduleExports: new Proxy(mod, {
225
+ get(mod2, prop) {
226
+ var _a;
227
+ return mod2[prop] ?? ((_a = mod2.default) == null ? void 0 : _a[prop]);
228
+ }
229
+ }),
230
+ defaultExport: mod
231
+ };
232
+ }
233
+ return {
234
+ keys: Object.keys(mod).filter((key) => key !== "default"),
235
+ moduleExports: mod,
236
+ defaultExport: mod
237
+ };
238
+ }
239
+ const SyntheticModule$1 = vm.SyntheticModule;
240
+ const SourceTextModule = vm.SourceTextModule;
241
+
242
+ const dataURIRegex = /^data:(?<mime>text\/javascript|application\/json|application\/wasm)(?:;(?<encoding>charset=utf-8|base64))?,(?<code>.*)$/;
243
+ class EsmExecutor {
244
+ constructor(executor, options) {
245
+ this.executor = executor;
246
+ this.context = options.context;
247
+ }
248
+ moduleCache = /* @__PURE__ */ new Map();
249
+ esmLinkMap = /* @__PURE__ */ new WeakMap();
250
+ context;
251
+ async evaluateModule(m) {
252
+ if (m.status === "unlinked") {
253
+ this.esmLinkMap.set(
254
+ m,
255
+ m.link((identifier, referencer) => this.executor.resolveModule(identifier, referencer.identifier))
256
+ );
257
+ }
258
+ await this.esmLinkMap.get(m);
259
+ if (m.status === "linked")
260
+ await m.evaluate();
261
+ return m;
262
+ }
263
+ async createEsModule(fileUrl, code) {
264
+ const cached = this.moduleCache.get(fileUrl);
265
+ if (cached)
266
+ return cached;
267
+ if (fileUrl.endsWith(".json")) {
268
+ const m2 = new SyntheticModule$1(
269
+ ["default"],
270
+ () => {
271
+ const result = JSON.parse(code);
272
+ m2.setExport("default", result);
273
+ }
274
+ );
275
+ this.moduleCache.set(fileUrl, m2);
276
+ return m2;
277
+ }
278
+ const m = new SourceTextModule(
279
+ code,
280
+ {
281
+ identifier: fileUrl,
282
+ context: this.context,
283
+ importModuleDynamically: this.executor.importModuleDynamically,
284
+ initializeImportMeta: (meta, mod) => {
285
+ meta.url = mod.identifier;
286
+ meta.resolve = (specifier, importer) => {
287
+ return this.executor.resolve(specifier, importer ?? mod.identifier);
288
+ };
289
+ }
290
+ }
291
+ );
292
+ this.moduleCache.set(fileUrl, m);
293
+ return m;
294
+ }
295
+ async loadWebAssemblyModule(source, identifier) {
296
+ const cached = this.moduleCache.get(identifier);
297
+ if (cached)
298
+ return cached;
299
+ const wasmModule = await WebAssembly.compile(source);
300
+ const exports = WebAssembly.Module.exports(wasmModule);
301
+ const imports = WebAssembly.Module.imports(wasmModule);
302
+ const moduleLookup = {};
303
+ for (const { module } of imports) {
304
+ if (moduleLookup[module] === void 0) {
305
+ const resolvedModule = await this.executor.resolveModule(
306
+ module,
307
+ identifier
308
+ );
309
+ moduleLookup[module] = await this.evaluateModule(resolvedModule);
310
+ }
311
+ }
312
+ const syntheticModule = new SyntheticModule$1(
313
+ exports.map(({ name }) => name),
314
+ () => {
315
+ const importsObject = {};
316
+ for (const { module, name } of imports) {
317
+ if (!importsObject[module])
318
+ importsObject[module] = {};
319
+ importsObject[module][name] = moduleLookup[module].namespace[name];
320
+ }
321
+ const wasmInstance = new WebAssembly.Instance(
322
+ wasmModule,
323
+ importsObject
324
+ );
325
+ for (const { name } of exports)
326
+ syntheticModule.setExport(name, wasmInstance.exports[name]);
327
+ },
328
+ { context: this.context, identifier }
329
+ );
330
+ return syntheticModule;
331
+ }
332
+ cacheModule(identifier, module) {
333
+ this.moduleCache.set(identifier, module);
334
+ }
335
+ resolveCachedModule(identifier) {
336
+ return this.moduleCache.get(identifier);
337
+ }
338
+ async createDataModule(identifier) {
339
+ const cached = this.moduleCache.get(identifier);
340
+ if (cached)
341
+ return cached;
342
+ const match = identifier.match(dataURIRegex);
343
+ if (!match || !match.groups)
344
+ throw new Error("Invalid data URI");
345
+ const mime = match.groups.mime;
346
+ const encoding = match.groups.encoding;
347
+ if (mime === "application/wasm") {
348
+ if (!encoding)
349
+ throw new Error("Missing data URI encoding");
350
+ if (encoding !== "base64")
351
+ throw new Error(`Invalid data URI encoding: ${encoding}`);
352
+ const module = await this.loadWebAssemblyModule(
353
+ Buffer.from(match.groups.code, "base64"),
354
+ identifier
355
+ );
356
+ this.moduleCache.set(identifier, module);
357
+ return module;
358
+ }
359
+ let code = match.groups.code;
360
+ if (!encoding || encoding === "charset=utf-8")
361
+ code = decodeURIComponent(code);
362
+ else if (encoding === "base64")
363
+ code = Buffer.from(code, "base64").toString();
364
+ else
365
+ throw new Error(`Invalid data URI encoding: ${encoding}`);
366
+ if (mime === "application/json") {
367
+ const module = new SyntheticModule$1(
368
+ ["default"],
369
+ () => {
370
+ const obj = JSON.parse(code);
371
+ module.setExport("default", obj);
372
+ },
373
+ { context: this.context, identifier }
374
+ );
375
+ this.moduleCache.set(identifier, module);
376
+ return module;
377
+ }
378
+ return this.createEsModule(identifier, code);
379
+ }
380
+ }
381
+
382
+ const CLIENT_ID = "/@vite/client";
383
+ const CLIENT_FILE = pathToFileURL(CLIENT_ID).href;
384
+ class ViteExecutor {
385
+ constructor(options) {
386
+ this.options = options;
387
+ this.esm = options.esmExecutor;
388
+ }
389
+ esm;
390
+ resolve = (identifier, parent) => {
391
+ if (identifier === CLIENT_ID) {
392
+ if (this.workerState.environment.transformMode === "web")
393
+ return identifier;
394
+ const packageName = this.getPackageName(parent);
395
+ throw new Error(
396
+ `[vitest] Vitest cannot handle ${CLIENT_ID} imported in ${parent} when running in SSR environment. Add "${packageName}" to "ssr.noExternal" if you are using Vite SSR, or to "server.deps.inline" if you are using Vite Node.`
397
+ );
398
+ }
399
+ };
400
+ get workerState() {
401
+ return this.options.context.__vitest_worker__;
402
+ }
403
+ getPackageName(modulePath) {
404
+ const path = normalize(modulePath);
405
+ let name = path.split("/node_modules/").pop() || "";
406
+ if (name == null ? void 0 : name.startsWith("@"))
407
+ name = name.split("/").slice(0, 2).join("/");
408
+ else
409
+ name = name.split("/")[0];
410
+ return name;
411
+ }
412
+ async createViteModule(fileUrl) {
413
+ if (fileUrl === CLIENT_FILE)
414
+ return this.createViteClientModule();
415
+ const cached = this.esm.resolveCachedModule(fileUrl);
416
+ if (cached)
417
+ return cached;
418
+ const result = await this.options.transform(fileUrl, "web");
419
+ if (!result.code)
420
+ throw new Error(`[vitest] Failed to transform ${fileUrl}. Does the file exist?`);
421
+ return this.esm.createEsModule(fileUrl, result.code);
422
+ }
423
+ createViteClientModule() {
424
+ const identifier = CLIENT_ID;
425
+ const cached = this.esm.resolveCachedModule(identifier);
426
+ if (cached)
427
+ return cached;
428
+ const stub = this.options.viteClientModule;
429
+ const moduleKeys = Object.keys(stub);
430
+ const module = new SyntheticModule$1(
431
+ moduleKeys,
432
+ () => {
433
+ moduleKeys.forEach((key) => {
434
+ module.setExport(key, stub[key]);
435
+ });
436
+ },
437
+ { context: this.options.context, identifier }
438
+ );
439
+ this.esm.cacheModule(identifier, module);
440
+ return module;
441
+ }
442
+ canResolve = (fileUrl) => {
443
+ var _a;
444
+ const transformMode = this.workerState.environment.transformMode;
445
+ if (transformMode !== "web")
446
+ return false;
447
+ if (fileUrl === CLIENT_FILE)
448
+ return true;
449
+ const config = ((_a = this.workerState.config.deps) == null ? void 0 : _a.web) || {};
450
+ const [modulePath] = fileUrl.split("?");
451
+ if (config.transformCss && CSS_LANGS_RE.test(modulePath))
452
+ return true;
453
+ if (config.transformAssets && KNOWN_ASSET_RE.test(modulePath))
454
+ return true;
455
+ if (toArray(config.transformGlobPattern).some((pattern) => pattern.test(modulePath)))
456
+ return true;
457
+ return false;
458
+ };
459
+ }
460
+
461
+ const SyntheticModule = vm.SyntheticModule;
462
+ const nativeResolve = import.meta.resolve;
463
+ class ExternalModulesExecutor {
464
+ constructor(options) {
465
+ this.options = options;
466
+ this.context = options.context;
467
+ this.fs = options.fileMap;
468
+ this.esm = new EsmExecutor(this, {
469
+ context: this.context
470
+ });
471
+ this.cjs = new CommonjsExecutor({
472
+ context: this.context,
473
+ importModuleDynamically: this.importModuleDynamically,
474
+ fileMap: options.fileMap
475
+ });
476
+ this.vite = new ViteExecutor({
477
+ esmExecutor: this.esm,
478
+ context: this.context,
479
+ transform: options.transform,
480
+ viteClientModule: options.viteClientModule
481
+ });
482
+ this.resolvers = [this.vite.resolve];
483
+ }
484
+ cjs;
485
+ esm;
486
+ vite;
487
+ context;
488
+ fs;
489
+ resolvers = [];
490
+ // dynamic import can be used in both ESM and CJS, so we have it in the executor
491
+ importModuleDynamically = async (specifier, referencer) => {
492
+ const module = await this.resolveModule(specifier, referencer.identifier);
493
+ return this.esm.evaluateModule(module);
494
+ };
495
+ resolveModule = async (specifier, referencer) => {
496
+ const identifier = await this.resolve(specifier, referencer);
497
+ return await this.createModule(identifier);
498
+ };
499
+ async resolve(specifier, parent) {
500
+ for (const resolver of this.resolvers) {
501
+ const id = resolver(specifier, parent);
502
+ if (id)
503
+ return id;
504
+ }
505
+ return nativeResolve(specifier, parent);
506
+ }
507
+ findNearestPackageData(basedir) {
508
+ var _a;
509
+ const originalBasedir = basedir;
510
+ const packageCache = this.options.packageCache;
511
+ while (basedir) {
512
+ const cached = getCachedData(packageCache, basedir, originalBasedir);
513
+ if (cached)
514
+ return cached;
515
+ const pkgPath = join(basedir, "package.json");
516
+ try {
517
+ if ((_a = statSync(pkgPath, { throwIfNoEntry: false })) == null ? void 0 : _a.isFile()) {
518
+ const pkgData = JSON.parse(this.fs.readFile(pkgPath));
519
+ if (packageCache)
520
+ setCacheData(packageCache, pkgData, basedir, originalBasedir);
521
+ return pkgData;
522
+ }
523
+ } catch {
524
+ }
525
+ const nextBasedir = dirname$1(basedir);
526
+ if (nextBasedir === basedir)
527
+ break;
528
+ basedir = nextBasedir;
529
+ }
530
+ return {};
531
+ }
532
+ wrapCoreSynteticModule(identifier, exports) {
533
+ const moduleKeys = Object.keys(exports);
534
+ const m = new SyntheticModule(
535
+ [...moduleKeys, "default"],
536
+ () => {
537
+ for (const key of moduleKeys)
538
+ m.setExport(key, exports[key]);
539
+ m.setExport("default", exports);
540
+ },
541
+ {
542
+ context: this.context,
543
+ identifier
544
+ }
545
+ );
546
+ return m;
547
+ }
548
+ wrapCommonJsSynteticModule(identifier, exports) {
549
+ const { keys, moduleExports, defaultExport } = interopCommonJsModule(this.options.interopDefault, exports);
550
+ const m = new SyntheticModule(
551
+ [...keys, "default"],
552
+ () => {
553
+ for (const key of keys)
554
+ m.setExport(key, moduleExports[key]);
555
+ m.setExport("default", defaultExport);
556
+ },
557
+ {
558
+ context: this.context,
559
+ identifier
560
+ }
561
+ );
562
+ return m;
563
+ }
564
+ getModuleInformation(identifier) {
565
+ if (identifier.startsWith("data:"))
566
+ return { type: "data", url: identifier, path: identifier };
567
+ const extension = extname(identifier);
568
+ if (extension === ".node" || isNodeBuiltin(identifier))
569
+ return { type: "builtin", url: identifier, path: identifier };
570
+ const isFileUrl = identifier.startsWith("file://");
571
+ const pathUrl = isFileUrl ? fileURLToPath(identifier.split("?")[0]) : identifier;
572
+ const fileUrl = isFileUrl ? identifier : pathToFileURL(pathUrl).toString();
573
+ let type;
574
+ if (this.vite.canResolve(fileUrl)) {
575
+ type = "vite";
576
+ } else if (extension === ".mjs") {
577
+ type = "module";
578
+ } else if (extension === ".cjs") {
579
+ type = "commonjs";
580
+ } else {
581
+ const pkgData = this.findNearestPackageData(normalize(pathUrl));
582
+ type = pkgData.type === "module" ? "module" : "commonjs";
583
+ }
584
+ return { type, path: pathUrl, url: fileUrl };
585
+ }
586
+ async createModule(identifier) {
587
+ const { type, url, path } = this.getModuleInformation(identifier);
588
+ switch (type) {
589
+ case "data":
590
+ return this.esm.createDataModule(identifier);
591
+ case "builtin": {
592
+ const exports = this.require(identifier);
593
+ return this.wrapCoreSynteticModule(identifier, exports);
594
+ }
595
+ case "vite":
596
+ return await this.vite.createViteModule(url);
597
+ case "module":
598
+ return await this.esm.createEsModule(url, this.fs.readFile(path));
599
+ case "commonjs": {
600
+ const exports = this.require(path);
601
+ return this.wrapCommonJsSynteticModule(identifier, exports);
602
+ }
603
+ default: {
604
+ const _deadend = type;
605
+ return _deadend;
606
+ }
607
+ }
608
+ }
609
+ async import(identifier) {
610
+ const module = await this.createModule(identifier);
611
+ await this.esm.evaluateModule(module);
612
+ return module.namespace;
613
+ }
614
+ require(identifier) {
615
+ return this.cjs.require(identifier);
616
+ }
617
+ createRequire(identifier) {
618
+ return this.cjs.createRequire(identifier);
619
+ }
620
+ }
621
+
622
+ class FileMap {
623
+ fsCache = /* @__PURE__ */ new Map();
624
+ fsBufferCache = /* @__PURE__ */ new Map();
625
+ readFile(path) {
626
+ const cached = this.fsCache.get(path);
627
+ if (cached)
628
+ return cached;
629
+ const source = readFileSync(path, "utf-8");
630
+ this.fsCache.set(path, source);
631
+ return source;
632
+ }
633
+ readBuffer(path) {
634
+ const cached = this.fsBufferCache.get(path);
635
+ if (cached)
636
+ return cached;
637
+ const buffer = readFileSync(path);
638
+ this.fsBufferCache.set(path, buffer);
639
+ return buffer;
640
+ }
641
+ }
642
+
643
+ const entryFile = pathToFileURL(resolve(distDir, "workers/runVmTests.js")).href;
644
+ const fileMap = new FileMap();
645
+ const packageCache = /* @__PURE__ */ new Map();
646
+ async function runVmTests(state) {
647
+ var _a;
648
+ const { environment, ctx, rpc } = state;
649
+ if (!environment.setupVM) {
650
+ const envName = ctx.environment.name;
651
+ const packageId = envName[0] === "." ? envName : `vitest-environment-${envName}`;
652
+ throw new TypeError(
653
+ `Environment "${ctx.environment.name}" is not a valid environment. Path "${packageId}" doesn't support vm environment because it doesn't provide "setupVM" method.`
654
+ );
655
+ }
656
+ const vm = await environment.setupVM(ctx.environment.options || ctx.config.environmentOptions || {});
657
+ state.durations.environment = performance.now() - state.durations.environment;
658
+ process.env.VITEST_VM_POOL = "1";
659
+ if (!vm.getVmContext)
660
+ throw new TypeError(`Environment ${environment.name} doesn't provide "getVmContext" method. It should return a context created by "vm.createContext" method.`);
661
+ const context = vm.getVmContext();
662
+ if (!isContext(context))
663
+ throw new TypeError(`Environment ${environment.name} doesn't provide a valid context. It should be created by "vm.createContext" method.`);
664
+ provideWorkerState(context, state);
665
+ context.process = process;
666
+ context.global = context;
667
+ context.console = createCustomConsole(state);
668
+ context.setImmediate = setImmediate;
669
+ context.clearImmediate = clearImmediate;
670
+ const stubs = getDefaultRequestStubs(context);
671
+ const externalModulesExecutor = new ExternalModulesExecutor({
672
+ context,
673
+ fileMap,
674
+ packageCache,
675
+ transform: rpc.transform,
676
+ viteClientModule: stubs["/@vite/client"]
677
+ });
678
+ const executor = await startVitestExecutor({
679
+ context,
680
+ moduleCache: state.moduleCache,
681
+ mockMap: state.mockMap,
682
+ state,
683
+ externalModulesExecutor,
684
+ requestStubs: stubs
685
+ });
686
+ context.__vitest_mocker__ = executor.mocker;
687
+ const { run } = await executor.importExternalModule(entryFile);
688
+ try {
689
+ await run(ctx.files, ctx.config, executor);
690
+ } finally {
691
+ await ((_a = vm.teardown) == null ? void 0 : _a.call(vm));
692
+ state.environmentTeardownRun = true;
693
+ }
694
+ }
695
+
696
+ export { runVmTests as r };