vitest-native 0.14.1 → 0.15.0-rc.2
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.
- package/README.md +11 -10
- package/dist/cli.d.mts +9 -1
- package/dist/cli.mjs +2609 -361
- package/dist/context.d.mts +19 -0
- package/dist/context.mjs +47 -1
- package/dist/docs-url.d.mts +4 -0
- package/dist/docs-url.mjs +9 -0
- package/dist/errors.d.mts +21 -1
- package/dist/hang-watch-setup.mjs +55 -0
- package/dist/hang-watch.d.mts +56 -0
- package/dist/hang-watch.mjs +343 -0
- package/dist/helpers.cjs +24 -53
- package/dist/helpers.mjs +22 -1
- package/dist/host-D0r3P_T1.mjs +1985 -0
- package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +723 -149
- package/dist/jest-compat/aliases.d.mts +1 -0
- package/dist/jest-compat/aliases.mjs +11 -0
- package/dist/jest-compat/interop.mjs +1 -1
- package/dist/jest-compat/jest-object.mjs +23 -5
- package/dist/jest-compat/node-registry.mjs +836 -68
- package/dist/jest-compat/setup.mjs +205 -12
- package/dist/jest-compat.cjs +383 -47
- package/dist/jest-compat.d.cts +19 -2
- package/dist/jest-compat.d.mts +19 -2
- package/dist/jest-compat.mjs +232 -47
- package/dist/matchers.d.cts +0 -1
- package/dist/matchers.d.mts +0 -1
- package/dist/native/assets.mjs +3 -1
- package/dist/native/babel-caller.d.mts +13 -0
- package/dist/native/babel-caller.mjs +24 -0
- package/dist/native/babel-toolchain.mjs +27 -3
- package/dist/native/boundary.mjs +45 -8
- package/dist/native/bounded-process.mjs +63 -5
- package/dist/native/bridge-client.mjs +133 -0
- package/dist/native/bridge-server.mjs +215 -0
- package/dist/native/bridge-thread.mjs +79 -0
- package/dist/native/bridge.mjs +512 -0
- package/dist/native/compile-error.mjs +120 -0
- package/dist/native/explain.mjs +3 -2
- package/dist/native/expo-module-mocks.mjs +2 -0
- package/dist/native/export-condition-recovery.mjs +20 -99
- package/dist/native/hooks.mjs +256 -133
- package/dist/native/jest-resolvers.mjs +94 -0
- package/dist/native/library-jest.mjs +352 -0
- package/dist/native/loader.mjs +167 -73
- package/dist/native/match.mjs +67 -7
- package/dist/native/module-reset.mjs +44 -49
- package/dist/native/ownership-ledger.d.mts +87 -0
- package/dist/native/ownership-ledger.mjs +524 -0
- package/dist/native/ownership.d.mts +20 -0
- package/dist/native/ownership.mjs +114 -0
- package/dist/native/registry-compiler.mjs +39 -5
- package/dist/native/registry-process.mjs +327 -28
- package/dist/native/registry.mjs +752 -200
- package/dist/native/resident-health.mjs +1 -0
- package/dist/native/resolve.d.mts +7 -0
- package/dist/native/resolve.mjs +119 -4
- package/dist/native/rntl-hooks.mjs +9 -5
- package/dist/native/rntl-text-host.mjs +5 -15
- package/dist/native/root-spelling.d.mts +6 -0
- package/dist/native/root-spelling.mjs +77 -0
- package/dist/native/runner.mjs +2 -19
- package/dist/native/setup.mjs +119 -38
- package/dist/native/shared-resolver.d.mts +141 -0
- package/dist/native/shared-resolver.mjs +719 -0
- package/dist/native/test-runner.mjs +26 -0
- package/dist/native/transform.mjs +18 -22
- package/dist/native/worker.mjs +9 -4
- package/dist/node-dispatch.mjs +293 -0
- package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
- package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/rntl-matchers.d.ts +11 -15
- package/dist/rntl-support.mjs +28 -13
- package/dist/root-mocks-BNXeosbR.mjs +155 -0
- package/dist/serializer.cjs +7 -5
- package/dist/serializer.d.cts +7 -5
- package/dist/serializer.d.mts +7 -5
- package/dist/serializer.mjs +7 -5
- package/dist/setup.mjs +26 -27
- package/docs/migrating-from-jest.md +9 -232
- package/docs/migrating-from-vitest-react-native.md +4 -4
- package/docs/release-readiness.md +9 -11
- package/docs/versioning.md +38 -9
- package/package.json +59 -33
- package/dist/host-BAAAlSkO.mjs +0 -1028
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
export declare const OWNERSHIP_CHANNEL: "ownership";
|
|
2
|
+
export declare const OWNERSHIP_ACCESS: string;
|
|
3
|
+
export declare const OWNERSHIP_META_KEY: "vitestNativeOwnership";
|
|
4
|
+
export declare const ENGINE_RUNTIME_DIR: string;
|
|
5
|
+
|
|
6
|
+
export type OwnershipGuardMode = "warn" | "error";
|
|
7
|
+
|
|
8
|
+
export interface OwnershipGuardConfig {
|
|
9
|
+
mode: OwnershipGuardMode;
|
|
10
|
+
allow: { path: string; reason: string }[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type DualEvaluationRoute =
|
|
14
|
+
| "jest-compat"
|
|
15
|
+
| "require-from-vite"
|
|
16
|
+
| "node-owned-source"
|
|
17
|
+
| "installed-package"
|
|
18
|
+
| "node-esm"
|
|
19
|
+
| "installed-typescript"
|
|
20
|
+
| "vite-inline";
|
|
21
|
+
|
|
22
|
+
/** Where Node's load began: the first file of its chain that Node loaded from outside. */
|
|
23
|
+
export interface DualEvaluationCause {
|
|
24
|
+
readonly route: DualEvaluationRoute;
|
|
25
|
+
readonly file: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export declare const OWNERSHIP_ROUTES: Record<DualEvaluationRoute, { label: string; fix: string }>;
|
|
29
|
+
|
|
30
|
+
export interface DualEvaluation {
|
|
31
|
+
readonly code: "SOURCE_EVALUATED_TWICE";
|
|
32
|
+
readonly file: string;
|
|
33
|
+
readonly first: "node" | "vite";
|
|
34
|
+
readonly second: "node" | "vite";
|
|
35
|
+
readonly route: DualEvaluationRoute;
|
|
36
|
+
readonly cause: DualEvaluationCause;
|
|
37
|
+
readonly via: NodeEvaluation["via"];
|
|
38
|
+
readonly owner: "vite" | "node" | "vitest-default" | null;
|
|
39
|
+
readonly message: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface NodeEvaluation {
|
|
43
|
+
via: "cjs" | "require-esm" | "esm" | "json";
|
|
44
|
+
ref?: WeakRef<object>;
|
|
45
|
+
cacheKey?: string;
|
|
46
|
+
parent?: string;
|
|
47
|
+
generation?: number | null;
|
|
48
|
+
jestRequire?: boolean;
|
|
49
|
+
filename?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ViteEvaluation {
|
|
53
|
+
file: string;
|
|
54
|
+
key: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface OwnershipLedger {
|
|
58
|
+
readonly mode: OwnershipGuardMode;
|
|
59
|
+
readonly conflicts: DualEvaluation[];
|
|
60
|
+
readonly allowUsed: Set<string>;
|
|
61
|
+
recordNode(filename: string, entry: NodeEvaluation, options?: { key?: string }): void;
|
|
62
|
+
recordVite(key: string, file: string): void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The ledger installed in this worker, on the dispatcher's "ownership" channel. */
|
|
66
|
+
export type InstalledOwnershipLedger = OwnershipLedger;
|
|
67
|
+
|
|
68
|
+
export declare function ledgerKey(file: string): string;
|
|
69
|
+
export declare function realKey(file: string): string;
|
|
70
|
+
export declare function viteMarkerFor(id: string): string | null;
|
|
71
|
+
export declare function parseOwnershipGuardConfig(
|
|
72
|
+
raw: string | Partial<OwnershipGuardConfig> | undefined,
|
|
73
|
+
): OwnershipGuardConfig;
|
|
74
|
+
export declare function createOwnershipLedger(options?: {
|
|
75
|
+
mode?: OwnershipGuardMode;
|
|
76
|
+
allow?: { path: string; reason: string }[];
|
|
77
|
+
exemptDirs?: string[];
|
|
78
|
+
nodeLive?: (entry: NodeEvaluation) => boolean;
|
|
79
|
+
viteLive?: (entry: ViteEvaluation) => boolean;
|
|
80
|
+
viteImporter?: (entry: ViteEvaluation) => string | null;
|
|
81
|
+
ownerOf?: (file: string) => { owner: string; reason: string } | null;
|
|
82
|
+
nodeHolds?: (file: string) => boolean;
|
|
83
|
+
warn?: (message: string) => void;
|
|
84
|
+
}): OwnershipLedger;
|
|
85
|
+
export declare function installOwnershipLedger(options?: {
|
|
86
|
+
projectRoot?: string;
|
|
87
|
+
}): InstalledOwnershipLedger;
|
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
// The ownership guard: a per-worker ledger of which module system evaluated each file,
|
|
2
|
+
// reporting a file evaluated by both while the first copy is still live. Design, the
|
|
3
|
+
// reasons behind each rule, measured costs and limits: docs/ownership-guard.md.
|
|
4
|
+
import { nodeDispatch } from "../node-dispatch.mjs";
|
|
5
|
+
import Module from "node:module";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { NODE_MODULES_PATH } from "./match.mjs";
|
|
10
|
+
import {
|
|
11
|
+
INSTALLED_TYPESCRIPT,
|
|
12
|
+
TEST_RUNTIME_RESIDENT_PATH,
|
|
13
|
+
createNativeOwnershipPolicy,
|
|
14
|
+
parseNativeOwnershipManifest,
|
|
15
|
+
} from "./ownership.mjs";
|
|
16
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
17
|
+
import { projectContext } from "../context.mjs";
|
|
18
|
+
import { docsUrl } from "../docs-url.mjs";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The engine's dispatcher channel the ledger lives on (node-dispatch.mjs): `ledger`, and
|
|
22
|
+
* the records it receives from outside the worker's own code, `.vite(key, file)` from the
|
|
23
|
+
* call appended to each Vite module and `.nodeEsm(url)` from the in-thread loader hook
|
|
24
|
+
* (loader.mjs); jest-compat raises `jestRequireDepth` around its synchronous
|
|
25
|
+
* requireActual/requireMock loads.
|
|
26
|
+
*/
|
|
27
|
+
export const OWNERSHIP_CHANNEL = "ownership";
|
|
28
|
+
/**
|
|
29
|
+
* How code Vite runs reaches the ledger: through the dispatcher, whose one per-worker
|
|
30
|
+
* global it shares, rather than a global of its own.
|
|
31
|
+
*/
|
|
32
|
+
export const OWNERSHIP_ACCESS = `globalThis[Symbol.for("vitest-native.node-dispatch")]?.channel(${JSON.stringify(OWNERSHIP_CHANNEL)})`;
|
|
33
|
+
export const OWNERSHIP_META_KEY = "vitestNativeOwnership";
|
|
34
|
+
|
|
35
|
+
// The engine's own runtime (src/ or dist/): exempt, as the hot worker loads it through
|
|
36
|
+
// Node and the setup file through Vite, and every install in it is guarded.
|
|
37
|
+
export const ENGINE_RUNTIME_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
38
|
+
|
|
39
|
+
// Forward slashes and an upper-case drive letter: Vite says `D:/a`, Node `D:\a`.
|
|
40
|
+
export function ledgerKey(file) {
|
|
41
|
+
const forward = String(file).replace(/\\/g, "/");
|
|
42
|
+
return /^[a-z]:\//.test(forward) ? forward[0].toUpperCase() + forward.slice(1) : forward;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Case-insensitive by default on macOS and Windows: keys are folded there.
|
|
46
|
+
const FOLD_CASE = process.platform === "darwin" || process.platform === "win32";
|
|
47
|
+
const fold = FOLD_CASE ? (key) => key.toLowerCase() : (key) => key;
|
|
48
|
+
|
|
49
|
+
export function nodeKey(file) {
|
|
50
|
+
return fold(ledgerKey(file));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function realKey(file) {
|
|
54
|
+
try {
|
|
55
|
+
return fold(ledgerKey(fs.realpathSync(file)));
|
|
56
|
+
} catch {
|
|
57
|
+
return fold(ledgerKey(file));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const NOT_THE_MODULE = /[?&](?:raw|url|inline|worker|sharedworker)\b/;
|
|
62
|
+
|
|
63
|
+
// The call the plugin appends to a module (query ids are the file's code; `?raw`,
|
|
64
|
+
// `?url` and worker queries serve something else). Keyed by real path through a
|
|
65
|
+
// per-directory cache: Vite can keep a symlinked directory in an id, and one realpath
|
|
66
|
+
// per directory instead of a stat or two per module kept transform time at main's.
|
|
67
|
+
const realDirs = new Map();
|
|
68
|
+
function realpathOr(file, fallback) {
|
|
69
|
+
try {
|
|
70
|
+
// The OS's spelling (realpathSync.native), as Vite's ids are: viteMarkerFor keys Vite's
|
|
71
|
+
// side by it.
|
|
72
|
+
return fs.realpathSync.native(file);
|
|
73
|
+
} catch {
|
|
74
|
+
return fallback;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function realDir(dir) {
|
|
78
|
+
let real = realDirs.get(dir);
|
|
79
|
+
if (real === undefined) {
|
|
80
|
+
real = realpathOr(dir, dir);
|
|
81
|
+
realDirs.set(dir, real);
|
|
82
|
+
}
|
|
83
|
+
return real;
|
|
84
|
+
}
|
|
85
|
+
export function viteMarkerFor(id) {
|
|
86
|
+
if (typeof id !== "string" || id.includes("\0") || NOT_THE_MODULE.test(id)) return null;
|
|
87
|
+
const file = id.replace(/[?#].*$/, "");
|
|
88
|
+
if (!path.isAbsolute(file) || !/\.(?:[cm]?[jt]sx?|json)$/.test(file)) return null;
|
|
89
|
+
const key = nodeKey(path.join(realDir(path.dirname(file)), path.basename(file)));
|
|
90
|
+
return `${OWNERSHIP_ACCESS}.vite?.(${JSON.stringify(key)}, ${JSON.stringify(file)});`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The project context's `ownershipGuard` (or its JSON). A malformed value falls back to
|
|
94
|
+
// the default rather than stopping the run.
|
|
95
|
+
export function parseOwnershipGuardConfig(raw) {
|
|
96
|
+
const fallback = { mode: "warn", allow: [] };
|
|
97
|
+
if (!raw) return fallback;
|
|
98
|
+
try {
|
|
99
|
+
const value = typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
100
|
+
const mode = value?.mode === "error" ? "error" : "warn";
|
|
101
|
+
const allow = Array.isArray(value?.allow)
|
|
102
|
+
? value.allow.filter(
|
|
103
|
+
(entry) =>
|
|
104
|
+
entry &&
|
|
105
|
+
typeof entry.path === "string" &&
|
|
106
|
+
typeof entry.reason === "string" &&
|
|
107
|
+
entry.reason.trim() !== "",
|
|
108
|
+
)
|
|
109
|
+
: [];
|
|
110
|
+
return { mode, allow };
|
|
111
|
+
} catch {
|
|
112
|
+
return fallback;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export const OWNERSHIP_ROUTES = {
|
|
117
|
+
"jest-compat": {
|
|
118
|
+
label: "a synchronous jest.requireActual/requireMock through jest-compat",
|
|
119
|
+
fix:
|
|
120
|
+
"Vite had not evaluated the file yet, so Node loaded its own copy. Import the " +
|
|
121
|
+
"module statically before the jest.mock that needs it, or load it with " +
|
|
122
|
+
"`await vi.importActual(...)` inside an async factory. Or set " +
|
|
123
|
+
"reactNative({ experimental: { ownershipModel: 'resolution' } }), which gives " +
|
|
124
|
+
"Node's require of your source Vite's instance.",
|
|
125
|
+
},
|
|
126
|
+
"require-from-vite": {
|
|
127
|
+
label: "require() in a file Vite evaluated",
|
|
128
|
+
fix:
|
|
129
|
+
"Vitest's `require` inside a test or source file is Node's. Use `import`, or, in " +
|
|
130
|
+
"a jest.mock factory, load it with `await vi.importActual(...)` in an async " +
|
|
131
|
+
"factory, so the file stays in Vite's graph. Or set " +
|
|
132
|
+
"reactNative({ experimental: { ownershipModel: 'resolution' } }), which gives " +
|
|
133
|
+
"Node's require of your source Vite's instance.",
|
|
134
|
+
},
|
|
135
|
+
"node-owned-source": {
|
|
136
|
+
label: "an import from source Node evaluated",
|
|
137
|
+
fix:
|
|
138
|
+
"Node-owned code reached a file Vite owns, typically a workspace package Node " +
|
|
139
|
+
"owns whose source imports a sibling through a resolve.alias or tsconfig paths. " +
|
|
140
|
+
"Keep both packages on one side.",
|
|
141
|
+
},
|
|
142
|
+
"installed-package": {
|
|
143
|
+
label: "an installed package required it",
|
|
144
|
+
fix:
|
|
145
|
+
"A Node-owned package depends on a file Vite owns. Nothing can make that one " +
|
|
146
|
+
"instance: import the file from one side only, or test it from a package that " +
|
|
147
|
+
"does not sit underneath that dependency.",
|
|
148
|
+
},
|
|
149
|
+
"node-esm": {
|
|
150
|
+
label: "Node's ESM loader imported it",
|
|
151
|
+
fix:
|
|
152
|
+
"An externalized module imported a file Vite also evaluates. Give the file one " +
|
|
153
|
+
"owner: drop the server.deps.inline rule that claims it, or the alias that " +
|
|
154
|
+
"sends Vite to it.",
|
|
155
|
+
},
|
|
156
|
+
"installed-typescript": {
|
|
157
|
+
label: "an installed package's TypeScript source, required and imported",
|
|
158
|
+
fix:
|
|
159
|
+
"Vitest gives Vite an installed package's TypeScript source, which Node also " +
|
|
160
|
+
"compiles for a require. Set reactNative({ experimental: { nodeMocks: true } }): " +
|
|
161
|
+
"Node then loads it once for both, and a vi.mock still reaches it.",
|
|
162
|
+
},
|
|
163
|
+
"vite-inline": {
|
|
164
|
+
label: "an installed file that Vite also evaluates",
|
|
165
|
+
fix:
|
|
166
|
+
"A server.deps.inline rule, Vitest's default inlining or an alias gave Vite a " +
|
|
167
|
+
"file under node_modules that Node also loads. Remove the rule or alias that " +
|
|
168
|
+
"gives it to Vite, so Node's copy is the only one.",
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const VIA = {
|
|
173
|
+
cjs: "CommonJS",
|
|
174
|
+
"require-esm": "require() of an ES module",
|
|
175
|
+
esm: "ESM loader",
|
|
176
|
+
json: "JSON",
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const ENGINE_FRAME = ENGINE_RUNTIME_DIR + path.sep;
|
|
180
|
+
|
|
181
|
+
function frames(stack) {
|
|
182
|
+
return String(stack ?? "")
|
|
183
|
+
.split("\n")
|
|
184
|
+
.slice(1)
|
|
185
|
+
.map((line) => line.trim())
|
|
186
|
+
.filter(
|
|
187
|
+
(line) =>
|
|
188
|
+
line.startsWith("at ") &&
|
|
189
|
+
!line.includes("node:") &&
|
|
190
|
+
!line.includes(ENGINE_FRAME) &&
|
|
191
|
+
!/[\\/](?:vitest|vite)[\\/]dist[\\/]/.test(line),
|
|
192
|
+
)
|
|
193
|
+
.slice(0, 8);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Pure apart from the probes it is given. Node records are per module, not per path.
|
|
197
|
+
export function createOwnershipLedger({
|
|
198
|
+
mode = "warn",
|
|
199
|
+
allow = [],
|
|
200
|
+
exemptDirs = [ENGINE_RUNTIME_DIR],
|
|
201
|
+
nodeLive = () => true,
|
|
202
|
+
collected = () => false,
|
|
203
|
+
viteLive = () => true,
|
|
204
|
+
viteImporter = () => null,
|
|
205
|
+
ownerOf = () => null,
|
|
206
|
+
// Whether Node holds `file` now, loaded or still loading: a requirer Node is still
|
|
207
|
+
// evaluating is not recorded yet (Node's copies are recorded once they have loaded).
|
|
208
|
+
nodeHolds = () => false,
|
|
209
|
+
warn = (message) => console.warn(message),
|
|
210
|
+
} = {}) {
|
|
211
|
+
const node = new Map();
|
|
212
|
+
const vite = new Map();
|
|
213
|
+
const reported = new Set();
|
|
214
|
+
// The causes already printed in this worker, with how many files each has had since.
|
|
215
|
+
const printed = new Map();
|
|
216
|
+
const conflicts = [];
|
|
217
|
+
const allowUsed = new Set();
|
|
218
|
+
|
|
219
|
+
// On the ledger key (real path, folded where the file system ignores case), the same
|
|
220
|
+
// whichever side was second: Node's filename and Vite's id can spell one file apart.
|
|
221
|
+
const within = (dirKey, key) => key === dirKey || key.startsWith(`${dirKey}/`);
|
|
222
|
+
const exemptKeys = exemptDirs.map((dir) => realKey(dir).replace(/\/+$/, ""));
|
|
223
|
+
const allowKeys = allow.map((entry) => ({ entry, key: realKey(entry.path).replace(/\/+$/, "") }));
|
|
224
|
+
const exemption = (key) => {
|
|
225
|
+
if (TEST_RUNTIME_RESIDENT_PATH.test(key)) return "the test runtime (vitest, chai)";
|
|
226
|
+
if (exemptKeys.some((dir) => within(dir, key))) return "the engine's own runtime";
|
|
227
|
+
const hit = allowKeys.find((candidate) => within(candidate.key, key))?.entry;
|
|
228
|
+
if (!hit) return null;
|
|
229
|
+
allowUsed.add(hit.path);
|
|
230
|
+
return `ownership.allow: ${hit.reason}`;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const liveNode = (key) => node.get(key)?.find((record) => nodeLive(record));
|
|
234
|
+
|
|
235
|
+
function routeOf(key, nodeEntry, owner) {
|
|
236
|
+
// Only with nodeMocks off: with it on, the policy gives these files to Node (#544).
|
|
237
|
+
if (NODE_MODULES_PATH.test(key) && INSTALLED_TYPESCRIPT.test(key)) {
|
|
238
|
+
return "installed-typescript";
|
|
239
|
+
}
|
|
240
|
+
if (owner?.owner === "node" || NODE_MODULES_PATH.test(key)) return "vite-inline";
|
|
241
|
+
if (nodeEntry.via === "esm") return "node-esm";
|
|
242
|
+
if (nodeEntry.jestRequire) return "jest-compat";
|
|
243
|
+
const parent = nodeEntry.parent;
|
|
244
|
+
if (typeof parent === "string" && NODE_MODULES_PATH.test(parent)) return "installed-package";
|
|
245
|
+
if (typeof parent === "string" && (node.has(nodeKey(parent)) || nodeHolds(parent))) {
|
|
246
|
+
return "node-owned-source";
|
|
247
|
+
}
|
|
248
|
+
return "require-from-vite";
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Where Node's load of a file began: up its chain of Node-loaded parents to the first
|
|
253
|
+
* one whose parent Node did not load (a test file, a file Vite evaluated, an installed
|
|
254
|
+
* package). Every file one `require` pulls in shares it, so they are one cause: a jest.mock
|
|
255
|
+
* factory's require of a module that imports 600 others is one finding, not 600. The
|
|
256
|
+
* walk stops below a parent the policy gives Node (a workspace package Node owns):
|
|
257
|
+
* that code reaching a file Vite owns is the cause itself.
|
|
258
|
+
*/
|
|
259
|
+
function originOf(nodeEntry) {
|
|
260
|
+
const seen = new Set([nodeEntry]);
|
|
261
|
+
let entry = nodeEntry;
|
|
262
|
+
for (;;) {
|
|
263
|
+
const parent = entry.parent;
|
|
264
|
+
if (typeof parent !== "string" || NODE_MODULES_PATH.test(parent)) return entry;
|
|
265
|
+
if (ownerOf(parent)?.owner === "node") return entry;
|
|
266
|
+
// A live copy only: under the hot runtime an earlier generation's record can remain.
|
|
267
|
+
const up = liveNode(nodeKey(parent));
|
|
268
|
+
if (up === undefined || seen.has(up)) return entry;
|
|
269
|
+
seen.add(up);
|
|
270
|
+
entry = up;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function report(key, nodeEntry, viteEntry, second) {
|
|
275
|
+
const owner = ownerOf(nodeEntry.filename);
|
|
276
|
+
const route = routeOf(key, nodeEntry, owner);
|
|
277
|
+
const { label } = OWNERSHIP_ROUTES[route];
|
|
278
|
+
const origin = originOf(nodeEntry);
|
|
279
|
+
const originRoute =
|
|
280
|
+
origin === nodeEntry
|
|
281
|
+
? route
|
|
282
|
+
: routeOf(nodeKey(origin.filename), origin, ownerOf(origin.filename));
|
|
283
|
+
const cause = { route: originRoute, file: origin.filename };
|
|
284
|
+
const causeKey = `${originRoute}\0${origin.filename}`;
|
|
285
|
+
// The fix is the cause's: the files a require pulled in name their importer as the
|
|
286
|
+
// route, but what fixes them all is fixing that require.
|
|
287
|
+
const { fix } = OWNERSHIP_ROUTES[originRoute];
|
|
288
|
+
const originLine =
|
|
289
|
+
origin === nodeEntry
|
|
290
|
+
? ""
|
|
291
|
+
: ` origin -> ${origin.filename}, which Node loaded through ` +
|
|
292
|
+
`${OWNERSHIP_ROUTES[originRoute].label}, and which loaded this file\n`;
|
|
293
|
+
const ownerName = { node: "Node", vite: "Vite", "vitest-default": "none declared" };
|
|
294
|
+
const ownerLine = owner
|
|
295
|
+
? `${ownerName[owner.owner] ?? owner.owner} (${owner.reason})`
|
|
296
|
+
: "unknown";
|
|
297
|
+
const parent = nodeEntry.parent ?? "(no parent recorded)";
|
|
298
|
+
const importer = viteImporter(viteEntry) ?? "(no importer recorded)";
|
|
299
|
+
const nodeLine = `Node (${VIA[nodeEntry.via] ?? nodeEntry.via}), required by ${parent}`;
|
|
300
|
+
const viteLine = `Vite, imported by ${importer}`;
|
|
301
|
+
// A stack only when reporting: one per compile cost more than the whole ledger.
|
|
302
|
+
const stack = second === "node" ? frames(new Error().stack) : [];
|
|
303
|
+
let outcome;
|
|
304
|
+
if (mode !== "error") {
|
|
305
|
+
outcome = ` This is a warning; set reactNative({ ownership: 'error' }) to fail on it. `;
|
|
306
|
+
} else if (second === "node" && nodeEntry.via === "esm") {
|
|
307
|
+
outcome = ` Node's copy was never evaluated: the import threw (ownership: 'error'). `;
|
|
308
|
+
} else if (second === "node") {
|
|
309
|
+
outcome =
|
|
310
|
+
` Node's copy ran, as Node reports a module once it has loaded; the require threw ` +
|
|
311
|
+
`(ownership: 'error'). `;
|
|
312
|
+
} else {
|
|
313
|
+
outcome =
|
|
314
|
+
` Vite's copy ran; this file fails. Its top-level code had already run when this ` +
|
|
315
|
+
`was seen, so the import throws and the test file fails at its end (ownership: 'error'). `;
|
|
316
|
+
}
|
|
317
|
+
const message =
|
|
318
|
+
`[vitest-native] ${nodeEntry.filename} was evaluated by both Node and Vite in this ` +
|
|
319
|
+
`worker. It now exists twice, and module state written through one copy is not ` +
|
|
320
|
+
`seen by the other.\n` +
|
|
321
|
+
` policy owner -> ${ownerLine}\n` +
|
|
322
|
+
` first -> ${second === "vite" ? nodeLine : viteLine}\n` +
|
|
323
|
+
` second -> ${second === "vite" ? viteLine : nodeLine}\n` +
|
|
324
|
+
` route -> ${label}\n` +
|
|
325
|
+
originLine +
|
|
326
|
+
` fix -> ${fix}\n` +
|
|
327
|
+
(stack.length > 0
|
|
328
|
+
? ` Node stack:\n${stack.map((line) => ` ${line}`).join("\n")}\n`
|
|
329
|
+
: "") +
|
|
330
|
+
outcome +
|
|
331
|
+
`A deliberate case can be exempted with ownership.allow: [{ path, reason }] ` +
|
|
332
|
+
`(${docsUrl("/guide/errors#SOURCE_EVALUATED_TWICE")}).`;
|
|
333
|
+
conflicts.push(
|
|
334
|
+
Object.freeze({
|
|
335
|
+
code: "SOURCE_EVALUATED_TWICE",
|
|
336
|
+
file: nodeEntry.filename,
|
|
337
|
+
first: second === "vite" ? "node" : "vite",
|
|
338
|
+
second,
|
|
339
|
+
route,
|
|
340
|
+
cause,
|
|
341
|
+
via: nodeEntry.via,
|
|
342
|
+
owner: owner?.owner ?? null,
|
|
343
|
+
message,
|
|
344
|
+
}),
|
|
345
|
+
);
|
|
346
|
+
if (mode === "error") {
|
|
347
|
+
throw new VitestNativeError("SOURCE_EVALUATED_TWICE", message);
|
|
348
|
+
}
|
|
349
|
+
if (reported.has(key)) return;
|
|
350
|
+
reported.add(key);
|
|
351
|
+
// One full warning per cause in this worker; the end-of-run summary counts the rest.
|
|
352
|
+
const count = printed.get(causeKey);
|
|
353
|
+
printed.set(causeKey, (count ?? 0) + 1);
|
|
354
|
+
if (count !== undefined) return;
|
|
355
|
+
warn(
|
|
356
|
+
`${message}\n Other files with the same origin are not printed here; the summary ` +
|
|
357
|
+
`at the end of the run counts them.`,
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
return {
|
|
362
|
+
mode,
|
|
363
|
+
conflicts,
|
|
364
|
+
allowUsed,
|
|
365
|
+
// When Node evaluates `filename`: before an ES module runs (the loader's hook), so in
|
|
366
|
+
// error mode the throw means it never runs; once a CommonJS module has loaded (the
|
|
367
|
+
// dispatcher's report), so the throw fails the require after it ran.
|
|
368
|
+
recordNode(filename, entry, { key = nodeKey(filename) } = {}) {
|
|
369
|
+
entry.filename = filename;
|
|
370
|
+
const records = node.get(key);
|
|
371
|
+
if (records === undefined) node.set(key, [entry]);
|
|
372
|
+
else {
|
|
373
|
+
// Drop only collected modules (isolateModules restores an evicted copy) and ES
|
|
374
|
+
// module records of an earlier hot generation, which can never be live again.
|
|
375
|
+
const stale = (record) =>
|
|
376
|
+
record.via === "esm" &&
|
|
377
|
+
record.generation != null &&
|
|
378
|
+
entry.generation != null &&
|
|
379
|
+
record.generation !== entry.generation;
|
|
380
|
+
const kept = records.filter((record) => !collected(record) && !stale(record));
|
|
381
|
+
kept.push(entry);
|
|
382
|
+
node.set(key, kept);
|
|
383
|
+
}
|
|
384
|
+
// Recorded first, so a copy error mode refuses is still known to a later Vite load.
|
|
385
|
+
const prior = vite.get(key);
|
|
386
|
+
if (prior && viteLive(prior) && !exemption(key)) {
|
|
387
|
+
report(key, entry, prior, "node");
|
|
388
|
+
}
|
|
389
|
+
},
|
|
390
|
+
// After Vite ran the module: the marker is its last statement.
|
|
391
|
+
recordVite(key, file) {
|
|
392
|
+
const entry = { file, key };
|
|
393
|
+
const prior = liveNode(key);
|
|
394
|
+
if (prior && !exemption(key)) report(key, prior, entry, "vite");
|
|
395
|
+
vite.set(key, entry);
|
|
396
|
+
},
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function preserveSymlinks() {
|
|
401
|
+
return (
|
|
402
|
+
process.execArgv.includes("--preserve-symlinks") || process.env.NODE_PRESERVE_SYMLINKS === "1"
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Once per worker: from the setup file, or the hot worker at boot.
|
|
407
|
+
export function installOwnershipLedger({ projectRoot = process.cwd() } = {}) {
|
|
408
|
+
const channel = nodeDispatch().channel(OWNERSHIP_CHANNEL);
|
|
409
|
+
if (channel.ledger) return channel.ledger;
|
|
410
|
+
const context = projectContext();
|
|
411
|
+
const config = parseOwnershipGuardConfig(context?.ownershipGuard);
|
|
412
|
+
let policy;
|
|
413
|
+
const ownerOf = (file) => {
|
|
414
|
+
if (policy === undefined) {
|
|
415
|
+
const manifest = parseNativeOwnershipManifest(context?.ownership);
|
|
416
|
+
policy = manifest
|
|
417
|
+
? createNativeOwnershipPolicy({
|
|
418
|
+
projectRoot: manifest.projectRoot,
|
|
419
|
+
projectDirs: manifest.projectDirs,
|
|
420
|
+
reactNativeRoots: manifest.reactNativeRoots,
|
|
421
|
+
runtimeTransforms: manifest.nodeTransformPackages,
|
|
422
|
+
})
|
|
423
|
+
: null;
|
|
424
|
+
}
|
|
425
|
+
return policy?.decideFile(file) ?? null;
|
|
426
|
+
};
|
|
427
|
+
const generation = () => {
|
|
428
|
+
const view = globalThis.__vitest_native_hot_generation;
|
|
429
|
+
return view ? Atomics.load(view, 0) : 0;
|
|
430
|
+
};
|
|
431
|
+
const graph = () => globalThis.__vitest_worker__?.evaluatedModules;
|
|
432
|
+
// Plus the `mock:<id>` node vi.mock(path, { spy: true }) runs the original under.
|
|
433
|
+
const viteNodes = (file) => {
|
|
434
|
+
const g = graph();
|
|
435
|
+
const nodes = [...(g?.getModulesByFile?.(file) ?? [])];
|
|
436
|
+
const spy = g?.idToModuleMap?.get?.(`mock:${file}`);
|
|
437
|
+
if (spy) nodes.push(spy);
|
|
438
|
+
return nodes;
|
|
439
|
+
};
|
|
440
|
+
const ledger = createOwnershipLedger({
|
|
441
|
+
mode: config.mode,
|
|
442
|
+
allow: config.allow.map((entry) => ({
|
|
443
|
+
...entry,
|
|
444
|
+
path: path.resolve(projectRoot, entry.path),
|
|
445
|
+
})),
|
|
446
|
+
ownerOf,
|
|
447
|
+
nodeLive: (record) => {
|
|
448
|
+
if (record.via === "esm") {
|
|
449
|
+
// No ESM eviction; only a hot generation stamp makes a new instance.
|
|
450
|
+
return record.generation == null || record.generation === generation();
|
|
451
|
+
}
|
|
452
|
+
// Under the key Node cached it by (the link path with --preserve-symlinks).
|
|
453
|
+
const module = record.ref?.deref();
|
|
454
|
+
return module !== undefined && Module._cache[record.cacheKey] === module;
|
|
455
|
+
},
|
|
456
|
+
collected: (record) => record.ref !== undefined && record.ref.deref() === undefined,
|
|
457
|
+
nodeHolds: (file) => Module._cache[file] !== undefined,
|
|
458
|
+
viteLive: (entry) => {
|
|
459
|
+
if (typeof graph()?.getModulesByFile !== "function") return true;
|
|
460
|
+
return viteNodes(entry.file).some((n) => n.evaluated || n.promise);
|
|
461
|
+
},
|
|
462
|
+
viteImporter: (entry) => {
|
|
463
|
+
for (const n of viteNodes(entry.file)) {
|
|
464
|
+
const importer = n.importers?.values().next().value;
|
|
465
|
+
if (importer) return importer;
|
|
466
|
+
}
|
|
467
|
+
return null;
|
|
468
|
+
},
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
const keyOf = preserveSymlinks() ? realKey : nodeKey;
|
|
472
|
+
// Raised by jest-compat while a jest.require* call loads (node-registry.mjs).
|
|
473
|
+
const jestRequire = () => (channel.jestRequireDepth ?? 0) > 0;
|
|
474
|
+
|
|
475
|
+
// Every module Node's CommonJS loader evaluates, reported by the engine's dispatcher once
|
|
476
|
+
// it has loaded: CommonJS, require() of an ES module, and JSON. A copy whose evaluation
|
|
477
|
+
// throws is not reported: Node drops it from its cache, so it leaves no twin. In error
|
|
478
|
+
// mode the require fails here, after Node's copy ran.
|
|
479
|
+
nodeDispatch().onNodeEvaluation(({ filename, module, via }) => {
|
|
480
|
+
try {
|
|
481
|
+
ledger.recordNode(
|
|
482
|
+
filename,
|
|
483
|
+
{
|
|
484
|
+
via,
|
|
485
|
+
ref: new WeakRef(module),
|
|
486
|
+
cacheKey: filename,
|
|
487
|
+
// A string, so the record holds nothing alive. DEP0144 is documentation-only.
|
|
488
|
+
parent: module.parent?.filename,
|
|
489
|
+
jestRequire: jestRequire(),
|
|
490
|
+
},
|
|
491
|
+
{ key: keyOf(filename) },
|
|
492
|
+
);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
// Error mode refused Node's copy after it loaded: take it out of Node's cache, as
|
|
495
|
+
// Node does for a module that throws, so no later require is handed it.
|
|
496
|
+
if (Module._cache[filename] === module) delete Module._cache[filename];
|
|
497
|
+
throw error;
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
const fileOf = (url) => {
|
|
502
|
+
if (typeof url !== "string" || !url.startsWith("file:")) return null;
|
|
503
|
+
try {
|
|
504
|
+
return fileURLToPath(url);
|
|
505
|
+
} catch {
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
// True ESM, from loader.mjs's load hook in this thread, before Node evaluates it.
|
|
510
|
+
channel.nodeEsm = (url) => {
|
|
511
|
+
const file = fileOf(url);
|
|
512
|
+
if (file === null) return;
|
|
513
|
+
const stamp = /[?&]vnhot=(\d+)/.exec(url);
|
|
514
|
+
ledger.recordNode(
|
|
515
|
+
file,
|
|
516
|
+
{ via: "esm", generation: stamp ? Number(stamp[1]) : null },
|
|
517
|
+
{ key: keyOf(file) },
|
|
518
|
+
);
|
|
519
|
+
};
|
|
520
|
+
// The marker viteMarkerFor writes into each module Vite evaluates.
|
|
521
|
+
channel.vite = (key, file) => ledger.recordVite(key, file);
|
|
522
|
+
channel.ledger = ledger;
|
|
523
|
+
return ledger;
|
|
524
|
+
}
|
|
@@ -82,6 +82,8 @@ export interface NativeOwnershipOptions {
|
|
|
82
82
|
/** Files Vitest runs as entries without a test-file name: the project's `test.setupFiles`. */
|
|
83
83
|
entryFiles?: string[];
|
|
84
84
|
serverDepsInlineAll?: boolean;
|
|
85
|
+
/** An installed package's TypeScript source is Node's (#544); default: the context's nodeMocks. */
|
|
86
|
+
installedTypeScriptToNode?: boolean;
|
|
85
87
|
/** How each package's directory is found; defaults to `packageDirOf` (match.mjs). */
|
|
86
88
|
packageDirOf?: (name: string, fromDir: string) => string | null;
|
|
87
89
|
}
|
|
@@ -98,6 +100,21 @@ export declare function isResidentPackageName(name: string): boolean;
|
|
|
98
100
|
export declare function createNativeOwnershipPolicy(
|
|
99
101
|
options?: NativeOwnershipOptions,
|
|
100
102
|
): NativeOwnershipPolicy;
|
|
103
|
+
export declare function recordedPackageDirOf(
|
|
104
|
+
recorded: { root: string; dirs: Record<string, string | null> } | undefined,
|
|
105
|
+
resolve?: (name: string, fromDir: string) => string | null,
|
|
106
|
+
): (name: string, fromDir: string) => string | null;
|
|
107
|
+
export declare function workerOwnershipPolicy(
|
|
108
|
+
inputs: {
|
|
109
|
+
projectRoot: string;
|
|
110
|
+
projectDirs?: readonly string[];
|
|
111
|
+
reactNativeRoots?: readonly string[];
|
|
112
|
+
serverDepsInlineAll?: boolean;
|
|
113
|
+
runtimeTransforms?: readonly string[];
|
|
114
|
+
},
|
|
115
|
+
context?: { packageDirs?: { root: string; dirs: Record<string, string | null> } } | null,
|
|
116
|
+
): NativeOwnershipPolicy;
|
|
117
|
+
export declare function workerOwnershipPolicyBuilds(): number;
|
|
101
118
|
export declare function findNativeOwnershipConflict(
|
|
102
119
|
policy: NativeOwnershipPolicy,
|
|
103
120
|
file: string,
|
|
@@ -113,3 +130,6 @@ export declare function parseNativeOwnershipManifest(
|
|
|
113
130
|
export declare function formatNativeOwnershipManifest(
|
|
114
131
|
manifest: NativeOwnershipManifest | string | unknown,
|
|
115
132
|
): string[];
|
|
133
|
+
|
|
134
|
+
/** TypeScript source under node_modules (not a declaration file): #544's rule. */
|
|
135
|
+
export declare const INSTALLED_TYPESCRIPT: RegExp;
|