vitest 4.0.0-beta.1 → 4.0.0-beta.10

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 (85) hide show
  1. package/LICENSE.md +2 -2
  2. package/dist/browser.d.ts +13 -14
  3. package/dist/browser.js +6 -5
  4. package/dist/chunks/base.Cjha6usc.js +129 -0
  5. package/dist/chunks/{benchmark.CYdenmiT.js → benchmark.CJUa-Hsa.js} +6 -8
  6. package/dist/chunks/{benchmark.d.BwvBVTda.d.ts → benchmark.d.DAaHLpsq.d.ts} +4 -4
  7. package/dist/chunks/{browser.d.q8Z0P0q1.d.ts → browser.d.yFAklsD1.d.ts} +5 -5
  8. package/dist/chunks/{cac.D3EzDDZd.js → cac.DCxo_nSu.js} +70 -152
  9. package/dist/chunks/{cli-api.Dn5gKePv.js → cli-api.BJJXh9BV.js} +1330 -1677
  10. package/dist/chunks/{config.d.HJdfX-8k.d.ts → config.d.B_LthbQq.d.ts} +58 -63
  11. package/dist/chunks/{console.CtFJOzRO.js → console.7h5kHUIf.js} +34 -70
  12. package/dist/chunks/{constants.DnKduX2e.js → constants.D_Q9UYh-.js} +1 -9
  13. package/dist/chunks/{coverage.Cwa-XhJt.js → coverage.BCU-r2QL.js} +515 -781
  14. package/dist/chunks/{coverage.DVF1vEu8.js → coverage.D_JHT54q.js} +2 -2
  15. package/dist/chunks/{coverage.d.S9RMNXIe.d.ts → coverage.d.BZtK59WP.d.ts} +10 -8
  16. package/dist/chunks/{creator.GK6I-cL4.js → creator.08Gi-vCA.js} +93 -77
  17. package/dist/chunks/{date.Bq6ZW5rf.js → date.-jtEtIeV.js} +6 -17
  18. package/dist/chunks/{environment.d.CUq4cUgQ.d.ts → environment.d.BsToaxti.d.ts} +27 -6
  19. package/dist/chunks/{git.BVQ8w_Sw.js → git.BFNcloKD.js} +1 -2
  20. package/dist/chunks/{global.d.CVbXEflG.d.ts → global.d.BK3X7FW1.d.ts} +2 -5
  21. package/dist/chunks/{globals.Cxal6MLI.js → globals.DG-S3xFe.js} +8 -8
  22. package/dist/chunks/{index.CZI_8rVt.js → index.BIP7prJq.js} +289 -608
  23. package/dist/chunks/{index.B521nVV-.js → index.Bgo3tNWt.js} +23 -4
  24. package/dist/chunks/{index.TfbsX-3I.js → index.BjKEiSn0.js} +14 -24
  25. package/dist/chunks/{index.BWf_gE5n.js → index.CMfqw92x.js} +7 -6
  26. package/dist/chunks/{index.CmSc2RE5.js → index.DIWhzsUh.js} +72 -118
  27. package/dist/chunks/{inspector.C914Efll.js → inspector.CvQD-Nie.js} +10 -25
  28. package/dist/chunks/moduleRunner.d.D9nBoC4p.d.ts +201 -0
  29. package/dist/chunks/moduleTransport.I-bgQy0S.js +19 -0
  30. package/dist/chunks/{node.fjCdwEIl.js → node.CyipiPvJ.js} +1 -1
  31. package/dist/chunks/{plugin.d.C2EcJUjo.d.ts → plugin.d.BMVSnsGV.d.ts} +1 -1
  32. package/dist/chunks/{reporters.d.DxZg19fy.d.ts → reporters.d.BUWjmRYq.d.ts} +1226 -1291
  33. package/dist/chunks/resolveSnapshotEnvironment.Bkht6Yor.js +81 -0
  34. package/dist/chunks/resolver.Bx6lE0iq.js +119 -0
  35. package/dist/chunks/rpc.BKr6mtxz.js +65 -0
  36. package/dist/chunks/{setup-common.D7ZqXFx-.js → setup-common.uiMcU3cv.js} +17 -29
  37. package/dist/chunks/startModuleRunner.p67gbNo9.js +665 -0
  38. package/dist/chunks/{suite.d.FvehnV49.d.ts → suite.d.BJWk38HB.d.ts} +1 -1
  39. package/dist/chunks/test.BiqSKISg.js +214 -0
  40. package/dist/chunks/{typechecker.CVytUJuF.js → typechecker.DB-fIMaH.js} +144 -213
  41. package/dist/chunks/{utils.CAioKnHs.js → utils.C2YI6McM.js} +5 -14
  42. package/dist/chunks/{utils.XdZDrNZV.js → utils.D2R2NiOH.js} +8 -27
  43. package/dist/chunks/{vi.bdSIJ99Y.js → vi.ZPgvtBao.js} +156 -305
  44. package/dist/chunks/{vm.BThCzidc.js → vm.Ca0Y0W5f.js} +116 -226
  45. package/dist/chunks/{worker.d.DoNjFAiv.d.ts → worker.d.BDsXGkwh.d.ts} +28 -22
  46. package/dist/chunks/{worker.d.CmvJfRGs.d.ts → worker.d.BNcX_2mH.d.ts} +1 -1
  47. package/dist/cli.js +4 -4
  48. package/dist/config.cjs +3 -9
  49. package/dist/config.d.ts +49 -54
  50. package/dist/config.js +1 -1
  51. package/dist/coverage.d.ts +27 -26
  52. package/dist/coverage.js +6 -7
  53. package/dist/environments.d.ts +9 -13
  54. package/dist/environments.js +1 -1
  55. package/dist/index.d.ts +38 -45
  56. package/dist/index.js +7 -9
  57. package/dist/module-evaluator.d.ts +13 -0
  58. package/dist/module-evaluator.js +276 -0
  59. package/dist/module-runner.js +15 -0
  60. package/dist/node.d.ts +40 -41
  61. package/dist/node.js +23 -33
  62. package/dist/reporters.d.ts +12 -13
  63. package/dist/reporters.js +3 -3
  64. package/dist/runners.d.ts +3 -3
  65. package/dist/runners.js +13 -232
  66. package/dist/snapshot.js +2 -2
  67. package/dist/suite.d.ts +2 -2
  68. package/dist/suite.js +2 -2
  69. package/dist/worker.js +90 -47
  70. package/dist/workers/forks.js +34 -10
  71. package/dist/workers/runVmTests.js +36 -56
  72. package/dist/workers/threads.js +34 -10
  73. package/dist/workers/vmForks.js +11 -10
  74. package/dist/workers/vmThreads.js +11 -10
  75. package/dist/workers.d.ts +5 -4
  76. package/dist/workers.js +35 -17
  77. package/globals.d.ts +17 -17
  78. package/package.json +32 -31
  79. package/dist/chunks/base.Bj3pWTr1.js +0 -38
  80. package/dist/chunks/execute.B7h3T_Hc.js +0 -708
  81. package/dist/chunks/index.D-VkfKhf.js +0 -105
  82. package/dist/chunks/rpc.CsFtxqeq.js +0 -83
  83. package/dist/chunks/runBaseTests.BC7ZIH5L.js +0 -129
  84. package/dist/execute.d.ts +0 -148
  85. package/dist/execute.js +0 -13
