vitest 4.0.0-beta.1 → 4.0.0-beta.11

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 (90) hide show
  1. package/LICENSE.md +83 -2
  2. package/dist/browser.d.ts +19 -16
  3. package/dist/browser.js +11 -7
  4. package/dist/chunks/{benchmark.CYdenmiT.js → benchmark.LXhJ0F0X.js} +7 -9
  5. package/dist/chunks/{benchmark.d.BwvBVTda.d.ts → benchmark.d.DAaHLpsq.d.ts} +4 -4
  6. package/dist/chunks/{browser.d.q8Z0P0q1.d.ts → browser.d.Dx7DO_Ce.d.ts} +5 -5
  7. package/dist/chunks/{cac.D3EzDDZd.js → cac.elvK37c9.js} +71 -153
  8. package/dist/chunks/{cli-api.Dn5gKePv.js → cli-api.C7plPyhs.js} +1376 -1693
  9. package/dist/chunks/{config.d.HJdfX-8k.d.ts → config.d.B_LthbQq.d.ts} +58 -63
  10. package/dist/chunks/{console.CtFJOzRO.js → console.CiTi59Jy.js} +35 -71
  11. package/dist/chunks/{constants.DnKduX2e.js → constants.D_Q9UYh-.js} +1 -9
  12. package/dist/chunks/{coverage.Cwa-XhJt.js → coverage.CG6Uhorw.js} +522 -792
  13. package/dist/chunks/{coverage.DVF1vEu8.js → coverage.D_JHT54q.js} +2 -2
  14. package/dist/chunks/{coverage.d.S9RMNXIe.d.ts → coverage.d.BZtK59WP.d.ts} +10 -8
  15. package/dist/chunks/{creator.GK6I-cL4.js → creator.08Gi-vCA.js} +93 -77
  16. package/dist/chunks/{date.Bq6ZW5rf.js → date.-jtEtIeV.js} +6 -17
  17. package/dist/chunks/{environment.d.CUq4cUgQ.d.ts → environment.d.BsToaxti.d.ts} +27 -6
  18. package/dist/chunks/{git.BVQ8w_Sw.js → git.BFNcloKD.js} +1 -2
  19. package/dist/chunks/{global.d.CVbXEflG.d.ts → global.d.BK3X7FW1.d.ts} +2 -5
  20. package/dist/chunks/{globals.Cxal6MLI.js → globals.BjvYA-AD.js} +11 -9
  21. package/dist/chunks/{index.BWf_gE5n.js → index.AZOjjqWP.js} +7 -6
  22. package/dist/chunks/{index.B521nVV-.js → index.Bgo3tNWt.js} +23 -4
  23. package/dist/chunks/{index.TfbsX-3I.js → index.BhY64fF0.js} +16 -26
  24. package/dist/chunks/{index.CZI_8rVt.js → index.BwBttQPf.js} +340 -663
  25. package/dist/chunks/{index.CmSc2RE5.js → index.DIWhzsUh.js} +72 -118
  26. package/dist/chunks/{inspector.C914Efll.js → inspector.CvQD-Nie.js} +10 -25
  27. package/dist/chunks/moduleRunner.d.BNa-CL9e.d.ts +201 -0
  28. package/dist/chunks/{node.fjCdwEIl.js → node.BsdMi6DV.js} +2 -2
  29. package/dist/chunks/{plugin.d.C2EcJUjo.d.ts → plugin.d.C5phQR6o.d.ts} +1 -1
  30. package/dist/chunks/{reporters.d.DxZg19fy.d.ts → reporters.d.CVzhsTvK.d.ts} +1233 -1293
  31. package/dist/chunks/resolveSnapshotEnvironment.DQVamkje.js +81 -0
  32. package/dist/chunks/rpc.jKGRSXIH.js +65 -0
  33. package/dist/chunks/{setup-common.D7ZqXFx-.js → setup-common.NAWRuMRP.js} +18 -30
  34. package/dist/chunks/startModuleRunner.oAuCu1yL.js +682 -0
  35. package/dist/chunks/{suite.d.FvehnV49.d.ts → suite.d.BJWk38HB.d.ts} +1 -1
  36. package/dist/chunks/test.KC5tH8hC.js +214 -0
  37. package/dist/chunks/typechecker.gXq-5P3n.js +1438 -0
  38. package/dist/chunks/{utils.XdZDrNZV.js → utils.DGKhod2J.js} +9 -28
  39. package/dist/chunks/{vi.bdSIJ99Y.js → vi.CiJ0Laa6.js} +159 -306
  40. package/dist/chunks/worker.d.B_Fd9M_w.d.ts +100 -0
  41. package/dist/chunks/worker.rPGLlbkW.js +200 -0
  42. package/dist/cli.js +8 -6
  43. package/dist/config.cjs +3 -9
  44. package/dist/config.d.ts +49 -54
  45. package/dist/config.js +1 -1
  46. package/dist/coverage.d.ts +27 -26
  47. package/dist/coverage.js +6 -8
  48. package/dist/environments.d.ts +9 -13
  49. package/dist/environments.js +1 -1
  50. package/dist/index.d.ts +38 -45
  51. package/dist/index.js +10 -10
  52. package/dist/module-evaluator.d.ts +13 -0
  53. package/dist/module-evaluator.js +276 -0
  54. package/dist/module-runner.js +15 -0
  55. package/dist/node.d.ts +44 -42
  56. package/dist/node.js +30 -36
  57. package/dist/reporters.d.ts +12 -13
  58. package/dist/reporters.js +7 -5
  59. package/dist/runners.d.ts +3 -3
  60. package/dist/runners.js +15 -232
  61. package/dist/snapshot.js +3 -3
  62. package/dist/suite.d.ts +2 -2
  63. package/dist/suite.js +4 -3
  64. package/dist/worker-base.js +203 -0
  65. package/dist/{chunks/vm.BThCzidc.js → worker-vm.js} +179 -228
  66. package/dist/workers/runVmTests.js +39 -56
  67. package/globals.d.ts +17 -17
  68. package/package.json +40 -38
  69. package/browser.d.ts +0 -1
  70. package/dist/chunks/base.Bj3pWTr1.js +0 -38
  71. package/dist/chunks/execute.B7h3T_Hc.js +0 -708
  72. package/dist/chunks/index.D-VkfKhf.js +0 -105
  73. package/dist/chunks/rpc.CsFtxqeq.js +0 -83
  74. package/dist/chunks/runBaseTests.BC7ZIH5L.js +0 -129
  75. package/dist/chunks/typechecker.CVytUJuF.js +0 -874
  76. package/dist/chunks/utils.CAioKnHs.js +0 -61
  77. package/dist/chunks/worker.d.CmvJfRGs.d.ts +0 -8
  78. package/dist/chunks/worker.d.DoNjFAiv.d.ts +0 -169
  79. package/dist/execute.d.ts +0 -148
  80. package/dist/execute.js +0 -13
  81. package/dist/worker.js +0 -124
  82. package/dist/workers/forks.js +0 -43
  83. package/dist/workers/threads.js +0 -31
  84. package/dist/workers/vmForks.js +0 -47
  85. package/dist/workers/vmThreads.js +0 -37
  86. package/dist/workers.d.ts +0 -37
  87. package/dist/workers.js +0 -30
  88. package/execute.d.ts +0 -1
  89. package/utils.d.ts +0 -1
  90. package/workers.d.ts +0 -1
