vitest-native 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +731 -0
- package/README.md +32 -1
- package/dist/cli.cjs +163 -27
- package/dist/cli.mjs +162 -26
- package/dist/{ecosystem-EFtHnKS9.mjs → ecosystem-CO5vqExO.mjs} +77 -15
- package/dist/{ecosystem-BIWaVwYL.cjs → ecosystem-IuZ-Gv0R.cjs} +78 -16
- package/dist/errors-Dm5yLNTF.mjs +64 -0
- package/dist/errors-flXDIeWk.cjs +75 -0
- package/dist/errors.d.mts +46 -0
- package/dist/errors.mjs +78 -0
- package/dist/helpers.cjs +6 -23
- package/dist/helpers.d.cts +0 -6
- package/dist/helpers.d.mts +0 -6
- package/dist/helpers.mjs +6 -23
- package/dist/{index-CEgRDdhd.d.cts → index-BJL4cQ-l.d.cts} +9 -4
- package/dist/{index-j-0tueBr.d.mts → index-CvCU0cLl.d.mts} +9 -4
- package/dist/index.d.mts +8 -6
- package/dist/index.mjs +245 -59
- package/dist/jest-compat/interop.mjs +15 -0
- package/dist/jest-compat/setup.mjs +102 -7
- package/dist/matchers.cjs +16 -7
- package/dist/matchers.mjs +16 -7
- package/dist/native/hooks.mjs +75 -1
- package/dist/native/loader.mjs +26 -6
- package/dist/native/module-reset.mjs +63 -0
- package/dist/native/registry.mjs +80 -11
- package/dist/native/resolve.d.mts +22 -0
- package/dist/native/resolve.mjs +21 -13
- package/dist/native/runner.mjs +21 -0
- package/dist/native/setup.mjs +4 -2
- package/dist/native/transform.mjs +108 -3
- package/dist/native/worker.mjs +59 -16
- package/dist/{pool-CJmjRgsB.mjs → pool-Bcxp4Qrg.mjs} +2 -1
- package/dist/{pool-DzsEo9vv.cjs → pool-CFND7plG.cjs} +2 -1
- package/dist/{preset-map-CNsZKfvu.mjs → preset-map-BpDG_D5m.mjs} +0 -1
- package/dist/{preset-map-CG4FMtsl.cjs → preset-map-DxilQ4pI.cjs} +0 -1
- package/dist/{presets-C4faM3ds.cjs → presets-BGTqVH6C.cjs} +94 -50
- package/dist/{presets-CuDrNA_W.mjs → presets-CK85x8ey.mjs} +94 -50
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/rntl-matchers.d.ts +35 -0
- package/dist/serializer.cjs +33 -3
- package/dist/serializer.mjs +33 -3
- package/dist/setup.mjs +234 -71
- package/docs/release-readiness.md +22 -5
- package/docs/versioning.md +133 -0
- package/package.json +25 -35
- package/dist/index.cjs +0 -788
- package/dist/index.d.cts +0 -14
- package/dist/presets.cjs +0 -18
- package/dist/presets.d.cts +0 -2
- package/dist/setup.cjs +0 -2702
- package/dist/setup.d.cts +0 -1
|
@@ -13,8 +13,10 @@
|
|
|
13
13
|
// `jest.useFakeTimers` work at runtime via the `jest` global installed here.
|
|
14
14
|
import { vi } from "vitest";
|
|
15
15
|
import { createRequire } from "node:module";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
16
17
|
import path from "node:path";
|
|
17
18
|
import { jestMockInterop } from "./interop.mjs";
|
|
19
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
18
20
|
|
|
19
21
|
// Resolve modules from the consumer project root, not this file's location, so
|
|
20
22
|
// `jest.requireActual('some-project-dep')` resolves the same module the suite sees.
|
|
@@ -43,12 +45,68 @@ function writableModuleFacade(mod) {
|
|
|
43
45
|
});
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
/**
|
|
49
|
+
* The file that called into here, taken from the stack.
|
|
50
|
+
*
|
|
51
|
+
* Jest resolves a relative `requireActual('../x')` against the CALLING module. This
|
|
52
|
+
* shim had a single require anchored at the project root, so bare specifiers worked
|
|
53
|
+
* and relative ones escaped the source tree: `jest.requireActual('../thing')` threw
|
|
54
|
+
* MODULE_NOT_FOUND with a requireStack pointing at <projectRoot>/package.json, which
|
|
55
|
+
* is a confusing place to be sent when the file sits next to the test.
|
|
56
|
+
*
|
|
57
|
+
* The stack is the only thing that knows the caller. These are plain runtime calls
|
|
58
|
+
* on the `jest` global, not rewritten at transform time, so there is no import.meta
|
|
59
|
+
* to consult.
|
|
60
|
+
*/
|
|
61
|
+
function callerFile() {
|
|
62
|
+
const original = Error.prepareStackTrace;
|
|
63
|
+
try {
|
|
64
|
+
Error.prepareStackTrace = (_, frames) => frames;
|
|
65
|
+
const frames = new Error().stack;
|
|
66
|
+
for (const frame of frames) {
|
|
67
|
+
const file = typeof frame.getFileName === "function" ? frame.getFileName() : null;
|
|
68
|
+
if (!file || file.startsWith("node:") || file.includes("/jest-compat/")) continue;
|
|
69
|
+
return file.startsWith("file://") ? fileURLToPath(file) : file;
|
|
70
|
+
}
|
|
71
|
+
} catch {
|
|
72
|
+
// Fall through to the project-root require below.
|
|
73
|
+
} finally {
|
|
74
|
+
Error.prepareStackTrace = original;
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Resolve as Jest does: relative against the caller, bare from the project root. */
|
|
80
|
+
function requireFrom(specifier) {
|
|
81
|
+
if (typeof specifier === "string" && specifier.startsWith(".")) {
|
|
82
|
+
const caller = callerFile();
|
|
83
|
+
// A caller-relative miss is the honest answer. Falling back to the project root
|
|
84
|
+
// could resolve some other file that happens to sit at the same relative path.
|
|
85
|
+
if (caller) return createRequire(caller)(specifier);
|
|
86
|
+
}
|
|
87
|
+
return require(specifier);
|
|
88
|
+
}
|
|
89
|
+
|
|
46
90
|
if (typeof vi.requireActual !== "function")
|
|
47
|
-
vi.requireActual = (m) =>
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
//
|
|
51
|
-
|
|
91
|
+
vi.requireActual = (m) =>
|
|
92
|
+
m === "react-native" ? writableModuleFacade(require(m)) : requireFrom(m);
|
|
93
|
+
if (typeof vi.requireMock !== "function") vi.requireMock = (m) => requireFrom(m);
|
|
94
|
+
// `jest.setTimeout(ms)` maps onto `vi.setConfig({ testTimeout })`, which applies for
|
|
95
|
+
// the rest of the file — the same scope Jest gives it, since Vitest resets the config
|
|
96
|
+
// after each test file.
|
|
97
|
+
//
|
|
98
|
+
// This used to be a silent no-op, on the grounds that there was no `vi` equivalent.
|
|
99
|
+
// There is. The cost of the no-op was not a crash but silence: a suite opening with
|
|
100
|
+
// `jest.setTimeout(30000)`, which is routine for slower React Native suites, kept
|
|
101
|
+
// Vitest's 5s default and its slow tests failed on time while the line that was
|
|
102
|
+
// supposed to prevent that sat there looking effective.
|
|
103
|
+
if (typeof vi.setTimeout !== "function") {
|
|
104
|
+
vi.setTimeout = (ms) => {
|
|
105
|
+
if (typeof vi.setConfig === "function" && typeof ms === "number") {
|
|
106
|
+
vi.setConfig({ testTimeout: ms });
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
52
110
|
|
|
53
111
|
// `jest.advanceTimersByTime(Async)` is lenient in Jest: when fake timers are NOT
|
|
54
112
|
// active it's effectively a no-op. Vitest's `vi.advanceTimersByTimeAsync` instead
|
|
@@ -65,6 +123,20 @@ vi.advanceTimersByTime = (...args) =>
|
|
|
65
123
|
vi.advanceTimersByTimeAsync = async (...args) =>
|
|
66
124
|
vi.isFakeTimers() ? advanceTimersByTimeAsync(...args) : undefined;
|
|
67
125
|
|
|
126
|
+
// Jest APIs that DO have a Vitest equivalent, under a different name. Each of these
|
|
127
|
+
// was missing, so a suite calling it hit `jest.X is not a function` — the bare
|
|
128
|
+
// TypeError the signposting below exists to avoid — even though the behaviour was
|
|
129
|
+
// available all along. `dontMock` is the sibling of the already-signposted
|
|
130
|
+
// `deepUnmock`, which is what marks these as omissions rather than decisions.
|
|
131
|
+
if (typeof vi.dontMock !== "function") vi.dontMock = (m) => vi.doUnmock(m);
|
|
132
|
+
if (typeof vi.setMock !== "function") vi.setMock = (m, exports) => vi.doMock(m, () => exports);
|
|
133
|
+
// `Date.now()` alone is right for both clocks: Vitest's fake timers replace Date, so
|
|
134
|
+
// this returns the faked time when they are active and the real time otherwise —
|
|
135
|
+
// which is what jest.now() reports. An earlier version consulted
|
|
136
|
+
// vi.getMockedSystemTime() first; removing that branch changed no observable
|
|
137
|
+
// behaviour, so it was complexity no test could distinguish.
|
|
138
|
+
if (typeof vi.now !== "function") vi.now = () => Date.now();
|
|
139
|
+
|
|
68
140
|
// Jest APIs with NO Vitest equivalent would otherwise surface as bare
|
|
69
141
|
// "jest.isolateModules is not a function" TypeErrors deep in a migrated suite.
|
|
70
142
|
// Give each one an error that names the API and states the closest migration,
|
|
@@ -74,8 +146,10 @@ const MIGRATION_GUIDE =
|
|
|
74
146
|
function unsupported(name, guidance) {
|
|
75
147
|
if (typeof vi[name] === "function") return;
|
|
76
148
|
vi[name] = () => {
|
|
77
|
-
throw new
|
|
78
|
-
|
|
149
|
+
throw new VitestNativeError(
|
|
150
|
+
"JEST_API_UNSUPPORTED",
|
|
151
|
+
`jest.${name}() has no Vitest equivalent. ${guidance}`,
|
|
152
|
+
{ docs: MIGRATION_GUIDE },
|
|
79
153
|
);
|
|
80
154
|
};
|
|
81
155
|
}
|
|
@@ -92,6 +166,27 @@ unsupported(
|
|
|
92
166
|
"Build the mock explicitly with vi.fn()/vi.mock(), or import the real module and override members.",
|
|
93
167
|
);
|
|
94
168
|
unsupported("deepUnmock", "Use vi.unmock()/vi.doUnmock() per module.");
|
|
169
|
+
unsupported(
|
|
170
|
+
"isolateModulesAsync",
|
|
171
|
+
"Use vi.resetModules() plus a dynamic import() to get a fresh module copy.",
|
|
172
|
+
);
|
|
173
|
+
unsupported("unstable_mockModule", "Use vi.doMock(path, factory), which mocks ESM too.");
|
|
174
|
+
unsupported(
|
|
175
|
+
"replaceProperty",
|
|
176
|
+
"Assign the property and restore it yourself, or use vi.spyOn(obj, key, 'get') for an accessor.",
|
|
177
|
+
);
|
|
178
|
+
// Vitest has no automocking at all, so these cannot be approximated — the whole
|
|
179
|
+
// premise (every module auto-replaced with mocks) does not exist. Naming that is more
|
|
180
|
+
// useful than a TypeError.
|
|
181
|
+
for (const name of [
|
|
182
|
+
"enableAutomock",
|
|
183
|
+
"disableAutomock",
|
|
184
|
+
"autoMockOff",
|
|
185
|
+
"autoMockOn",
|
|
186
|
+
"onGenerateMock",
|
|
187
|
+
]) {
|
|
188
|
+
unsupported(name, "Vitest has no automocking; mock each module explicitly with vi.mock().");
|
|
189
|
+
}
|
|
95
190
|
// jest.retryTimes configures retries at runtime; Vitest configures them statically.
|
|
96
191
|
// Warn once and continue — crashing a suite over retry policy helps nobody.
|
|
97
192
|
if (typeof vi.retryTimes !== "function") {
|
package/dist/matchers.cjs
CHANGED
|
@@ -15,11 +15,20 @@ function getProps(received) {
|
|
|
15
15
|
}
|
|
16
16
|
return null;
|
|
17
17
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
/**
|
|
19
|
+
* THROWS for a value that is not a rendered element — it does not return
|
|
20
|
+
* `{ pass: false }`.
|
|
21
|
+
*
|
|
22
|
+
* Returning a failing result reads as the safe option and is not: under `.not` the
|
|
23
|
+
* result is inverted, so `expect(null).not.toHaveAnimatedStyle({ opacity: 1 })`
|
|
24
|
+
* SILENTLY PASSED. A query that matched nothing, or a value of the wrong shape, then
|
|
25
|
+
* produced a green assertion — the failure mode a matcher must never have.
|
|
26
|
+
*
|
|
27
|
+
* Throwing also matches React Native Testing Library, whose `checkHostElement` raises
|
|
28
|
+
* a HostElementTypeError for the same case rather than failing softly.
|
|
29
|
+
*/
|
|
30
|
+
function throwNotAnElement(ctx, matcherName, received) {
|
|
31
|
+
throw new Error(`${ctx.utils.matcherHint(`${ctx.isNot ? ".not." : ""}${matcherName}`, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`);
|
|
23
32
|
}
|
|
24
33
|
/** Pick only the keys present in `expected` from `actual`, for readable diffs. */
|
|
25
34
|
function subset(actual, expected) {
|
|
@@ -29,7 +38,7 @@ function subset(actual, expected) {
|
|
|
29
38
|
}
|
|
30
39
|
function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
31
40
|
const props = getProps(received);
|
|
32
|
-
if (!props)
|
|
41
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedStyle", received);
|
|
33
42
|
const currentStyle = flattenStyle(props.style);
|
|
34
43
|
const compared = config.shouldMatchAllProps ? currentStyle : subset(currentStyle, expectedStyle);
|
|
35
44
|
const pass = this.equals(compared, expectedStyle);
|
|
@@ -45,7 +54,7 @@ function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
|
45
54
|
}
|
|
46
55
|
function toHaveAnimatedProps(received, expectedProps) {
|
|
47
56
|
const props = getProps(received);
|
|
48
|
-
if (!props)
|
|
57
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedProps", received);
|
|
49
58
|
const compared = subset(props.animatedProps && typeof props.animatedProps === "object" ? props.animatedProps : props, expectedProps);
|
|
50
59
|
const pass = this.equals(compared, expectedProps);
|
|
51
60
|
return {
|
package/dist/matchers.mjs
CHANGED
|
@@ -14,11 +14,20 @@ function getProps(received) {
|
|
|
14
14
|
}
|
|
15
15
|
return null;
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
17
|
+
/**
|
|
18
|
+
* THROWS for a value that is not a rendered element — it does not return
|
|
19
|
+
* `{ pass: false }`.
|
|
20
|
+
*
|
|
21
|
+
* Returning a failing result reads as the safe option and is not: under `.not` the
|
|
22
|
+
* result is inverted, so `expect(null).not.toHaveAnimatedStyle({ opacity: 1 })`
|
|
23
|
+
* SILENTLY PASSED. A query that matched nothing, or a value of the wrong shape, then
|
|
24
|
+
* produced a green assertion — the failure mode a matcher must never have.
|
|
25
|
+
*
|
|
26
|
+
* Throwing also matches React Native Testing Library, whose `checkHostElement` raises
|
|
27
|
+
* a HostElementTypeError for the same case rather than failing softly.
|
|
28
|
+
*/
|
|
29
|
+
function throwNotAnElement(ctx, matcherName, received) {
|
|
30
|
+
throw new Error(`${ctx.utils.matcherHint(`${ctx.isNot ? ".not." : ""}${matcherName}`, "element", "expected")}\n\nExpected a rendered element with a \`props\` object, but received:\n ${ctx.utils.printReceived(received)}`);
|
|
22
31
|
}
|
|
23
32
|
/** Pick only the keys present in `expected` from `actual`, for readable diffs. */
|
|
24
33
|
function subset(actual, expected) {
|
|
@@ -28,7 +37,7 @@ function subset(actual, expected) {
|
|
|
28
37
|
}
|
|
29
38
|
function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
30
39
|
const props = getProps(received);
|
|
31
|
-
if (!props)
|
|
40
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedStyle", received);
|
|
32
41
|
const currentStyle = flattenStyle(props.style);
|
|
33
42
|
const compared = config.shouldMatchAllProps ? currentStyle : subset(currentStyle, expectedStyle);
|
|
34
43
|
const pass = this.equals(compared, expectedStyle);
|
|
@@ -44,7 +53,7 @@ function toHaveAnimatedStyle(received, expectedStyle, config = {}) {
|
|
|
44
53
|
}
|
|
45
54
|
function toHaveAnimatedProps(received, expectedProps) {
|
|
46
55
|
const props = getProps(received);
|
|
47
|
-
if (!props)
|
|
56
|
+
if (!props) throwNotAnElement(this, "toHaveAnimatedProps", received);
|
|
48
57
|
const compared = subset(props.animatedProps && typeof props.animatedProps === "object" ? props.animatedProps : props, expectedProps);
|
|
49
58
|
const pass = this.equals(compared, expectedProps);
|
|
50
59
|
return {
|
package/dist/native/hooks.mjs
CHANGED
|
@@ -20,6 +20,78 @@ const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
|
20
20
|
// can be evaluated twice in one worker (once by the worker entry through Node's
|
|
21
21
|
// loader, once through Vitest's module runner when the setup file is inlined),
|
|
22
22
|
// and the hooks must still install exactly once per worker.
|
|
23
|
+
/**
|
|
24
|
+
* Packages Vite executes itself (see ecosystem.ts). If Node also resolves one of
|
|
25
|
+
* these, the module exists TWICE in the process — once in Vite's graph, once in
|
|
26
|
+
* Node's — and module-level state does not cross between them.
|
|
27
|
+
*
|
|
28
|
+
* This is silent by construction: nothing fails, nothing is logged, the second
|
|
29
|
+
* copy simply starts empty. A store configured through one copy reads back
|
|
30
|
+
* unset through the other, so a translated label renders as "" and the test
|
|
31
|
+
* compares empty output against expected output with nothing pointing at the
|
|
32
|
+
* cause. Reported once per package, with both files, because the two paths are
|
|
33
|
+
* what makes it recognisable.
|
|
34
|
+
*/
|
|
35
|
+
// The fields Vite is configured with for React Native (see plugin.ts), in order.
|
|
36
|
+
// Node's CJS resolver uses `main`, which is not in this list at all.
|
|
37
|
+
const VITE_MAIN_FIELDS = ["react-native", "module", "jsnext:main", "jsnext"];
|
|
38
|
+
|
|
39
|
+
const reportedDuplicates = new Set();
|
|
40
|
+
|
|
41
|
+
/** Test seam: the warning is once per package for the life of the worker. */
|
|
42
|
+
export function _resetDuplicateReports() {
|
|
43
|
+
reportedDuplicates.clear();
|
|
44
|
+
}
|
|
45
|
+
function reportDuplicateInstance(pkg, nodeFile, viteFile, field) {
|
|
46
|
+
reportedDuplicates.add(pkg);
|
|
47
|
+
console.warn(
|
|
48
|
+
`[vitest-native] '${pkg}' resolves to two different files.\n` +
|
|
49
|
+
` Node (require) -> ${nodeFile}\n` +
|
|
50
|
+
` Vite ("${field}") -> ${viteFile}\n` +
|
|
51
|
+
" If both module systems load it, the package exists twice and module-level state —\n" +
|
|
52
|
+
" stores, React contexts, event emitters, registries — is not shared between the copies.\n" +
|
|
53
|
+
" Nothing throws: writes through one are simply invisible to the other, so values read\n" +
|
|
54
|
+
" back unset. Set `resolve.mainFields` so both resolvers agree, or import the package\n" +
|
|
55
|
+
" from one side only.",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Compare what Node just resolved against what Vite's field order would pick for
|
|
61
|
+
* the same package. A difference means the two module systems have different
|
|
62
|
+
* files for one package id, so anything importing it from both sides gets two
|
|
63
|
+
* copies with separate state.
|
|
64
|
+
*/
|
|
65
|
+
export function checkResolverAgreement(request, resolved) {
|
|
66
|
+
const pkg = packageOf(request);
|
|
67
|
+
if (!pkg || typeof resolved !== "string") return;
|
|
68
|
+
if (reportedDuplicates.has(pkg)) return;
|
|
69
|
+
const marker = `${path.sep}node_modules${path.sep}`;
|
|
70
|
+
const at = resolved.lastIndexOf(marker + pkg.split("/").join(path.sep) + path.sep);
|
|
71
|
+
if (at === -1) return;
|
|
72
|
+
const dir = resolved.slice(0, at + marker.length + pkg.length);
|
|
73
|
+
let manifest;
|
|
74
|
+
try {
|
|
75
|
+
manifest = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
|
|
76
|
+
} catch {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const field = VITE_MAIN_FIELDS.find((f) => typeof manifest[f] === "string");
|
|
80
|
+
if (!field) return;
|
|
81
|
+
const viteFile = path.resolve(dir, manifest[field]);
|
|
82
|
+
if (viteFile === resolved) return;
|
|
83
|
+
reportDuplicateInstance(pkg, resolved, viteFile, field);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The npm package a bare specifier belongs to, or null for relative/absolute ones. */
|
|
87
|
+
function packageOf(request) {
|
|
88
|
+
if (!request || request.startsWith(".") || request.startsWith("/") || request.startsWith("\\")) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const parts = request.split("/");
|
|
92
|
+
return request.startsWith("@") ? (parts[1] ? `${parts[0]}/${parts[1]}` : null) : parts[0];
|
|
93
|
+
}
|
|
94
|
+
|
|
23
95
|
export function installRequireHooks(
|
|
24
96
|
projectRoot,
|
|
25
97
|
transformPkgs = [],
|
|
@@ -137,7 +209,9 @@ export function installRequireHooks(
|
|
|
137
209
|
);
|
|
138
210
|
if (hit) return hit;
|
|
139
211
|
}
|
|
140
|
-
|
|
212
|
+
const resolved = origResolve.call(this, request, parent, ...rest);
|
|
213
|
+
checkResolverAgreement(request, resolved);
|
|
214
|
+
return resolved;
|
|
141
215
|
};
|
|
142
216
|
|
|
143
217
|
const origJs = Module._extensions[".js"];
|
package/dist/native/loader.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
6
|
-
import { transformRN, isFlow } from "./transform.mjs";
|
|
6
|
+
import { transformRN, isFlow, cjsExportNames } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
8
|
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
9
|
import { buildPkgMatcher, packageNameOf, subpathLeafOf, isUtilitySubpath } from "./match.mjs";
|
|
@@ -87,6 +87,7 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
87
87
|
context.parentURL && context.parentURL.startsWith("file:")
|
|
88
88
|
? fileURLToPath(context.parentURL)
|
|
89
89
|
: null;
|
|
90
|
+
let resolved;
|
|
90
91
|
if (
|
|
91
92
|
parent &&
|
|
92
93
|
(NODE_MODULES.test(parent) || RN_PATH.test(parent) || isExtra(parent)) &&
|
|
@@ -94,12 +95,13 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
94
95
|
!path.extname(specifier)
|
|
95
96
|
) {
|
|
96
97
|
const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier), PLATFORM);
|
|
97
|
-
|
|
98
|
+
// Not returned directly: `json` is a Metro source extension, so this can now
|
|
99
|
+
// land on a .json file, which still needs the import attribute injected below.
|
|
100
|
+
if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
98
101
|
}
|
|
99
102
|
|
|
100
|
-
let resolved;
|
|
101
103
|
try {
|
|
102
|
-
resolved
|
|
104
|
+
resolved ??= await nextResolve(specifier, context);
|
|
103
105
|
} catch (err) {
|
|
104
106
|
// Fallback: an extensionless relative import that Node's ESM resolver rejected
|
|
105
107
|
// but a bundler (Metro) would accept. Common in externalized RN libs shipping
|
|
@@ -222,12 +224,30 @@ export async function load(url, context, nextLoad) {
|
|
|
222
224
|
return nextLoad(url, context);
|
|
223
225
|
}
|
|
224
226
|
|
|
225
|
-
// Configured third-party package: transform any JS/TS/JSX source to CJS
|
|
227
|
+
// Configured third-party package: transform any JS/TS/JSX source to CJS, and tell
|
|
228
|
+
// Node what it exports.
|
|
229
|
+
//
|
|
230
|
+
// When Node imports a CommonJS module from ESM it decides the named exports with
|
|
231
|
+
// cjs-module-lexer, which reads the source statically and gives up partway through
|
|
232
|
+
// shapes it cannot follow. `module.exports = { A() {}, b: () => 1 }` — ordinary
|
|
233
|
+
// hand-written CommonJS, and common in this ecosystem — yields
|
|
234
|
+
// ["A", "default", "module.exports"]: `b` is missing and a name that is not an
|
|
235
|
+
// export appears. Plain Node behaviour, reproducible with no plugin involved; it
|
|
236
|
+
// became reachable when these packages moved from Vite's graph (whose interop
|
|
237
|
+
// enumerates the real object at run time) to Node's.
|
|
238
|
+
//
|
|
239
|
+
// The dead `0 && (module.exports = { … })` hint is the form the lexer does
|
|
240
|
+
// understand — the same trick react-native's index facade uses below. Names are
|
|
241
|
+
// read from the transform's own output rather than by requiring the module: this
|
|
242
|
+
// hook runs on the module-loader thread, where the CJS require hooks that compile
|
|
243
|
+
// JSX are not installed, so a require here fails with "Unexpected token '<'".
|
|
226
244
|
if (TRANSFORMABLE.test(norm)) {
|
|
227
245
|
const src = fs.readFileSync(file, "utf8");
|
|
246
|
+
const code = transformRN(file, src, PROJECT_ROOT, PLATFORM);
|
|
247
|
+
const names = cjsExportNames(code);
|
|
228
248
|
return {
|
|
229
249
|
format: "commonjs",
|
|
230
|
-
source:
|
|
250
|
+
source: names.length > 0 ? `${code}\n0 && (module.exports = { ${names.join(", ")} });` : code,
|
|
231
251
|
shortCircuit: true,
|
|
232
252
|
};
|
|
233
253
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Per-file reset of the worker's Node module graph (hot runtime).
|
|
2
|
+
//
|
|
3
|
+
// The hot runtime keeps a worker alive across test files — that is where its speed
|
|
4
|
+
// comes from, since a fresh worker costs ~200ms of boot and that dominates a run at
|
|
5
|
+
// scale. What it must not keep is state. Vitest's own per-file reset covers the
|
|
6
|
+
// module-runner graph; everything Vitest externalizes lives in Node's require cache,
|
|
7
|
+
// outside its reach.
|
|
8
|
+
//
|
|
9
|
+
// Anything the worker loaded to bootstrap ITSELF stays; anything a TEST FILE caused
|
|
10
|
+
// to load is dropped and runs again on the next file.
|
|
11
|
+
import Module from "node:module";
|
|
12
|
+
|
|
13
|
+
// Native addons cannot be unloaded — dropping one and requiring it again
|
|
14
|
+
// re-initialises native state in the same process, which crashes some addons.
|
|
15
|
+
const UNRESETTABLE = /\.node$/;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Modules that must NOT be dropped, because dropping them creates a second copy
|
|
19
|
+
* rather than a fresh one.
|
|
20
|
+
*
|
|
21
|
+
* Test files reach these through ESM `import`, which caches them in Node's ESM
|
|
22
|
+
* registry — and that registry has no invalidation API, so the copy a test holds
|
|
23
|
+
* survives any reset. Dropping the CJS entry therefore does not replace the module;
|
|
24
|
+
* it adds a twin, and the two halves of the test stack stop recognising each other.
|
|
25
|
+
* The symptom is not an error about modules: it is RNTL's matchers failing to see
|
|
26
|
+
* elements that a resident renderer produced.
|
|
27
|
+
*
|
|
28
|
+
* Which entries carry weight depends on the RNTL version, so the list is bisected
|
|
29
|
+
* rather than assumed. Measured one entry at a time:
|
|
30
|
+
*
|
|
31
|
+
* @testing-library/react-native RNTL 14: parity 135/135 -> 81/135, 10.4x -> 7.8x.
|
|
32
|
+
* The dominant case on every version.
|
|
33
|
+
* react-test-renderer, RNTL 13: `test:native:hot` 175 -> 173 passing.
|
|
34
|
+
* test-renderer RNTL 14 does not use them and is unaffected —
|
|
35
|
+
* which is why a single-version check calls them
|
|
36
|
+
* dead and is wrong.
|
|
37
|
+
* react, react-is, react-dom, No measured effect on either suite under RNTL 13
|
|
38
|
+
* scheduler, react-reconciler or 14: React is already loaded by the worker's
|
|
39
|
+
* boot-time RN preload, so the baseline snapshot
|
|
40
|
+
* below protects it before this pattern is
|
|
41
|
+
* consulted. Kept because that protection is a
|
|
42
|
+
* side effect of preload contents, not a contract.
|
|
43
|
+
*
|
|
44
|
+
* Note for anyone re-testing this: the two suites disagree, so run both.
|
|
45
|
+
* `validate:hot-parity` is the only one that sees the RNTL regression (it is
|
|
46
|
+
* app-shaped rendering); `test:native:hot` is the only one that sees the
|
|
47
|
+
* react-test-renderer regression (it is engine mechanics).
|
|
48
|
+
*/
|
|
49
|
+
const KEEP_RESIDENT =
|
|
50
|
+
/[\\/]node_modules[\\/](react|react-is|react-dom|scheduler|react-reconciler|react-test-renderer|test-renderer|@testing-library[\\/]react-native)[\\/]/;
|
|
51
|
+
|
|
52
|
+
export function captureModuleBaseline() {
|
|
53
|
+
const baseline = new Set(Object.keys(Module._cache));
|
|
54
|
+
return function resetModules() {
|
|
55
|
+
let dropped = 0;
|
|
56
|
+
for (const id of Object.keys(Module._cache)) {
|
|
57
|
+
if (baseline.has(id) || UNRESETTABLE.test(id) || KEEP_RESIDENT.test(id)) continue;
|
|
58
|
+
delete Module._cache[id];
|
|
59
|
+
dropped++;
|
|
60
|
+
}
|
|
61
|
+
return dropped;
|
|
62
|
+
};
|
|
63
|
+
}
|
package/dist/native/registry.mjs
CHANGED
|
@@ -30,14 +30,63 @@ import { createRequire } from "node:module";
|
|
|
30
30
|
import path from "node:path";
|
|
31
31
|
import fs from "node:fs";
|
|
32
32
|
import crypto from "node:crypto";
|
|
33
|
-
import { transformRN, isFlow, cacheRootFor } from "./transform.mjs";
|
|
33
|
+
import { transformRN, isFlow, cacheRootFor, TRANSFORM_CACHE_VERSION } from "./transform.mjs";
|
|
34
|
+
|
|
34
35
|
import { boundarySourceFor, BOUNDARY_SOURCES } from "./boundary.mjs";
|
|
35
36
|
import { resolvePlatformFile } from "./resolve.mjs";
|
|
36
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Losing the registry is a silent performance cliff, not a correctness problem:
|
|
40
|
+
* React Native still loads, file by file, and nothing fails. Measured on this
|
|
41
|
+
* package's own native suite (~42 files), that costs roughly 1.4x — 1.8s becomes
|
|
42
|
+
* 2.5-2.8s — and the per-file cost compounds on a real app suite.
|
|
43
|
+
*
|
|
44
|
+
* Both failure paths used to return null in silence (the build path spoke only
|
|
45
|
+
* under `diagnostics`, the cache-directory path never spoke at all), so the
|
|
46
|
+
* fallback was indistinguishable from working normally. A precompile failure is
|
|
47
|
+
* exactly the kind of thing that happens on one machine and not another — it
|
|
48
|
+
* happened on a Windows CI runner while this was being reviewed, and reported
|
|
49
|
+
* nothing but a null.
|
|
50
|
+
*
|
|
51
|
+
* Reported once per distinct cause, so a project failing on both platforms says
|
|
52
|
+
* it once, while two different causes are both visible.
|
|
53
|
+
*/
|
|
54
|
+
const reportedRegistryFailures = new Set();
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Exported as a test seam. The shape of the underlying error depends on how the
|
|
58
|
+
* host resolves modules — under the package's own mock-engine test config,
|
|
59
|
+
* `react-native` is aliased to a virtual module and the failure is a one-line
|
|
60
|
+
* argument error, so a test driving `buildRegistry` there can never produce the
|
|
61
|
+
* multi-line "Require stack:" this collapses. Calling it directly is the only way
|
|
62
|
+
* to assert the collapse rather than assume the environment supplies one.
|
|
63
|
+
*/
|
|
64
|
+
export function _warnRegistryUnavailable(rawReason) {
|
|
65
|
+
warnRegistryUnavailable(rawReason);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function warnRegistryUnavailable(rawReason) {
|
|
69
|
+
// Node appends a "Require stack:" block to resolution failures; one line is
|
|
70
|
+
// enough to identify the cause without turning a warning into a wall of text.
|
|
71
|
+
const reason = String(rawReason).split("\n")[0].trim();
|
|
72
|
+
if (reportedRegistryFailures.has(reason)) return;
|
|
73
|
+
reportedRegistryFailures.add(reason);
|
|
74
|
+
console.warn(
|
|
75
|
+
`[vitest-native] (native) could not precompile the React Native registry (${reason}); ` +
|
|
76
|
+
"falling back to per-file module loading, which is slower. Tests still run and " +
|
|
77
|
+
"results are unaffected. Set VITEST_NATIVE_NO_REGISTRY=1 to opt out silently.",
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Test seam: the warning is once-per-cause for the life of the process. */
|
|
82
|
+
export function _resetRegistryFailureReports() {
|
|
83
|
+
reportedRegistryFailures.clear();
|
|
84
|
+
}
|
|
85
|
+
|
|
37
86
|
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
38
87
|
// Bump when the emitted registry's shape or the walk's semantics change, so a
|
|
39
88
|
// stale on-disk registry from an older vitest-native can never be reused.
|
|
40
|
-
const REGISTRY_FORMAT_VERSION =
|
|
89
|
+
const REGISTRY_FORMAT_VERSION = 2;
|
|
41
90
|
|
|
42
91
|
/**
|
|
43
92
|
* Literal `require('…')` / `require("…")` calls. The leading class excludes
|
|
@@ -111,8 +160,10 @@ function ownVersion() {
|
|
|
111
160
|
* This package's version is in the key for the same reason, covering everything
|
|
112
161
|
* else it contributes — the transform's Babel options, platform resolution, the
|
|
113
162
|
* emitted registry's own shape.
|
|
163
|
+
*
|
|
164
|
+
* Exported for tests. Not part of the public surface — see docs/versioning.md.
|
|
114
165
|
*/
|
|
115
|
-
function registryKey({ projectRoot, platform, reactNativeVersion }) {
|
|
166
|
+
export function registryKey({ projectRoot, platform, reactNativeVersion }) {
|
|
116
167
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
117
168
|
const version = (name) => {
|
|
118
169
|
try {
|
|
@@ -135,10 +186,28 @@ function registryKey({ projectRoot, platform, reactNativeVersion }) {
|
|
|
135
186
|
.update(
|
|
136
187
|
[
|
|
137
188
|
`f${REGISTRY_FORMAT_VERSION}`,
|
|
189
|
+
// The registry stores TRANSFORMED module source, so a change in what the
|
|
190
|
+
// transform emits must invalidate it. Nothing else here would: the preset and
|
|
191
|
+
// Babel versions are unchanged when the transform's own configuration changes,
|
|
192
|
+
// and ownVersion() is the published package version, which does not move during
|
|
193
|
+
// development. Adding the Flow-enum plugin produced exactly that situation — the
|
|
194
|
+
// transform was fixed and a warm registry kept serving modules built without it.
|
|
195
|
+
`t${TRANSFORM_CACHE_VERSION}`,
|
|
138
196
|
ownVersion(),
|
|
139
197
|
platform,
|
|
140
198
|
reactNativeVersion,
|
|
141
199
|
version("react-native"),
|
|
200
|
+
// React Native's modules resolve `react` at runtime, so the registry is only
|
|
201
|
+
// valid for the React it was built against. This was missing, and the manifest
|
|
202
|
+
// check below could not cover it: it stats React Native's own files, which do
|
|
203
|
+
// not change when React alone is upgraded. Upgrading React while staying on the
|
|
204
|
+
// same React Native therefore served a registry built against the previous one,
|
|
205
|
+
// and the suite failed with a null React dispatcher ("Cannot read properties of
|
|
206
|
+
// null (reading 'useContext')") plus React Native singletons that no longer
|
|
207
|
+
// compared equal — the duplicate-instance failure this cache exists to avoid.
|
|
208
|
+
// Reproduced by switching between two trees differing only in React's version;
|
|
209
|
+
// clearing node_modules/.cache/vitest-native was the only way out.
|
|
210
|
+
version("react"),
|
|
142
211
|
version("@react-native/babel-preset"),
|
|
143
212
|
version("@babel/core"),
|
|
144
213
|
process.env.BABEL_ENV || process.env.NODE_ENV || "none",
|
|
@@ -268,7 +337,7 @@ function emit(files, modules) {
|
|
|
268
337
|
`const __entry = __r(0);`,
|
|
269
338
|
`module.exports = __entry;`,
|
|
270
339
|
`Object.defineProperty(module.exports, "__vitestNativeRegistry", {`,
|
|
271
|
-
` value: { ids: __ids, load: __r, entry: __ids[0] },`,
|
|
340
|
+
` value: { ids: __ids, load: __r, entry: __ids[0], reset: () => { __m.length = 0; } },`,
|
|
272
341
|
` enumerable: false, configurable: true,`,
|
|
273
342
|
`});`,
|
|
274
343
|
];
|
|
@@ -305,6 +374,9 @@ export function buildRegistry({
|
|
|
305
374
|
assetExts = [],
|
|
306
375
|
diagnostics = false,
|
|
307
376
|
}) {
|
|
377
|
+
// See warnRegistryUnavailable: this is the one path that stays quiet, because
|
|
378
|
+
// the user asked for it.
|
|
379
|
+
//
|
|
308
380
|
// Escape hatch. The registry is transparent by design, but it is also the piece
|
|
309
381
|
// most likely to be implicated if a project sees something unexpected from React
|
|
310
382
|
// Native — so there is a way to take it out of the picture and get the per-file
|
|
@@ -323,7 +395,8 @@ export function buildRegistry({
|
|
|
323
395
|
key = registryKey({ projectRoot, platform, reactNativeVersion });
|
|
324
396
|
dir = path.join(cacheRootFor(projectRoot), "registry");
|
|
325
397
|
fs.mkdirSync(dir, { recursive: true });
|
|
326
|
-
} catch {
|
|
398
|
+
} catch (error) {
|
|
399
|
+
warnRegistryUnavailable(error?.message ?? "cache directory unavailable");
|
|
327
400
|
return null;
|
|
328
401
|
}
|
|
329
402
|
|
|
@@ -403,12 +476,7 @@ export function buildRegistry({
|
|
|
403
476
|
}
|
|
404
477
|
return registryFile;
|
|
405
478
|
} catch (error) {
|
|
406
|
-
|
|
407
|
-
console.warn(
|
|
408
|
-
`[vitest-native] (native) could not precompile the RN registry (${error?.message}); ` +
|
|
409
|
-
`falling back to per-file module loading.`,
|
|
410
|
-
);
|
|
411
|
-
}
|
|
479
|
+
warnRegistryUnavailable(error?.message ?? "unknown error");
|
|
412
480
|
return null;
|
|
413
481
|
}
|
|
414
482
|
}
|
|
@@ -440,6 +508,7 @@ export function installRegistry(registryFile, projectRoot) {
|
|
|
440
508
|
return false;
|
|
441
509
|
}
|
|
442
510
|
globalThis.__vitest_native_registry_installed = true;
|
|
511
|
+
globalThis.__vitest_native_registry_reset = () => registry.reset();
|
|
443
512
|
|
|
444
513
|
const idOf = new Map(registry.ids.map((f, i) => [f, i]));
|
|
445
514
|
const entryId = idOf.get(registry.entry);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for resolve.mjs. Hand-written because the implementation is plain .mjs: it
|
|
3
|
+
* is loaded verbatim by the Node-side require hook and ESM loader at run time.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Metro's default `sourceExts`, in Metro's own precedence order. */
|
|
7
|
+
export declare const METRO_SOURCE_EXTS: string[];
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Extensions to try for `platform`, in Metro's order: every platform-suffixed
|
|
11
|
+
* variant, then every `.native` one, then the bare extensions.
|
|
12
|
+
*/
|
|
13
|
+
export declare function extensionsFor(platform: "ios" | "android"): string[];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* First existing platform variant of an extensionless absolute base path, or its
|
|
17
|
+
* directory index, or null when nothing matches.
|
|
18
|
+
*/
|
|
19
|
+
export declare function resolvePlatformFile(
|
|
20
|
+
absBase: string,
|
|
21
|
+
platform?: "ios" | "android",
|
|
22
|
+
): string | null;
|