package/dist/index.d.ts CHANGED
@@ -1,28 +1,26 @@
1
- import { S as SerializedTestSpecification } from './chunks/browser.d.q8Z0P0q1.js';
2
- export { B as BrowserTesterOptions } from './chunks/browser.d.q8Z0P0q1.js';
3
- import './chunks/global.d.CVbXEflG.js';
1
+ import { S as SerializedTestSpecification } from './chunks/browser.d.yFAklsD1.js';
2
+ export { B as BrowserTesterOptions } from './chunks/browser.d.yFAklsD1.js';
3
+ import './chunks/global.d.BK3X7FW1.js';
4
4
  import { File, TestAnnotation, TaskResultPack, TaskEventPack, TaskPopulated } from '@vitest/runner';
5
- export { CancelReason, ExtendedContext, HookCleanupCallback, HookListener, ImportDuration, OnTestFailedHandler, OnTestFinishedHandler, RunMode, Custom as RunnerCustomCase, Task as RunnerTask, TaskBase as RunnerTaskBase, TaskEventPack as RunnerTaskEventPack, TaskResult as RunnerTaskResult, TaskResultPack as RunnerTaskResultPack, Test as RunnerTestCase, File as RunnerTestFile, Suite as RunnerTestSuite, SuiteAPI, SuiteCollector, SuiteFactory, TaskContext, TaskCustomOptions, TaskMeta, TaskState, TestAPI, TestAnnotation, TestContext, TestFunction, TestOptions, afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';
6
- import { a as BirpcReturn } from './chunks/worker.d.DoNjFAiv.js';
7
- export { C as ContextRPC, c as ContextTestEnvironment, b as RunnerRPC, R as RuntimeRPC, T as TestExecutionMethod, W as WorkerGlobalState } from './chunks/worker.d.DoNjFAiv.js';
8
- import { a as SerializedConfig, F as FakeTimerInstallOpts, R as RuntimeOptions } from './chunks/config.d.HJdfX-8k.js';
9
- export { b as RuntimeConfig, S as SerializedCoverageConfig } from './chunks/config.d.HJdfX-8k.js';
10
- import { b as Awaitable, U as UserConsoleLog, L as LabelColor, M as ModuleGraphData, P as ProvidedContext } from './chunks/environment.d.CUq4cUgQ.js';
11
- export { A as AfterSuiteRunMeta } from './chunks/environment.d.CUq4cUgQ.js';
5
+ export { CancelReason, HookCleanupCallback, HookListener, ImportDuration, OnTestFailedHandler, OnTestFinishedHandler, RunMode, Task as RunnerTask, TaskBase as RunnerTaskBase, TaskEventPack as RunnerTaskEventPack, TaskResult as RunnerTaskResult, TaskResultPack as RunnerTaskResultPack, Test as RunnerTestCase, File as RunnerTestFile, Suite as RunnerTestSuite, SuiteAPI, SuiteCollector, SuiteFactory, TaskCustomOptions, TaskMeta, TaskState, TestAPI, TestAnnotation, TestContext, TestFunction, TestOptions, afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';
6
+ import { a as BirpcReturn } from './chunks/worker.d.BDsXGkwh.js';
7
+ export { C as ContextRPC, c as ContextTestEnvironment, b as RunnerRPC, R as RuntimeRPC, T as TestExecutionMethod, W as WorkerGlobalState } from './chunks/worker.d.BDsXGkwh.js';
8
+ import { a as SerializedConfig, F as FakeTimerInstallOpts, R as RuntimeOptions } from './chunks/config.d.B_LthbQq.js';
9
+ export { b as RuntimeConfig, S as SerializedCoverageConfig } from './chunks/config.d.B_LthbQq.js';
10
+ import { b as Awaitable, U as UserConsoleLog, L as LabelColor, M as ModuleGraphData, P as ProvidedContext } from './chunks/environment.d.BsToaxti.js';
11
+ export { A as AfterSuiteRunMeta } from './chunks/environment.d.BsToaxti.js';
12
12
  import { ExpectStatic } from '@vitest/expect';
13
- export { Assertion, AsymmetricMatchersContaining, DeeplyAllowMatchers, ExpectPollOptions, ExpectStatic, JestAssertion, Matchers } from '@vitest/expect';
13
+ export { Assertion, AsymmetricMatchersContaining, DeeplyAllowMatchers, ExpectPollOptions, ExpectStatic, JestAssertion, Matchers, chai } from '@vitest/expect';
14
14
  import { spyOn, fn, MaybeMockedDeep, MaybeMocked, MaybePartiallyMocked, MaybePartiallyMockedDeep, MockInstance } from '@vitest/spy';
15
15
  export { Mock, MockContext, MockInstance, Mocked, MockedClass, MockedFunction, MockedObject } from '@vitest/spy';
16
16
  import { M as MockFactoryWithHelper, a as MockOptions } from './chunks/mocker.d.BE_2ls6u.js';
17
- export { b as bench } from './chunks/suite.d.FvehnV49.js';
18
- export { a as BenchFunction, b as Benchmark, c as BenchmarkAPI, B as BenchmarkResult } from './chunks/benchmark.d.BwvBVTda.js';
17
+ export { b as bench } from './chunks/suite.d.BJWk38HB.js';
18
+ export { a as BenchFunction, b as Benchmark, c as BenchmarkAPI, B as BenchmarkResult } from './chunks/benchmark.d.DAaHLpsq.js';
19
19
  export { ExpectTypeOf, expectTypeOf } from 'expect-type';
20
20
  export { SnapshotData, SnapshotMatchOptions, SnapshotResult, SnapshotSerializer, SnapshotStateOptions, SnapshotSummary, SnapshotUpdateState, UncheckedSnapshot } from '@vitest/snapshot';
21
21
  export { ParsedStack, SerializedError, TestError } from '@vitest/utils';
22
22
  export { DiffOptions } from '@vitest/utils/diff';
23
- import * as chai from 'chai';
24
- export { chai };
25
- export { assert, should } from 'chai';
23
+ export { EvaluatedModules } from 'vite/module-runner';
26
24
  export { Bench as BenchFactory, Options as BenchOptions, Task as BenchTask, TaskResult as BenchTaskResult } from 'tinybench';
27
25
  import '@vitest/pretty-format';
28
26
  import '@vitest/mocker';
@@ -41,7 +39,7 @@ interface SourceMap {
41
39
  interface TransformResultWithSource {
42
40
  code: string;
43
41
  map: SourceMap | {
44
- mappings: ""
42
+ mappings: "";
45
43
  } | null;
46
44
  etag?: string;
47
45
  deps?: string[];
@@ -54,12 +52,9 @@ interface WebSocketHandlers {
54
52
  getTestFiles: () => Promise<SerializedTestSpecification[]>;
55
53
  getPaths: () => string[];
56
54
  getConfig: () => SerializedConfig;
57
- // TODO: Remove in v4
58
- /** @deprecated -- Use `getResolvedProjectLabels` instead */
59
- getResolvedProjectNames: () => string[];
60
55
  getResolvedProjectLabels: () => {
61
- name: string
62
- color?: LabelColor
56
+ name: string;
57
+ color?: LabelColor;
63
58
  }[];
64
59
  getModuleGraph: (projectName: string, id: string, browser?: boolean) => Promise<ModuleGraphData>;
65
60
  getTransformResult: (projectName: string, id: string, browser?: boolean) => Promise<TransformResultWithSource | undefined>;
@@ -84,6 +79,8 @@ type WebSocketRPC = BirpcReturn<WebSocketEvents, WebSocketHandlers>;
84
79
 
85
80
  declare function createExpect(test?: TaskPopulated): ExpectStatic;
86
81
  declare const globalExpect: ExpectStatic;
82
+ declare const assert: Chai.Assert;
83
+ declare const should: () => Chai.Should;
87
84
 
88
85
  /**
89
86
  * Gives access to injected context provided from the main thread.
@@ -91,7 +88,6 @@ declare const globalExpect: ExpectStatic;
91
88
  */
92
89
  declare function inject<T extends keyof ProvidedContext & string>(key: T): ProvidedContext[T];
93
90
 
94
- // The waitFor function was inspired by https://github.com/testing-library/web-testing-library/pull/2
95
91
  type WaitForCallback<T> = () => T | Promise<T>;
96
92
  interface WaitForOptions {
97
93
  /**
@@ -280,13 +276,11 @@ interface VitestUtils {
280
276
  * The call to `vi.mock` is hoisted to the top of the file, so you don't have access to variables declared in the global file scope
281
277
  * unless they are defined with [`vi.hoisted`](https://vitest.dev/api/vi#vi-hoisted) before this call.
282
278
  *
283
- * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
279
+ * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
284
280
  * @param path Path to the module. Can be aliased, if your Vitest config supports it
285
281
  * @param factory Mocked module factory. The result of this function will be an exports object
286
282
  */
287
- // eslint-disable-next-line ts/method-signature-style
288
283
  mock(path: string, factory?: MockFactoryWithHelper | MockOptions): void;
289
- // eslint-disable-next-line ts/method-signature-style
290
284
  mock<T>(module: Promise<T>, factory?: MockFactoryWithHelper<T> | MockOptions): void;
291
285
  /**
292
286
  * Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.
@@ -294,22 +288,18 @@ interface VitestUtils {
294
288
  * This call is hoisted to the top of the file, so it will only unmock modules that were defined in `setupFiles`, for example.
295
289
  * @param path Path to the module. Can be aliased, if your Vitest config supports it
296
290
  */
297
- // eslint-disable-next-line ts/method-signature-style
298
291
  unmock(path: string): void;
299
- // eslint-disable-next-line ts/method-signature-style
300
292
  unmock(module: Promise<unknown>): void;
301
293
  /**
302
294
  * Mocks every subsequent [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) call.
303
295
  *
304
296
  * Unlike [`vi.mock`](https://vitest.dev/api/vi#vi-mock), this method will not mock statically imported modules because it is not hoisted to the top of the file.
305
297
  *
306
- * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
298
+ * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
307
299
  * @param path Path to the module. Can be aliased, if your Vitest config supports it
308
300
  * @param factory Mocked module factory. The result of this function will be an exports object
309
301
  */
310
- // eslint-disable-next-line ts/method-signature-style
311
302
  doMock(path: string, factory?: MockFactoryWithHelper | MockOptions): void;
312
- // eslint-disable-next-line ts/method-signature-style
313
303
  doMock<T>(module: Promise<T>, factory?: MockFactoryWithHelper<T> | MockOptions): void;
314
304
  /**
315
305
  * Removes module from mocked registry. All subsequent calls to import will return original module.
@@ -317,9 +307,7 @@ interface VitestUtils {
317
307
  * Unlike [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock), this method is not hoisted to the top of the file.
318
308
  * @param path Path to the module. Can be aliased, if your Vitest config supports it
319
309
  */
320
- // eslint-disable-next-line ts/method-signature-style
321
310
  doUnmock(path: string): void;
322
- // eslint-disable-next-line ts/method-signature-style
323
311
  doUnmock(module: Promise<unknown>): void;
324
312
  /**
325
313
  * Imports module, bypassing all checks if it should be mocked.
@@ -338,7 +326,7 @@ interface VitestUtils {
338
326
  /**
339
327
  * Imports a module with all of its properties and nested properties mocked.
340
328
  *
341
- * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking#modules).
329
+ * Mocking algorithm is described in [documentation](https://vitest.dev/guide/mocking/modules).
342
330
  * @example
343
331
  * ```ts
344
332
  * const example = await vi.importMock<typeof import('./example.js')>('./example.js')
@@ -373,12 +361,17 @@ interface VitestUtils {
373
361
  *
374
362
  * expect(mocked.simple()).toBe('mocked')
375
363
  * expect(mocked.nested.method()).toBe('mocked nested')
364
+ *
365
+ * const spied = vi.mockObject(original, { spy: true })
366
+ * expect(spied.simple()).toBe('value')
367
+ * expect(spied.simple).toHaveBeenCalled()
368
+ * expect(spied.simple.mock.results[0]).toEqual({ type: 'return', value: 'value' })
376
369
  * ```
377
370
  *
378
371
  * @param value - The object to be mocked
379
372
  * @returns A deeply mocked version of the input object
380
373
  */
381
- mockObject: <T>(value: T) => MaybeMockedDeep<T>;
374
+ mockObject: <T>(value: T, options?: MockOptions) => MaybeMockedDeep<T>;
382
375
  /**
383
376
  * Type helper for TypeScript. Just returns the object that was passed.
384
377
  *
@@ -399,17 +392,17 @@ interface VitestUtils {
399
392
  * @param options If the object is partially or deeply mocked
400
393
  */
401
394
  mocked: (<T>(item: T, deep?: false) => MaybeMocked<T>) & (<T>(item: T, deep: true) => MaybeMockedDeep<T>) & (<T>(item: T, options: {
402
- partial?: false
403
- deep?: false
395
+ partial?: false;
396
+ deep?: false;
404
397
  }) => MaybeMocked<T>) & (<T>(item: T, options: {
405
- partial?: false
406
- deep: true
398
+ partial?: false;
399
+ deep: true;
407
400
  }) => MaybeMockedDeep<T>) & (<T>(item: T, options: {
408
- partial: true
409
- deep?: false
401
+ partial: true;
402
+ deep?: false;
410
403
  }) => MaybePartiallyMocked<T>) & (<T>(item: T, options: {
411
- partial: true
412
- deep: true
404
+ partial: true;
405
+ deep: true;
413
406
  }) => MaybePartiallyMockedDeep<T>) & (<T>(item: T) => MaybeMocked<T>);
414
407
  /**
415
408
  * Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.
@@ -476,7 +469,7 @@ interface VitestUtils {
476
469
  */
477
470
  setConfig: (config: RuntimeOptions) => void;
478
471
  /**
479
- * If config was changed with `vi.setConfig`, this will reset it to the original state.
472
+ * If config was changed with `vi.setConfig`, this will reset it to the original state().
480
473
  */
481
474
  resetConfig: () => void;
482
475
  }
@@ -493,5 +486,5 @@ interface BrowserUI {
493
486
  setIframeViewport: (width: number, height: number) => Promise<void>;
494
487
  }
495
488
 
496
- export { LabelColor, ModuleGraphData, ProvidedContext, SerializedConfig, SerializedTestSpecification, UserConsoleLog, assertType, createExpect, globalExpect as expect, inject, vi, vitest };
489
+ export { LabelColor, ModuleGraphData, ProvidedContext, SerializedConfig, SerializedTestSpecification, UserConsoleLog, assert, assertType, createExpect, globalExpect as expect, inject, should, vi, vitest };
497
490
  export type { AssertType, BrowserUI, TransformResultWithSource, VitestUtils, WebSocketEvents, WebSocketHandlers, WebSocketRPC };
package/dist/index.js CHANGED
@@ -1,18 +1,16 @@
1
- export { c as createExpect, a as expect, i as inject, v as vi, b as vitest } from './chunks/vi.bdSIJ99Y.js';
2
- export { b as bench } from './chunks/benchmark.CYdenmiT.js';
3
- export { a as assertType } from './chunks/index.BWf_gE5n.js';
1
+ export { b as assert, c as createExpect, g as expect, i as inject, s as should, v as vi, d as vitest } from './chunks/vi.ZPgvtBao.js';
2
+ export { b as bench } from './chunks/benchmark.CJUa-Hsa.js';
3
+ export { a as assertType } from './chunks/index.CMfqw92x.js';
4
4
  export { expectTypeOf } from 'expect-type';
5
5
  export { afterAll, afterEach, beforeAll, beforeEach, describe, it, onTestFailed, onTestFinished, suite, test } from '@vitest/runner';
6
- import * as chai from 'chai';
7
- export { chai };
8
- export { assert, should } from 'chai';
9
- import '@vitest/expect';
6
+ export { EvaluatedModules } from 'vite/module-runner';
7
+ export { chai } from '@vitest/expect';
10
8
  import '@vitest/runner/utils';
11
- import './chunks/utils.XdZDrNZV.js';
9
+ import './chunks/utils.D2R2NiOH.js';
12
10
  import '@vitest/utils';
13
11
  import './chunks/_commonjsHelpers.BFTU3MAI.js';
14
12
  import '@vitest/snapshot';
15
13
  import '@vitest/utils/error';
16
14
  import '@vitest/spy';
17
15
  import '@vitest/utils/source-map';
18
- import './chunks/date.Bq6ZW5rf.js';
16
+ import './chunks/date.-jtEtIeV.js';
@@ -0,0 +1,13 @@
1
+ import 'vite/module-runner';
2
+ export { b as VitestModuleEvaluator, a as VitestModuleEvaluatorOptions, c as createImportMetaEnvProxy, g as getDefaultRequestStubs, i as isPrimitive, u as unwrapId, w as wrapId } from './chunks/moduleRunner.d.D9nBoC4p.js';
3
+ import 'node:vm';
4
+ import '@vitest/spy';
5
+ import './chunks/worker.d.BDsXGkwh.js';
6
+ import '@vitest/runner';
7
+ import './chunks/config.d.B_LthbQq.js';
8
+ import '@vitest/pretty-format';
9
+ import '@vitest/snapshot';
10
+ import '@vitest/utils/diff';
11
+ import './chunks/environment.d.BsToaxti.js';
12
+ import '@vitest/mocker';
13
+ import './chunks/mocker.d.BE_2ls6u.js';
@@ -0,0 +1,276 @@
1
+ import { isBuiltin, createRequire } from 'node:module';
2
+ import { pathToFileURL } from 'node:url';
3
+ import vm from 'node:vm';
4
+ import { isAbsolute } from 'pathe';
5
+ import { ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey } from 'vite/module-runner';
6
+
7
+ const performanceNow = performance.now.bind(performance);
8
+ class ModuleDebug {
9
+ executionStack = [];
10
+ startCalculateModuleExecutionInfo(filename, startOffset) {
11
+ const startTime = performanceNow();
12
+ return this.executionStack.push({
13
+ filename,
14
+ startTime,
15
+ subImportTime: 0
16
+ }), () => {
17
+ const duration = performanceNow() - startTime, currentExecution = this.executionStack.pop();
18
+ if (currentExecution == null) throw new Error("Execution stack is empty, this should never happen");
19
+ const selfTime = duration - currentExecution.subImportTime;
20
+ if (this.executionStack.length > 0) this.executionStack.at(-1).subImportTime += duration;
21
+ return {
22
+ startOffset,
23
+ duration,
24
+ selfTime
25
+ };
26
+ };
27
+ }
28
+ }
29
+
30
+ const isWindows = process.platform === "win32";
31
+ class VitestModuleEvaluator {
32
+ stubs = {};
33
+ env = createImportMetaEnvProxy();
34
+ vm;
35
+ compiledFunctionArgumentsNames;
36
+ compiledFunctionArgumentsValues = [];
37
+ primitives;
38
+ debug = new ModuleDebug();
39
+ constructor(vmOptions, options = {}) {
40
+ if (this.options = options, this.vm = vmOptions, this.stubs = getDefaultRequestStubs(vmOptions?.context), options.compiledFunctionArgumentsNames) this.compiledFunctionArgumentsNames = options.compiledFunctionArgumentsNames;
41
+ if (options.compiledFunctionArgumentsValues) this.compiledFunctionArgumentsValues = options.compiledFunctionArgumentsValues;
42
+ if (vmOptions) this.primitives = vm.runInContext("({ Object, Proxy, Reflect })", vmOptions.context);
43
+ else this.primitives = {
44
+ Object,
45
+ Proxy,
46
+ Reflect
47
+ };
48
+ }
49
+ convertIdToImportUrl(id) {
50
+ // TODO: vitest returns paths for external modules, but Vite returns file://
51
+ // unfortunetly, there is a bug in Vite where ID is resolved incorrectly, so we can't return files until the fix is merged
52
+ // https://github.com/vitejs/vite/pull/20449
53
+ if (!isWindows || isBuiltin(id) || /^(?:node:|data:|http:|https:|file:)/.test(id)) return id;
54
+ const [filepath, query] = id.split("?");
55
+ return query ? `${pathToFileURL(filepath).toString()}?${query}` : pathToFileURL(filepath).toString();
56
+ }
57
+ async runExternalModule(id) {
58
+ if (id in this.stubs) return this.stubs[id];
59
+ const file = this.convertIdToImportUrl(id), namespace = this.vm ? await this.vm.externalModulesExecutor.import(file) : await import(file);
60
+ if (!this.shouldInterop(file, namespace)) return namespace;
61
+ const { mod, defaultExport } = interopModule(namespace), { Proxy, Reflect } = this.primitives, proxy = new Proxy(mod, {
62
+ get(mod, prop) {
63
+ return prop === "default" ? defaultExport : mod[prop] ?? defaultExport?.[prop];
64
+ },
65
+ has(mod, prop) {
66
+ return prop === "default" ? defaultExport !== void 0 : prop in mod || defaultExport && prop in defaultExport;
67
+ },
68
+ getOwnPropertyDescriptor(mod, prop) {
69
+ const descriptor = Reflect.getOwnPropertyDescriptor(mod, prop);
70
+ if (descriptor) return descriptor;
71
+ if (prop === "default" && defaultExport !== void 0) return {
72
+ value: defaultExport,
73
+ enumerable: true,
74
+ configurable: true
75
+ };
76
+ }
77
+ });
78
+ return proxy;
79
+ }
80
+ async runInlinedModule(context, code, module) {
81
+ context.__vite_ssr_import_meta__.env = this.env;
82
+ const { Reflect, Proxy, Object } = this.primitives, exportsObject = context[ssrModuleExportsKey], SYMBOL_NOT_DEFINED = Symbol("not defined");
83
+ let moduleExports = SYMBOL_NOT_DEFINED;
84
+ // this proxy is triggered only on exports.{name} and module.exports access
85
+ // inside the module itself. imported module is always "exports"
86
+ const cjsExports = new Proxy(exportsObject, {
87
+ get: (target, p, receiver) => {
88
+ return Reflect.has(target, p) ? Reflect.get(target, p, receiver) : Reflect.get(Object.prototype, p, receiver);
89
+ },
90
+ getPrototypeOf: () => Object.prototype,
91
+ set: (_, p, value) => {
92
+ // treat "module.exports =" the same as "exports.default =" to not have nested "default.default",
93
+ // so "exports.default" becomes the actual module
94
+ if (p === "default" && this.shouldInterop(module.file, { default: value }) && cjsExports !== value) return exportAll(cjsExports, value), exportsObject.default = value, true;
95
+ if (!Reflect.has(exportsObject, "default")) exportsObject.default = {};
96
+ // returns undefined, when accessing named exports, if default is not an object
97
+ // but is still present inside hasOwnKeys, this is Node behaviour for CJS
98
+ if (moduleExports !== SYMBOL_NOT_DEFINED && isPrimitive(moduleExports)) return defineExport(exportsObject, p, () => void 0), true;
99
+ if (!isPrimitive(exportsObject.default)) exportsObject.default[p] = value;
100
+ if (p !== "default") defineExport(exportsObject, p, () => value);
101
+ return true;
102
+ }
103
+ }), moduleProxy = {
104
+ set exports(value) {
105
+ exportAll(cjsExports, value), exportsObject.default = value, moduleExports = value;
106
+ },
107
+ get exports() {
108
+ return cjsExports;
109
+ }
110
+ }, meta = context[ssrImportMetaKey], testFilepath = this.options.getCurrentTestFilepath?.();
111
+ if (testFilepath === module.file) {
112
+ const globalNamespace = this.vm?.context || globalThis;
113
+ Object.defineProperty(meta, "vitest", { get: () => globalNamespace.__vitest_index__ });
114
+ }
115
+ const filename = meta.filename, dirname = meta.dirname, require = this.createRequire(filename), argumentsList = [
116
+ ssrModuleExportsKey,
117
+ ssrImportMetaKey,
118
+ ssrImportKey,
119
+ ssrDynamicImportKey,
120
+ ssrExportAllKey,
121
+ "__vite_ssr_exportName__",
122
+ "__filename",
123
+ "__dirname",
124
+ "module",
125
+ "exports",
126
+ "require"
127
+ ];
128
+ if (this.compiledFunctionArgumentsNames) argumentsList.push(...this.compiledFunctionArgumentsNames);
129
+ // add 'use strict' since ESM enables it by default
130
+ const codeDefinition = `'use strict';async (${argumentsList.join(",")})=>{{`, wrappedCode = `${codeDefinition}${code}\n}}`, options = {
131
+ filename: module.id,
132
+ lineOffset: 0,
133
+ columnOffset: -codeDefinition.length
134
+ }, finishModuleExecutionInfo = this.debug.startCalculateModuleExecutionInfo(options.filename, codeDefinition.length);
135
+ try {
136
+ const initModule = this.vm ? vm.runInContext(wrappedCode, this.vm.context, options) : vm.runInThisContext(wrappedCode, options), dynamicRequest = async (dep, options) => {
137
+ return dep = String(dep), dep[0] === "#" ? context[ssrDynamicImportKey](wrapId(dep), options) : context[ssrDynamicImportKey](dep, options);
138
+ };
139
+ await initModule(
140
+ context[ssrModuleExportsKey],
141
+ context[ssrImportMetaKey],
142
+ context[ssrImportKey],
143
+ dynamicRequest,
144
+ context[ssrExportAllKey],
145
+ // vite 7 support, remove when vite 7+ is supported
146
+ context.__vite_ssr_exportName__ || ((name, getter) => Object.defineProperty(exportsObject, name, {
147
+ enumerable: true,
148
+ configurable: true,
149
+ get: getter
150
+ })),
151
+ filename,
152
+ dirname,
153
+ moduleProxy,
154
+ cjsExports,
155
+ require,
156
+ ...this.compiledFunctionArgumentsValues
157
+ );
158
+ } finally {
159
+ // moduleExecutionInfo needs to use Node filename instead of the normalized one
160
+ // because we rely on this behaviour in coverage-v8, for example
161
+ this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo());
162
+ }
163
+ }
164
+ createRequire(filename) {
165
+ return filename.startsWith("\0") || !isAbsolute(filename) ? () => ({}) : this.vm ? this.vm.externalModulesExecutor.createRequire(filename) : createRequire(filename);
166
+ }
167
+ shouldInterop(path, mod) {
168
+ // never interop ESM modules
169
+ // TODO: should also skip for `.js` with `type="module"`
170
+ return this.options.interopDefault === false ? false : !path.endsWith(".mjs") && "default" in mod;
171
+ }
172
+ }
173
+ function createImportMetaEnvProxy() {
174
+ // packages/vitest/src/node/plugins/index.ts:146
175
+ const booleanKeys = [
176
+ "DEV",
177
+ "PROD",
178
+ "SSR"
179
+ ];
180
+ return new Proxy(process.env, {
181
+ get(_, key) {
182
+ return typeof key === "string" ? booleanKeys.includes(key) ? !!process.env[key] : process.env[key] : void 0;
183
+ },
184
+ set(_, key, value) {
185
+ if (typeof key !== "string") return true;
186
+ if (booleanKeys.includes(key)) process.env[key] = value ? "1" : "";
187
+ else process.env[key] = value;
188
+ return true;
189
+ }
190
+ });
191
+ }
192
+ function updateStyle(id, css) {
193
+ if (typeof document === "undefined") return;
194
+ const element = document.querySelector(`[data-vite-dev-id="${id}"]`);
195
+ if (element) {
196
+ element.textContent = css;
197
+ return;
198
+ }
199
+ const head = document.querySelector("head"), style = document.createElement("style");
200
+ style.setAttribute("type", "text/css"), style.setAttribute("data-vite-dev-id", id), style.textContent = css, head?.appendChild(style);
201
+ }
202
+ function removeStyle(id) {
203
+ if (typeof document === "undefined") return;
204
+ const sheet = document.querySelector(`[data-vite-dev-id="${id}"]`);
205
+ if (sheet) document.head.removeChild(sheet);
206
+ }
207
+ const defaultClientStub = {
208
+ injectQuery: (id) => id,
209
+ createHotContext: () => {
210
+ return {
211
+ accept: () => {},
212
+ prune: () => {},
213
+ dispose: () => {},
214
+ decline: () => {},
215
+ invalidate: () => {},
216
+ on: () => {},
217
+ send: () => {}
218
+ };
219
+ },
220
+ updateStyle: () => {},
221
+ removeStyle: () => {}
222
+ };
223
+ function getDefaultRequestStubs(context) {
224
+ if (!context) {
225
+ const clientStub = {
226
+ ...defaultClientStub,
227
+ updateStyle,
228
+ removeStyle
229
+ };
230
+ return { "/@vite/client": clientStub };
231
+ }
232
+ const clientStub = vm.runInContext(`(defaultClient) => ({ ...defaultClient, updateStyle: ${updateStyle.toString()}, removeStyle: ${removeStyle.toString()} })`, context)(defaultClientStub);
233
+ return { "/@vite/client": clientStub };
234
+ }
235
+ function exportAll(exports, sourceModule) {
236
+ if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
237
+ for (const key in sourceModule) if (key !== "default" && !(key in exports)) try {
238
+ defineExport(exports, key, () => sourceModule[key]);
239
+ } catch {}
240
+ }
241
+ }
242
+ // keep consistency with Vite on how exports are defined
243
+ function defineExport(exports, key, value) {
244
+ Object.defineProperty(exports, key, {
245
+ enumerable: true,
246
+ configurable: true,
247
+ get: value
248
+ });
249
+ }
250
+ function isPrimitive(v) {
251
+ const isObject = typeof v === "object" || typeof v === "function";
252
+ return !isObject || v == null;
253
+ }
254
+ function interopModule(mod) {
255
+ if (isPrimitive(mod)) return {
256
+ mod: { default: mod },
257
+ defaultExport: mod
258
+ };
259
+ let defaultExport = "default" in mod ? mod.default : mod;
260
+ if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
261
+ if (mod = defaultExport, "default" in defaultExport) defaultExport = defaultExport.default;
262
+ }
263
+ return {
264
+ mod,
265
+ defaultExport
266
+ };
267
+ }
268
+ const VALID_ID_PREFIX = `/@id/`, NULL_BYTE_PLACEHOLDER = `__x00__`;
269
+ function wrapId(id) {
270
+ return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
271
+ }
272
+ function unwrapId(id) {
273
+ return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
274
+ }
275
+
276
+ export { VitestModuleEvaluator, createImportMetaEnvProxy, getDefaultRequestStubs, isPrimitive, unwrapId, wrapId };
@@ -0,0 +1,15 @@
1
+ export { VitestModuleEvaluator } from './module-evaluator.js';
2
+ export { a as VITEST_VM_CONTEXT_SYMBOL, V as VitestModuleRunner, s as startVitestModuleRunner } from './chunks/startModuleRunner.p67gbNo9.js';
3
+ export { g as getWorkerState } from './chunks/utils.D2R2NiOH.js';
4
+ import 'node:module';
5
+ import 'node:url';
6
+ import 'node:vm';
7
+ import 'pathe';
8
+ import 'vite/module-runner';
9
+ import 'node:fs';
10
+ import '@vitest/utils';
11
+ import './path.js';
12
+ import 'node:path';
13
+ import '@vitest/utils/error';
14
+ import '@vitest/mocker';
15
+ import './chunks/moduleTransport.I-bgQy0S.js';