@@ -1,61 +0,0 @@
1
- import { parseRegexp } from '@vitest/utils';
2
-
3
- const REGEXP_WRAP_PREFIX = "$$vitest:";
4
- // Store global APIs in case process is overwritten by tests
5
- const processSend = process.send?.bind(process);
6
- const processOn = process.on?.bind(process);
7
- const processOff = process.off?.bind(process);
8
- const dispose = [];
9
- function createThreadsRpcOptions({ port }) {
10
- return {
11
- post: (v) => {
12
- port.postMessage(v);
13
- },
14
- on: (fn) => {
15
- port.addListener("message", fn);
16
- }
17
- };
18
- }
19
- function disposeInternalListeners() {
20
- for (const fn of dispose) try {
21
- fn();
22
- } catch {}
23
- dispose.length = 0;
24
- }
25
- function createForksRpcOptions(nodeV8) {
26
- return {
27
- serialize: nodeV8.serialize,
28
- deserialize: (v) => nodeV8.deserialize(Buffer.from(v)),
29
- post(v) {
30
- processSend(v);
31
- },
32
- on(fn) {
33
- const handler = (message, ...extras) => {
34
- // Do not react on Tinypool's internal messaging
35
- if (message?.__tinypool_worker_message__) return;
36
- return fn(message, ...extras);
37
- };
38
- processOn("message", handler);
39
- dispose.push(() => processOff("message", handler));
40
- }
41
- };
42
- }
43
- /**
44
- * Reverts the wrapping done by `utils/config-helpers.ts`'s `wrapSerializableConfig`
45
- */
46
- function unwrapSerializableConfig(config) {
47
- if (config.testNamePattern && typeof config.testNamePattern === "string") {
48
- const testNamePattern = config.testNamePattern;
49
- if (testNamePattern.startsWith(REGEXP_WRAP_PREFIX)) config.testNamePattern = parseRegexp(testNamePattern.slice(REGEXP_WRAP_PREFIX.length));
50
- }
51
- if (config.defines && Array.isArray(config.defines.keys) && config.defines.original) {
52
- const { keys, original } = config.defines;
53
- const defines = {};
54
- // Apply all keys from the original. Entries which had undefined value are missing from original now
55
- for (const key of keys) defines[key] = original[key];
56
- config.defines = defines;
57
- }
58
- return config;
59
- }
60
-
61
- export { createThreadsRpcOptions as a, createForksRpcOptions as c, disposeInternalListeners as d, unwrapSerializableConfig as u };
@@ -1,8 +0,0 @@
1
- import { MessagePort } from 'node:worker_threads';
2
- import { C as ContextRPC } from './worker.d.DoNjFAiv.js';
3
-
4
- interface WorkerContext extends ContextRPC {
5
- port: MessagePort;
6
- }
7
-
8
- export type { WorkerContext as W };
@@ -1,169 +0,0 @@
1
- import { CancelReason, File, TestAnnotation, TaskResultPack, TaskEventPack, FileSpecification, Task } from '@vitest/runner';
2
- import { a as SerializedConfig } from './config.d.HJdfX-8k.js';
3
- import { T as TransformMode, U as UserConsoleLog, A as AfterSuiteRunMeta, E as Environment } from './environment.d.CUq4cUgQ.js';
4
- import { SnapshotResult } from '@vitest/snapshot';
5
-
6
- type ArgumentsType<T> = T extends (...args: infer A) => any ? A : never;
7
- type ReturnType<T> = T extends (...args: any) => infer R ? R : never;
8
- type PromisifyFn<T> = ReturnType<T> extends Promise<any> ? T : (...args: ArgumentsType<T>) => Promise<Awaited<ReturnType<T>>>;
9
- type BirpcResolver = (name: string, resolved: (...args: unknown[]) => unknown) => ((...args: unknown[]) => unknown) | undefined;
10
- interface ChannelOptions {
11
- /**
12
- * Function to post raw message
13
- */
14
- post: (data: any, ...extras: any[]) => any | Promise<any>;
15
- /**
16
- * Listener to receive raw message
17
- */
18
- on: (fn: (data: any, ...extras: any[]) => void) => any | Promise<any>;
19
- /**
20
- * Clear the listener when `$close` is called
21
- */
22
- off?: (fn: (data: any, ...extras: any[]) => void) => any | Promise<any>;
23
- /**
24
- * Custom function to serialize data
25
- *
26
- * by default it passes the data as-is
27
- */
28
- serialize?: (data: any) => any;
29
- /**
30
- * Custom function to deserialize data
31
- *
32
- * by default it passes the data as-is
33
- */
34
- deserialize?: (data: any) => any;
35
- /**
36
- * Call the methods with the RPC context or the original functions object
37
- */
38
- bind?: 'rpc' | 'functions';
39
- }
40
- interface EventOptions<Remote> {
41
- /**
42
- * Names of remote functions that do not need response.
43
- */
44
- eventNames?: (keyof Remote)[];
45
- /**
46
- * Maximum timeout for waiting for response, in milliseconds.
47
- *
48
- * @default 60_000
49
- */
50
- timeout?: number;
51
- /**
52
- * Custom resolver to resolve function to be called
53
- *
54
- * For advanced use cases only
55
- */
56
- resolver?: BirpcResolver;
57
- /**
58
- * Custom error handler
59
- *
60
- * @deprecated use `onFunctionError` and `onGeneralError` instead
61
- */
62
- onError?: (error: Error, functionName: string, args: any[]) => boolean | void;
63
- /**
64
- * Custom error handler for errors occurred in local functions being called
65
- *
66
- * @returns `true` to prevent the error from being thrown
67
- */
68
- onFunctionError?: (error: Error, functionName: string, args: any[]) => boolean | void;
69
- /**
70
- * Custom error handler for errors occurred during serialization or messsaging
71
- *
72
- * @returns `true` to prevent the error from being thrown
73
- */
74
- onGeneralError?: (error: Error, functionName?: string, args?: any[]) => boolean | void;
75
- /**
76
- * Custom error handler for timeouts
77
- *
78
- * @returns `true` to prevent the error from being thrown
79
- */
80
- onTimeoutError?: (functionName: string, args: any[]) => boolean | void;
81
- }
82
- type BirpcOptions<Remote> = EventOptions<Remote> & ChannelOptions;
83
- type BirpcFn<T> = PromisifyFn<T> & {
84
- /**
85
- * Send event without asking for response
86
- */
87
- asEvent: (...args: ArgumentsType<T>) => void;
88
- };
89
- type BirpcReturn<RemoteFunctions, LocalFunctions = Record<string, never>> = {
90
- [K in keyof RemoteFunctions]: BirpcFn<RemoteFunctions[K]>;
91
- } & {
92
- $functions: LocalFunctions;
93
- $close: (error?: Error) => void;
94
- $closed: boolean;
95
- };
96
-
97
- interface RuntimeRPC {
98
- fetch: (id: string, transformMode: TransformMode) => Promise<{
99
- externalize?: string
100
- id?: string
101
- }>;
102
- transform: (id: string, transformMode: TransformMode) => Promise<{
103
- code?: string
104
- }>;
105
- resolveId: (id: string, importer: string | undefined, transformMode: TransformMode) => Promise<{
106
- external?: boolean | "absolute" | "relative"
107
- id: string
108
- /** @deprecated */
109
- meta?: Record<string, any> | null
110
- /** @deprecated */
111
- moduleSideEffects?: boolean | "no-treeshake" | null
112
- /** @deprecated */
113
- syntheticNamedExports?: boolean | string | null
114
- } | null>;
115
- onUserConsoleLog: (log: UserConsoleLog) => void;
116
- onUnhandledError: (err: unknown, type: string) => void;
117
- onQueued: (file: File) => void;
118
- onCollected: (files: File[]) => Promise<void>;
119
- onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void;
120
- onTaskAnnotate: (testId: string, annotation: TestAnnotation) => Promise<TestAnnotation>;
121
- onTaskUpdate: (pack: TaskResultPack[], events: TaskEventPack[]) => Promise<void>;
122
- onCancel: (reason: CancelReason) => void;
123
- getCountOfFailedTests: () => number;
124
- snapshotSaved: (snapshot: SnapshotResult) => void;
125
- resolveSnapshotPath: (testPath: string) => string;
126
- }
127
- interface RunnerRPC {
128
- onCancel: (reason: CancelReason) => void;
129
- }
130
-
131
- type WorkerRPC = BirpcReturn<RuntimeRPC, RunnerRPC>;
132
- interface ContextTestEnvironment {
133
- name: string;
134
- transformMode?: TransformMode;
135
- options: Record<string, any> | null;
136
- }
137
- type TestExecutionMethod = "run" | "collect";
138
- interface ContextRPC {
139
- pool: string;
140
- worker: string;
141
- workerId: number;
142
- config: SerializedConfig;
143
- projectName: string;
144
- files: string[] | FileSpecification[];
145
- environment: ContextTestEnvironment;
146
- providedContext: Record<string, any>;
147
- invalidates?: string[];
148
- }
149
- interface WorkerGlobalState {
150
- ctx: ContextRPC;
151
- config: SerializedConfig;
152
- rpc: WorkerRPC;
153
- current?: Task;
154
- filepath?: string;
155
- environment: Environment;
156
- environmentTeardownRun?: boolean;
157
- onCancel: Promise<CancelReason>;
158
- moduleCache: Map<string, any>;
159
- moduleExecutionInfo: Map<string, any>;
160
- onCleanup: (listener: () => unknown) => void;
161
- providedContext: Record<string, any>;
162
- durations: {
163
- environment: number
164
- prepare: number
165
- };
166
- onFilterStackTrace?: (trace: string) => string;
167
- }
168
-
169
- export type { BirpcOptions as B, ContextRPC as C, RuntimeRPC as R, TestExecutionMethod as T, WorkerGlobalState as W, BirpcReturn as a, RunnerRPC as b, ContextTestEnvironment as c };
package/dist/execute.d.ts DELETED
@@ -1,148 +0,0 @@
1
- import { ViteNodeRunnerOptions } from 'vite-node';
2
- import { ViteNodeRunner, ModuleExecutionInfo } from 'vite-node/client';
3
- import { R as RuntimeRPC, W as WorkerGlobalState } from './chunks/worker.d.DoNjFAiv.js';
4
- import vm from 'node:vm';
5
- import { MockedModule, MockedModuleType } from '@vitest/mocker';
6
- import { P as PendingSuiteMock, b as MockFactory, a as MockOptions } from './chunks/mocker.d.BE_2ls6u.js';
7
- import '@vitest/runner';
8
- import './chunks/config.d.HJdfX-8k.js';
9
- import '@vitest/pretty-format';
10
- import '@vitest/snapshot';
11
- import '@vitest/utils/diff';
12
- import './chunks/environment.d.CUq4cUgQ.js';
13
-
14
- declare class FileMap {
15
- private fsCache;
16
- private fsBufferCache;
17
- readFileAsync(path: string): Promise<string>;
18
- readFile(path: string): string;
19
- readBuffer(path: string): Buffer;
20
- }
21
-
22
- // need to copy paste types for vm
23
- // because they require latest @types/node which we don't bundle
24
- interface ModuleEvaluateOptions {
25
- timeout?: vm.RunningScriptOptions["timeout"] | undefined;
26
- breakOnSigint?: vm.RunningScriptOptions["breakOnSigint"] | undefined;
27
- }
28
- type ModuleLinker = (specifier: string, referencingModule: VMModule, extra: {
29
- assert: object
30
- }) => VMModule | Promise<VMModule>;
31
- type ModuleStatus = "unlinked" | "linking" | "linked" | "evaluating" | "evaluated" | "errored";
32
- declare class VMModule {
33
- dependencySpecifiers: readonly string[];
34
- error: any;
35
- identifier: string;
36
- context: vm.Context;
37
- namespace: object;
38
- status: ModuleStatus;
39
- evaluate(options?: ModuleEvaluateOptions): Promise<void>;
40
- link(linker: ModuleLinker): Promise<void>;
41
- }
42
-
43
- interface ExternalModulesExecutorOptions {
44
- context: vm.Context;
45
- fileMap: FileMap;
46
- packageCache: Map<string, any>;
47
- transform: RuntimeRPC["transform"];
48
- interopDefault?: boolean;
49
- viteClientModule: Record<string, unknown>;
50
- }
51
- // TODO: improve Node.js strict mode support in #2854
52
- declare class ExternalModulesExecutor {
53
- #private;
54
- private options;
55
- private cjs;
56
- private esm;
57
- private vite;
58
- private context;
59
- private fs;
60
- private resolvers;
61
- constructor(options: ExternalModulesExecutorOptions);
62
- import(identifier: string): Promise<object>;
63
- require(identifier: string): any;
64
- createRequire(identifier: string): NodeJS.Require;
65
- // dynamic import can be used in both ESM and CJS, so we have it in the executor
66
- importModuleDynamically: (specifier: string, referencer: VMModule) => Promise<VMModule>;
67
- resolveModule: (specifier: string, referencer: string) => Promise<VMModule>;
68
- resolve(specifier: string, parent: string): string;
69
- private findNearestPackageData;
70
- private getModuleInformation;
71
- private createModule;
72
- private get isNetworkSupported();
73
- }
74
-
75
- interface MockContext {
76
- /**
77
- * When mocking with a factory, this refers to the module that imported the mock.
78
- */
79
- callstack: null | string[];
80
- }
81
- declare class VitestMocker {
82
- executor: VitestExecutor;
83
- static pendingIds: PendingSuiteMock[];
84
- private spyModule?;
85
- private primitives;
86
- private filterPublicKeys;
87
- private registries;
88
- private mockContext;
89
- constructor(executor: VitestExecutor);
90
- private get root();
91
- private get moduleCache();
92
- private get moduleDirectories();
93
- initializeSpyModule(): Promise<void>;
94
- private getMockerRegistry;
95
- reset(): void;
96
- private deleteCachedItem;
97
- private isModuleDirectory;
98
- getSuiteFilepath(): string;
99
- private createError;
100
- private resolvePath;
101
- resolveMocks(): Promise<void>;
102
- private callFunctionMock;
103
- // public method to avoid circular dependency
104
- getMockContext(): MockContext;
105
- // path used to store mocked dependencies
106
- getMockPath(dep: string): string;
107
- getDependencyMock(id: string): MockedModule | undefined;
108
- normalizePath(path: string): string;
109
- resolveMockPath(mockPath: string, external: string | null): string | null;
110
- mockObject(object: Record<string | symbol, any>, mockExports?: Record<string | symbol, any>, behavior?: MockedModuleType): Record<string | symbol, any>;
111
- unmockPath(path: string): void;
112
- mockPath(originalId: string, path: string, external: string | null, mockType: MockedModuleType | undefined, factory: MockFactory | undefined): void;
113
- importActual<T>(rawId: string, importer: string, callstack?: string[] | null): Promise<T>;
114
- importMock(rawId: string, importee: string): Promise<any>;
115
- requestWithMock(url: string, callstack: string[]): Promise<any>;
116
- queueMock(id: string, importer: string, factoryOrOptions?: MockFactory | MockOptions): void;
117
- queueUnmock(id: string, importer: string): void;
118
- }
119
-
120
- interface ExecuteOptions extends ViteNodeRunnerOptions {
121
- moduleDirectories?: string[];
122
- state: WorkerGlobalState;
123
- context?: vm.Context;
124
- externalModulesExecutor?: ExternalModulesExecutor;
125
- }
126
- declare class VitestExecutor extends ViteNodeRunner {
127
- options: ExecuteOptions;
128
- mocker: VitestMocker;
129
- externalModules?: ExternalModulesExecutor;
130
- private primitives;
131
- constructor(options: ExecuteOptions);
132
- protected getContextPrimitives(): {
133
- Object: typeof Object
134
- Reflect: typeof Reflect
135
- Symbol: typeof Symbol
136
- };
137
- get state(): WorkerGlobalState;
138
- get moduleExecutionInfo(): ModuleExecutionInfo | undefined;
139
- shouldResolveId(id: string, _importee?: string | undefined): boolean;
140
- originalResolveUrl(id: string, importer?: string): Promise<[url: string, fsPath: string]>;
141
- resolveUrl(id: string, importer?: string): Promise<[url: string, fsPath: string]>;
142
- protected runModule(context: Record<string, any>, transformed: string): Promise<void>;
143
- importExternalModule(path: string): Promise<any>;
144
- dependencyRequest(id: string, fsPath: string, callstack: string[]): Promise<any>;
145
- prepareContext(context: Record<string, any>): Record<string, any>;
146
- }
147
-
148
- export { VitestExecutor };
package/dist/execute.js DELETED
@@ -1,13 +0,0 @@
1
- export { V as VitestExecutor } from './chunks/execute.B7h3T_Hc.js';
2
- import 'node:fs';
3
- import 'node:url';
4
- import 'node:vm';
5
- import '@vitest/utils/error';
6
- import 'pathe';
7
- import 'vite-node/client';
8
- import 'vite-node/utils';
9
- import './path.js';
10
- import 'node:path';
11
- import '@vitest/mocker';
12
- import 'node:module';
13
- import '@vitest/utils';
package/dist/worker.js DELETED
@@ -1,124 +0,0 @@
1
- import { pathToFileURL } from 'node:url';
2
- import { createStackString, parseStacktrace } from '@vitest/utils/source-map';
3
- import { workerId } from 'tinypool';
4
- import { ViteNodeRunner, ModuleCacheMap } from 'vite-node/client';
5
- import { readFileSync } from 'node:fs';
6
- import { resolve, normalize } from 'pathe';
7
- import { e as environments } from './chunks/index.CmSc2RE5.js';
8
- import { s as setupInspect } from './chunks/inspector.C914Efll.js';
9
- import { c as createRuntimeRpc, a as rpcDone } from './chunks/rpc.CsFtxqeq.js';
10
- import { i as isChildProcess, s as setProcessTitle } from './chunks/utils.XdZDrNZV.js';
11
- import { d as disposeInternalListeners } from './chunks/utils.CAioKnHs.js';
12
- import 'node:console';
13
- import 'node:module';
14
- import '@vitest/utils';
15
- import './chunks/index.B521nVV-.js';
16
-
17
- function isBuiltinEnvironment(env) {
18
- return env in environments;
19
- }
20
- const _loaders = /* @__PURE__ */ new Map();
21
- async function createEnvironmentLoader(options) {
22
- if (!_loaders.has(options.root)) {
23
- const loader = new ViteNodeRunner(options);
24
- await loader.executeId("/@vite/env");
25
- _loaders.set(options.root, loader);
26
- }
27
- return _loaders.get(options.root);
28
- }
29
- async function loadEnvironment(ctx, rpc) {
30
- const name = ctx.environment.name;
31
- if (isBuiltinEnvironment(name)) return environments[name];
32
- const loader = await createEnvironmentLoader({
33
- root: ctx.config.root,
34
- fetchModule: async (id) => {
35
- const result = await rpc.fetch(id, "ssr");
36
- if (result.id) return { code: readFileSync(result.id, "utf-8") };
37
- return result;
38
- },
39
- resolveId: (id, importer) => rpc.resolveId(id, importer, "ssr")
40
- });
41
- const root = loader.root;
42
- const packageId = name[0] === "." || name[0] === "/" ? resolve(root, name) : (await rpc.resolveId(`vitest-environment-${name}`, void 0, "ssr"))?.id ?? resolve(root, name);
43
- const pkg = await loader.executeId(normalize(packageId));
44
- if (!pkg || !pkg.default || typeof pkg.default !== "object") throw new TypeError(`Environment "${name}" is not a valid environment. Path "${packageId}" should export default object with a "setup" or/and "setupVM" method.`);
45
- const environment = pkg.default;
46
- if (environment.transformMode !== "web" && environment.transformMode !== "ssr") throw new TypeError(`Environment "${name}" is not a valid environment. Path "${packageId}" should export default object with a "transformMode" method equal to "ssr" or "web".`);
47
- return environment;
48
- }
49
-
50
- const listeners = /* @__PURE__ */ new Set();
51
- function addCleanupListener(listener) {
52
- listeners.add(listener);
53
- }
54
- async function cleanup() {
55
- const promises = [...listeners].map((l) => l());
56
- await Promise.all(promises);
57
- }
58
-
59
- if (isChildProcess()) {
60
- setProcessTitle(`vitest ${workerId}`);
61
- const isProfiling = process.execArgv.some((execArg) => execArg.startsWith("--prof") || execArg.startsWith("--cpu-prof") || execArg.startsWith("--heap-prof") || execArg.startsWith("--diagnostic-dir"));
62
- if (isProfiling)
63
- // Work-around for nodejs/node#55094
64
- process.on("SIGTERM", () => {
65
- process.exit();
66
- });
67
- }
68
- // this is what every pool executes when running tests
69
- async function execute(method, ctx) {
70
- disposeInternalListeners();
71
- const prepareStart = performance.now();
72
- const inspectorCleanup = setupInspect(ctx);
73
- process.env.VITEST_WORKER_ID = String(ctx.workerId);
74
- process.env.VITEST_POOL_ID = String(workerId);
75
- try {
76
- // worker is a filepath or URL to a file that exposes a default export with "getRpcOptions" and "runTests" methods
77
- if (ctx.worker[0] === ".") throw new Error(`Path to the test runner cannot be relative, received "${ctx.worker}"`);
78
- const file = ctx.worker.startsWith("file:") ? ctx.worker : pathToFileURL(ctx.worker).toString();
79
- const testRunnerModule = await import(file);
80
- if (!testRunnerModule.default || typeof testRunnerModule.default !== "object") throw new TypeError(`Test worker object should be exposed as a default export. Received "${typeof testRunnerModule.default}"`);
81
- const worker = testRunnerModule.default;
82
- if (!worker.getRpcOptions || typeof worker.getRpcOptions !== "function") throw new TypeError(`Test worker should expose "getRpcOptions" method. Received "${typeof worker.getRpcOptions}".`);
83
- // RPC is used to communicate between worker (be it a thread worker or child process or a custom implementation) and the main thread
84
- const { rpc, onCancel } = createRuntimeRpc(worker.getRpcOptions(ctx));
85
- const beforeEnvironmentTime = performance.now();
86
- const environment = await loadEnvironment(ctx, rpc);
87
- if (ctx.environment.transformMode) environment.transformMode = ctx.environment.transformMode;
88
- const state = {
89
- ctx,
90
- moduleCache: new ModuleCacheMap(),
91
- moduleExecutionInfo: /* @__PURE__ */ new Map(),
92
- config: ctx.config,
93
- onCancel,
94
- environment,
95
- durations: {
96
- environment: beforeEnvironmentTime,
97
- prepare: prepareStart
98
- },
99
- rpc,
100
- onCleanup: (listener) => addCleanupListener(listener),
101
- providedContext: ctx.providedContext,
102
- onFilterStackTrace(stack) {
103
- return createStackString(parseStacktrace(stack));
104
- }
105
- };
106
- const methodName = method === "collect" ? "collectTests" : "runTests";
107
- if (!worker[methodName] || typeof worker[methodName] !== "function") throw new TypeError(`Test worker should expose "runTests" method. Received "${typeof worker.runTests}".`);
108
- await worker[methodName](state);
109
- } finally {
110
- await rpcDone().catch(() => {});
111
- inspectorCleanup();
112
- }
113
- }
114
- function run(ctx) {
115
- return execute("run", ctx);
116
- }
117
- function collect(ctx) {
118
- return execute("collect", ctx);
119
- }
120
- async function teardown() {
121
- return cleanup();
122
- }
123
-
124
- export { collect, run, teardown };
@@ -1,43 +0,0 @@
1
- import v8 from 'node:v8';
2
- import { r as runBaseTests } from '../chunks/base.Bj3pWTr1.js';
3
- import { c as createForksRpcOptions, u as unwrapSerializableConfig } from '../chunks/utils.CAioKnHs.js';
4
- import 'vite-node/client';
5
- import '../chunks/execute.B7h3T_Hc.js';
6
- import 'node:fs';
7
- import 'node:url';
8
- import 'node:vm';
9
- import '@vitest/utils/error';
10
- import 'pathe';
11
- import 'vite-node/utils';
12
- import '../path.js';
13
- import 'node:path';
14
- import '@vitest/mocker';
15
- import 'node:module';
16
- import '@vitest/utils';
17
- import '../chunks/utils.XdZDrNZV.js';
18
-
19
- class ForksBaseWorker {
20
- getRpcOptions() {
21
- return createForksRpcOptions(v8);
22
- }
23
- async executeTests(method, state) {
24
- // TODO: don't rely on reassigning process.exit
25
- // https://github.com/vitest-dev/vitest/pull/4441#discussion_r1443771486
26
- const exit = process.exit;
27
- state.ctx.config = unwrapSerializableConfig(state.ctx.config);
28
- try {
29
- await runBaseTests(method, state);
30
- } finally {
31
- process.exit = exit;
32
- }
33
- }
34
- runTests(state) {
35
- return this.executeTests("run", state);
36
- }
37
- collectTests(state) {
38
- return this.executeTests("collect", state);
39
- }
40
- }
41
- const worker = new ForksBaseWorker();
42
-
43
- export { worker as default };
@@ -1,31 +0,0 @@
1
- import { r as runBaseTests } from '../chunks/base.Bj3pWTr1.js';
2
- import { a as createThreadsRpcOptions } from '../chunks/utils.CAioKnHs.js';
3
- import 'vite-node/client';
4
- import '../chunks/execute.B7h3T_Hc.js';
5
- import 'node:fs';
6
- import 'node:url';
7
- import 'node:vm';
8
- import '@vitest/utils/error';
9
- import 'pathe';
10
- import 'vite-node/utils';
11
- import '../path.js';
12
- import 'node:path';
13
- import '@vitest/mocker';
14
- import 'node:module';
15
- import '@vitest/utils';
16
- import '../chunks/utils.XdZDrNZV.js';
17
-
18
- class ThreadsBaseWorker {
19
- getRpcOptions(ctx) {
20
- return createThreadsRpcOptions(ctx);
21
- }
22
- runTests(state) {
23
- return runBaseTests("run", state);
24
- }
25
- collectTests(state) {
26
- return runBaseTests("collect", state);
27
- }
28
- }
29
- const worker = new ThreadsBaseWorker();
30
-
31
- export { worker as default };
@@ -1,47 +0,0 @@
1
- import v8 from 'node:v8';
2
- import { c as createForksRpcOptions, u as unwrapSerializableConfig } from '../chunks/utils.CAioKnHs.js';
3
- import { r as runVmTests } from '../chunks/vm.BThCzidc.js';
4
- import '@vitest/utils';
5
- import 'node:url';
6
- import 'node:vm';
7
- import 'pathe';
8
- import '../path.js';
9
- import 'node:path';
10
- import '../chunks/console.CtFJOzRO.js';
11
- import 'node:console';
12
- import 'node:stream';
13
- import 'tinyrainbow';
14
- import '../chunks/date.Bq6ZW5rf.js';
15
- import '../chunks/utils.XdZDrNZV.js';
16
- import '../chunks/execute.B7h3T_Hc.js';
17
- import 'node:fs';
18
- import '@vitest/utils/error';
19
- import 'vite-node/client';
20
- import 'vite-node/utils';
21
- import '@vitest/mocker';
22
- import 'node:module';
23
- import 'vite-node/constants';
24
-
25
- class ForksVmWorker {
26
- getRpcOptions() {
27
- return createForksRpcOptions(v8);
28
- }
29
- async executeTests(method, state) {
30
- const exit = process.exit;
31
- state.ctx.config = unwrapSerializableConfig(state.ctx.config);
32
- try {
33
- await runVmTests(method, state);
34
- } finally {
35
- process.exit = exit;
36
- }
37
- }
38
- runTests(state) {
39
- return this.executeTests("run", state);
40
- }
41
- collectTests(state) {
42
- return this.executeTests("collect", state);
43
- }
44
- }
45
- const worker = new ForksVmWorker();
46
-
47
- export { worker as default };
@@ -1,37 +0,0 @@
1
- import { a as createThreadsRpcOptions } from '../chunks/utils.CAioKnHs.js';
2
- import { r as runVmTests } from '../chunks/vm.BThCzidc.js';
3
- import '@vitest/utils';
4
- import 'node:url';
5
- import 'node:vm';
6
- import 'pathe';
7
- import '../path.js';
8
- import 'node:path';
9
- import '../chunks/console.CtFJOzRO.js';
10
- import 'node:console';
11
- import 'node:stream';
12
- import 'tinyrainbow';
13
- import '../chunks/date.Bq6ZW5rf.js';
14
- import '../chunks/utils.XdZDrNZV.js';
15
- import '../chunks/execute.B7h3T_Hc.js';
16
- import 'node:fs';
17
- import '@vitest/utils/error';
18
- import 'vite-node/client';
19
- import 'vite-node/utils';
20
- import '@vitest/mocker';
21
- import 'node:module';
22
- import 'vite-node/constants';
23
-
24
- class ThreadsVmWorker {
25
- getRpcOptions(ctx) {
26
- return createThreadsRpcOptions(ctx);
27
- }
28
- runTests(state) {
29
- return runVmTests("run", state);
30
- }
31
- collectTests(state) {
32
- return runVmTests("collect", state);
33
- }
34
- }
35
- const worker = new ThreadsVmWorker();
36
-
37
- export { worker as default };