vitest-native 0.7.0 → 0.9.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 +373 -0
- package/README.md +32 -14
- package/dist/cli.cjs +506 -0
- package/dist/cli.d.cts +4 -0
- package/dist/cli.d.mts +4 -0
- package/dist/cli.mjs +502 -0
- package/dist/ecosystem-BIWaVwYL.cjs +294 -0
- package/dist/ecosystem-EFtHnKS9.mjs +256 -0
- package/dist/{index-DbfKy_bm.d.mts → index-CEgRDdhd.d.cts} +22 -3
- package/dist/{index-BgzErxHj.d.cts → index-j-0tueBr.d.mts} +20 -5
- package/dist/index.cjs +345 -200
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +341 -196
- package/dist/jest-compat/setup.mjs +65 -1
- package/dist/native/boundary.mjs +108 -30
- package/dist/native/compile-cache.mjs +45 -0
- package/dist/native/explain.mjs +69 -0
- package/dist/native/hooks.mjs +77 -4
- package/dist/native/loader.mjs +36 -7
- package/dist/native/match.mjs +107 -8
- package/dist/native/registry.mjs +471 -0
- package/dist/native/reset.mjs +18 -12
- package/dist/native/runner.mjs +13 -7
- package/dist/native/setup.mjs +44 -0
- package/dist/native/transform.mjs +88 -19
- package/dist/native/worker.mjs +13 -0
- package/dist/pool-CJmjRgsB.mjs +117 -0
- package/dist/pool-DzsEo9vv.cjs +121 -0
- package/dist/{preset-map-CNBOeqAu.cjs → preset-map-CG4FMtsl.cjs} +5 -1
- package/dist/{preset-map-C1UwEald.mjs → preset-map-CNsZKfvu.mjs} +5 -1
- package/dist/{presets-BTG8fiNF.cjs → presets-C4faM3ds.cjs} +838 -2
- package/dist/{presets-BFuAMwYQ.mjs → presets-CuDrNA_W.mjs} +761 -3
- package/dist/presets.cjs +5 -1
- package/dist/presets.d.cts +2 -2
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/setup.cjs +327 -347
- package/dist/setup.mjs +318 -338
- package/docs/hot-default-design.md +129 -0
- package/docs/migrating-from-jest.md +43 -7
- package/docs/migrating-from-vitest-react-native.md +1 -1
- package/docs/release-readiness.md +2 -1
- package/package.json +23 -7
- package/dist/pool-B7LBfcMQ.mjs +0 -67
- package/dist/pool-p54QV1dQ.cjs +0 -69
package/dist/native/match.mjs
CHANGED
|
@@ -1,9 +1,108 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
/** Escape a string for literal use inside a RegExp. */
|
|
5
|
+
function escapeRe(value) {
|
|
6
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The on-disk directory a package resolves to, or null.
|
|
11
|
+
*
|
|
12
|
+
* `pkg/package.json` is tried first because it names the package root exactly; some
|
|
13
|
+
* packages do not export it, so fall back to resolving the entry and walking up to
|
|
14
|
+
* the manifest that names them. Symlinked and workspace packages resolve to their
|
|
15
|
+
* real location, which is the whole point — see buildPkgMatcher.
|
|
16
|
+
*/
|
|
17
|
+
function packageDirOf(name, projectRoot) {
|
|
18
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
19
|
+
try {
|
|
20
|
+
return path.dirname(req.resolve(`${name}/package.json`));
|
|
21
|
+
} catch {}
|
|
22
|
+
let dir;
|
|
23
|
+
try {
|
|
24
|
+
dir = path.dirname(req.resolve(name));
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
for (;;) {
|
|
29
|
+
try {
|
|
30
|
+
if (createRequire(path.join(dir, "index.js"))("./package.json").name === name) return dir;
|
|
31
|
+
} catch {}
|
|
32
|
+
const parent = path.dirname(dir);
|
|
33
|
+
if (parent === dir) return null;
|
|
34
|
+
dir = parent;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Builds a predicate matching files that belong to any of the given packages.
|
|
40
|
+
*
|
|
41
|
+
* A bare `[/\]name[/\]` test — what this used to do — also matches any DIRECTORY
|
|
42
|
+
* that happens to share a package's name. A project folder called `expo`, or a source
|
|
43
|
+
* directory named after the library it implements, made every file beneath it look
|
|
44
|
+
* like third-party source to be compiled. That mis-compiled unrelated files, this
|
|
45
|
+
* package's own runtime among them.
|
|
46
|
+
*
|
|
47
|
+
* Anchoring on `node_modules` alone would fix that and break linked packages: a
|
|
48
|
+
* workspace or `file:` dependency resolves to its real path, which has no
|
|
49
|
+
* `node_modules` segment at all. So a file matches if it is either
|
|
50
|
+
*
|
|
51
|
+
* - inside the package's resolved directory (exact; covers workspace links, and
|
|
52
|
+
* stores like pnpm's and bun's), or
|
|
53
|
+
* - under `node_modules/<name>/` (covers additional copies of a package that the
|
|
54
|
+
* single resolution above cannot see, and projects where resolution fails).
|
|
55
|
+
*
|
|
56
|
+
* `projectRoot` is optional so existing callers keep working; without it only the
|
|
57
|
+
* `node_modules`-anchored rule applies.
|
|
58
|
+
*/
|
|
59
|
+
export function buildPkgMatcher(pkgs, projectRoot) {
|
|
60
|
+
const names = pkgs || [];
|
|
61
|
+
const anchored = names.map((p) => new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`));
|
|
62
|
+
const dirs = [];
|
|
63
|
+
if (projectRoot) {
|
|
64
|
+
for (const name of names) {
|
|
65
|
+
const dir = packageDirOf(name, projectRoot);
|
|
66
|
+
if (dir) dirs.push(dir.replace(/\\/g, "/").replace(/\/$/, "") + "/");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return (normPath) => {
|
|
70
|
+
if (anchored.some((re) => re.test(normPath))) return true;
|
|
71
|
+
if (dirs.length === 0) return false;
|
|
72
|
+
const norm = normPath.replace(/\\/g, "/");
|
|
73
|
+
return dirs.some((dir) => norm.startsWith(dir));
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The bare package name of an import specifier ("@scope/pkg/sub" → "@scope/pkg",
|
|
78
|
+
// "pkg/sub" → "pkg"). Relative/absolute specifiers yield strings that can never
|
|
79
|
+
// collide with a package name, so callers only need an equality check.
|
|
80
|
+
export function packageNameOf(specifier) {
|
|
81
|
+
if (specifier.startsWith("@")) {
|
|
82
|
+
const [scope, name] = specifier.split("/");
|
|
83
|
+
return name ? `${scope}/${name}` : specifier;
|
|
84
|
+
}
|
|
85
|
+
return specifier.split("/")[0];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// The leaf module name a subpath import points at ("pkg/lib/Swipeable" or
|
|
89
|
+
// "pkg/Swipeable.ios.js" → "Swipeable"), used to pick the matching export off a
|
|
90
|
+
// preset/RN mock. Returns null when there is no usable leaf (trailing slash).
|
|
91
|
+
export function subpathLeafOf(specifier) {
|
|
92
|
+
const base = specifier.split("/").pop();
|
|
93
|
+
if (!base) return null;
|
|
94
|
+
return base.split(".")[0] || null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Deep entries of preset packages that are deliberately Node-safe and must NOT
|
|
98
|
+
// be shadowed by the preset mock: test utilities and tooling entry points
|
|
99
|
+
// (react-native-gesture-handler/jest-utils, react-native-reanimated/mock,
|
|
100
|
+
// */jestSetup, babel `*/plugin` entries). They are designed to run under a
|
|
101
|
+
// Node test runner, and shadowing them replaces working code with undefined
|
|
102
|
+
// exports.
|
|
103
|
+
const UTILITY_SUBPATH_LEAVES = new Set(["jest-utils", "jestSetup", "mock", "plugin"]);
|
|
104
|
+
|
|
105
|
+
export function isUtilitySubpath(specifier) {
|
|
106
|
+
const leaf = subpathLeafOf(specifier);
|
|
107
|
+
return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf);
|
|
9
108
|
}
|
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
// Precompiled React Native module registry.
|
|
2
|
+
//
|
|
3
|
+
// The native engine runs RN's real JS, and with isolation on (the default) that
|
|
4
|
+
// graph is re-instantiated for every test FILE: ~440 separate Node module loads,
|
|
5
|
+
// each paying a filesystem stat, a module-wrapper construction, and a compile-cache
|
|
6
|
+
// lookup. Measured on RN 0.86, that is ~59ms for a typical test's slice of RN and
|
|
7
|
+
// ~110ms for the full public surface — per file.
|
|
8
|
+
//
|
|
9
|
+
// This module collapses that into ONE file. At config time we walk RN's require
|
|
10
|
+
// graph once, apply exactly the transforms the per-file hooks would apply (native
|
|
11
|
+
// boundary source, Flow strip via the project's Babel preset, asset stubs), resolve
|
|
12
|
+
// every require target statically, and emit a single CJS file of lazy per-module
|
|
13
|
+
// factories keyed by real path. A test file then pays one read and one compile.
|
|
14
|
+
//
|
|
15
|
+
// What is deliberately preserved, because tests depend on all of it:
|
|
16
|
+
// - laziness — factories run on first require, so a test that touches View
|
|
17
|
+
// and StyleSheet still does not execute the rest of RN;
|
|
18
|
+
// - module identity — one instance per path per worker, so RN's singletons
|
|
19
|
+
// (DeviceEventEmitter, Dimensions, Appearance) behave as they do
|
|
20
|
+
// today, and a deep `react-native/Libraries/...` require from an
|
|
21
|
+
// ecosystem package resolves to the same instance the app sees;
|
|
22
|
+
// - isolation — the registry is re-required per test file like any other
|
|
23
|
+
// module, so nothing leaks between files.
|
|
24
|
+
//
|
|
25
|
+
// The registry is an optimization, never a semantic: anything it cannot serve falls
|
|
26
|
+
// through to the per-file hooks in hooks.mjs / loader.mjs, and a failed build leaves
|
|
27
|
+
// the engine running exactly as it did before.
|
|
28
|
+
import Module from "node:module";
|
|
29
|
+
import { createRequire } from "node:module";
|
|
30
|
+
import path from "node:path";
|
|
31
|
+
import fs from "node:fs";
|
|
32
|
+
import crypto from "node:crypto";
|
|
33
|
+
import { transformRN, isFlow, cacheRootFor } from "./transform.mjs";
|
|
34
|
+
import { boundarySourceFor, BOUNDARY_SOURCES } from "./boundary.mjs";
|
|
35
|
+
import { resolvePlatformFile } from "./resolve.mjs";
|
|
36
|
+
|
|
37
|
+
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
38
|
+
// Bump when the emitted registry's shape or the walk's semantics change, so a
|
|
39
|
+
// stale on-disk registry from an older vitest-native can never be reused.
|
|
40
|
+
const REGISTRY_FORMAT_VERSION = 1;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Literal `require('…')` / `require("…")` calls. The leading class excludes
|
|
44
|
+
* property access (`foo.require(...)`) and identifiers ending in "require"
|
|
45
|
+
* (`__webpack_require__(...)`), which are not Node requires.
|
|
46
|
+
*
|
|
47
|
+
* Computed requires (`require(someVar)`) are invisible to this scan by design:
|
|
48
|
+
* they resolve at runtime and fall through to the per-file hooks, which is why
|
|
49
|
+
* the hooks must stay installed alongside the registry.
|
|
50
|
+
*/
|
|
51
|
+
const REQUIRE_RE = /(?:^|[^.\w$])require\(\s*(['"])([^'"]+)\1\s*\)/g;
|
|
52
|
+
|
|
53
|
+
/** Extensions Node handles natively and that must not be inlined as JS. */
|
|
54
|
+
const PASSTHROUGH_EXT = new Set([".json", ".node", ".wasm"]);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Source for one file, applying the same precedence the per-file hooks use:
|
|
58
|
+
* asset stub → native-boundary mock → Flow-stripped RN → verbatim.
|
|
59
|
+
*/
|
|
60
|
+
function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSet }) {
|
|
61
|
+
const norm = file.replace(/\\/g, "/");
|
|
62
|
+
const ext = path.extname(norm).slice(1).toLowerCase();
|
|
63
|
+
if (ext && assetExtSet.has(ext)) {
|
|
64
|
+
const basename = norm.split("/").pop() || norm;
|
|
65
|
+
return { code: `module.exports = ${JSON.stringify(basename)};`, scan: false };
|
|
66
|
+
}
|
|
67
|
+
const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
|
|
68
|
+
if (boundary != null) return { code: boundary, scan: true };
|
|
69
|
+
const src = fs.readFileSync(file, "utf8");
|
|
70
|
+
if (norm.endsWith(".js") && isFlow(src)) {
|
|
71
|
+
return { code: transformRN(file, src, projectRoot, platform), scan: true };
|
|
72
|
+
}
|
|
73
|
+
return { code: src, scan: true };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Resolve one require target from a file, applying the platform-extension
|
|
78
|
+
* resolution the hooks apply inside node_modules (`./Foo` → `Foo.ios.js`).
|
|
79
|
+
* Returns an absolute path, or null when the target cannot be resolved.
|
|
80
|
+
*/
|
|
81
|
+
function resolveTarget(request, fromFile, platform) {
|
|
82
|
+
if (request.startsWith(".") && !path.extname(request)) {
|
|
83
|
+
const hit = resolvePlatformFile(path.resolve(path.dirname(fromFile), request), platform);
|
|
84
|
+
if (hit) return hit;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
return createRequire(fromFile).resolve(request);
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** This package's own version — part of the cache key (see registryKey). */
|
|
94
|
+
function ownVersion() {
|
|
95
|
+
try {
|
|
96
|
+
return createRequire(import.meta.url)("../../package.json").version ?? "0";
|
|
97
|
+
} catch {
|
|
98
|
+
return "0";
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Identity of every input that determines the emitted registry's contents.
|
|
104
|
+
*
|
|
105
|
+
* The boundary mocks are compiled INTO the registry, so their SOURCE is hashed,
|
|
106
|
+
* not just their module names: editing a mock's body has to invalidate the cache
|
|
107
|
+
* the same way a Babel upgrade does. Hashing only the names meant a maintainer
|
|
108
|
+
* changing a mock, or a user upgrading to a release that changed one, kept getting
|
|
109
|
+
* the previous behaviour out of the cache with nothing to indicate it.
|
|
110
|
+
*
|
|
111
|
+
* This package's version is in the key for the same reason, covering everything
|
|
112
|
+
* else it contributes — the transform's Babel options, platform resolution, the
|
|
113
|
+
* emitted registry's own shape.
|
|
114
|
+
*/
|
|
115
|
+
function registryKey({ projectRoot, platform, reactNativeVersion }) {
|
|
116
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
117
|
+
const version = (name) => {
|
|
118
|
+
try {
|
|
119
|
+
return req(`${name}/package.json`).version ?? "0";
|
|
120
|
+
} catch {
|
|
121
|
+
return "0";
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
const boundaries = crypto.createHash("sha1");
|
|
125
|
+
for (const suffix of Object.keys(BOUNDARY_SOURCES).sort()) {
|
|
126
|
+
boundaries.update(suffix);
|
|
127
|
+
boundaries.update("\0");
|
|
128
|
+
boundaries.update(
|
|
129
|
+
String(boundarySourceFor(`/react-native/${suffix}`, platform, reactNativeVersion)),
|
|
130
|
+
);
|
|
131
|
+
boundaries.update("\0");
|
|
132
|
+
}
|
|
133
|
+
return crypto
|
|
134
|
+
.createHash("sha1")
|
|
135
|
+
.update(
|
|
136
|
+
[
|
|
137
|
+
`f${REGISTRY_FORMAT_VERSION}`,
|
|
138
|
+
ownVersion(),
|
|
139
|
+
platform,
|
|
140
|
+
reactNativeVersion,
|
|
141
|
+
version("react-native"),
|
|
142
|
+
version("@react-native/babel-preset"),
|
|
143
|
+
version("@babel/core"),
|
|
144
|
+
process.env.BABEL_ENV || process.env.NODE_ENV || "none",
|
|
145
|
+
boundaries.digest("hex"),
|
|
146
|
+
].join("\0"),
|
|
147
|
+
)
|
|
148
|
+
.digest("hex")
|
|
149
|
+
.slice(0, 16);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* True when every file the cached registry was built from is still present and
|
|
154
|
+
* unchanged (same size and mtime). ~440 stats, a few milliseconds — cheap enough
|
|
155
|
+
* to pay per run, and it means an edited or reinstalled React Native rebuilds
|
|
156
|
+
* instead of silently serving stale code.
|
|
157
|
+
*/
|
|
158
|
+
function manifestValid(manifest) {
|
|
159
|
+
if (!Array.isArray(manifest) || manifest.length === 0) return false;
|
|
160
|
+
for (const [file, mtimeMs, size] of manifest) {
|
|
161
|
+
let st;
|
|
162
|
+
try {
|
|
163
|
+
st = fs.statSync(file);
|
|
164
|
+
} catch {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
if (st.size !== size || st.mtimeMs !== mtimeMs) return false;
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Base64-VLQ encode one signed integer (source-map segment field). */
|
|
173
|
+
function vlq(value) {
|
|
174
|
+
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
175
|
+
let v = value < 0 ? (-value << 1) | 1 : value << 1;
|
|
176
|
+
let out = "";
|
|
177
|
+
do {
|
|
178
|
+
let digit = v & 31;
|
|
179
|
+
v >>>= 5;
|
|
180
|
+
if (v > 0) digit |= 32;
|
|
181
|
+
out += B64[digit];
|
|
182
|
+
} while (v > 0);
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* A source map attributing each emitted line to the React Native file it came from.
|
|
188
|
+
*
|
|
189
|
+
* Without it, every stack frame from inside React Native reports the registry's
|
|
190
|
+
* cache path — `rn-ios-<hash>.cjs:253:7638` instead of
|
|
191
|
+
* `Libraries/Animated/nodes/AnimatedInterpolation.js`. The file is the useful part
|
|
192
|
+
* of such a frame, and losing it makes an RN-internal failure far harder to read.
|
|
193
|
+
*
|
|
194
|
+
* Line granularity is enough here, and deliberately so: the Babel output for an RN
|
|
195
|
+
* module is a single line, so the original line is always 1 and only the FILE is in
|
|
196
|
+
* question. One segment per generated line keeps the map small (no `sourcesContent`
|
|
197
|
+
* — the real files are on disk at these very paths) and costs nothing at runtime.
|
|
198
|
+
*/
|
|
199
|
+
function sourceMapFor(lineOwners, files) {
|
|
200
|
+
let previousSource = 0;
|
|
201
|
+
const mappings = lineOwners.map((owner) => {
|
|
202
|
+
if (owner === null) return "";
|
|
203
|
+
const segment = vlq(0) + vlq(owner - previousSource) + vlq(0) + vlq(0);
|
|
204
|
+
previousSource = owner;
|
|
205
|
+
return segment;
|
|
206
|
+
});
|
|
207
|
+
return { version: 3, sources: files, names: [], mappings: mappings.join(";") };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Emit the registry source for the walked module set, plus the source map that
|
|
212
|
+
* keeps React Native's own files identifiable in stack traces.
|
|
213
|
+
*/
|
|
214
|
+
function emit(files, modules) {
|
|
215
|
+
const idOf = new Map(files.map((f, i) => [f, i]));
|
|
216
|
+
const deps = files.map((f) => {
|
|
217
|
+
const out = {};
|
|
218
|
+
for (const [request, target] of Object.entries(modules.get(f).deps)) {
|
|
219
|
+
out[request] = target === null ? null : (idOf.get(target) ?? target);
|
|
220
|
+
}
|
|
221
|
+
return JSON.stringify(out);
|
|
222
|
+
});
|
|
223
|
+
const prologue = [
|
|
224
|
+
`"use strict";`,
|
|
225
|
+
// __ext is this file's own require: the escape hatch for targets outside the
|
|
226
|
+
// registry (react, invariant, JSON, anything computed). Pre-resolved absolute
|
|
227
|
+
// paths make those lookups exact rather than re-running Node resolution.
|
|
228
|
+
`const __ext = require, __f = [], __m = [];`,
|
|
229
|
+
`const __ids = ${JSON.stringify(files)};`,
|
|
230
|
+
`const __deps = [${deps.join(",")}];`,
|
|
231
|
+
`const __dirs = __ids.map((f) => f.slice(0, Math.max(f.lastIndexOf("/"), f.lastIndexOf("\\\\"))));`,
|
|
232
|
+
`function __req(i) {`,
|
|
233
|
+
` const map = __deps[i];`,
|
|
234
|
+
` const r = function (q) {`,
|
|
235
|
+
` const t = map[q];`,
|
|
236
|
+
` if (t === undefined || t === null) return __ext(q);`,
|
|
237
|
+
` return typeof t === "number" ? __r(t) : __ext(t);`,
|
|
238
|
+
` };`,
|
|
239
|
+
` r.resolve = function (q) {`,
|
|
240
|
+
` const t = map[q];`,
|
|
241
|
+
` if (t === undefined || t === null) return __ext.resolve(q);`,
|
|
242
|
+
` return typeof t === "number" ? __ids[t] : t;`,
|
|
243
|
+
` };`,
|
|
244
|
+
` r.cache = __ext.cache;`,
|
|
245
|
+
` return r;`,
|
|
246
|
+
`}`,
|
|
247
|
+
// Cyclic requires resolve against the partially-filled exports object, exactly
|
|
248
|
+
// as Node's loader does: the module record is published before its factory runs.
|
|
249
|
+
`function __r(i) {`,
|
|
250
|
+
` const hit = __m[i];`,
|
|
251
|
+
` if (hit !== undefined) return hit.exports;`,
|
|
252
|
+
` const mod = { id: __ids[i], filename: __ids[i], exports: {}, loaded: false, children: [], paths: [] };`,
|
|
253
|
+
` __m[i] = mod;`,
|
|
254
|
+
` try {`,
|
|
255
|
+
` __f[i](mod, mod.exports, __req(i), __ids[i], __dirs[i]);`,
|
|
256
|
+
` } catch (e) {`,
|
|
257
|
+
` __m[i] = undefined;`,
|
|
258
|
+
` throw e;`,
|
|
259
|
+
` }`,
|
|
260
|
+
` mod.loaded = true;`,
|
|
261
|
+
` return mod.exports;`,
|
|
262
|
+
`}`,
|
|
263
|
+
];
|
|
264
|
+
const epilogue = [
|
|
265
|
+
// The entry's exports are the module's value, so `require(registry)` behaves
|
|
266
|
+
// like `require('react-native')`. __registry is the lookup surface the install
|
|
267
|
+
// hook uses to serve deep paths from the same instances.
|
|
268
|
+
`const __entry = __r(0);`,
|
|
269
|
+
`module.exports = __entry;`,
|
|
270
|
+
`Object.defineProperty(module.exports, "__vitestNativeRegistry", {`,
|
|
271
|
+
` value: { ids: __ids, load: __r, entry: __ids[0] },`,
|
|
272
|
+
` enumerable: false, configurable: true,`,
|
|
273
|
+
`});`,
|
|
274
|
+
];
|
|
275
|
+
|
|
276
|
+
// Track which module each emitted line belongs to, so the source map can point
|
|
277
|
+
// stack frames back at the real React Native file. A factory body may span
|
|
278
|
+
// several lines (the boundary mocks do), and every one of those lines is
|
|
279
|
+
// attributed, so a frame can never bleed onto the previous module's mapping.
|
|
280
|
+
const lines = [...prologue];
|
|
281
|
+
const lineOwners = prologue.map(() => null);
|
|
282
|
+
files.forEach((f, i) => {
|
|
283
|
+
const factory = `__f[${i}] = function (module, exports, require, __filename, __dirname) {${modules.get(f).code}\n};`;
|
|
284
|
+
for (const line of factory.split("\n")) {
|
|
285
|
+
lines.push(line);
|
|
286
|
+
lineOwners.push(i);
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
for (const line of epilogue) {
|
|
290
|
+
lines.push(line);
|
|
291
|
+
lineOwners.push(null);
|
|
292
|
+
}
|
|
293
|
+
return { code: lines.join("\n"), map: sourceMapFor(lineOwners, files) };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Build (or reuse) the precompiled registry for a project. Returns the registry
|
|
298
|
+
* file path, or null when a registry cannot be produced — in which case the caller
|
|
299
|
+
* simply keeps using the per-file hooks.
|
|
300
|
+
*/
|
|
301
|
+
export function buildRegistry({
|
|
302
|
+
projectRoot,
|
|
303
|
+
platform = "ios",
|
|
304
|
+
reactNativeVersion = "0.0.0",
|
|
305
|
+
assetExts = [],
|
|
306
|
+
diagnostics = false,
|
|
307
|
+
}) {
|
|
308
|
+
// Escape hatch. The registry is transparent by design, but it is also the piece
|
|
309
|
+
// most likely to be implicated if a project sees something unexpected from React
|
|
310
|
+
// Native — so there is a way to take it out of the picture and get the per-file
|
|
311
|
+
// loader back without downgrading.
|
|
312
|
+
if (process.env.VITEST_NATIVE_NO_REGISTRY === "1") {
|
|
313
|
+
if (diagnostics) {
|
|
314
|
+
console.log(
|
|
315
|
+
"[vitest-native] (native) VITEST_NATIVE_NO_REGISTRY=1 — using per-file module loading",
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
let dir;
|
|
321
|
+
let key;
|
|
322
|
+
try {
|
|
323
|
+
key = registryKey({ projectRoot, platform, reactNativeVersion });
|
|
324
|
+
dir = path.join(cacheRootFor(projectRoot), "registry");
|
|
325
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
326
|
+
} catch {
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const registryFile = path.join(dir, `rn-${platform}-${key}.cjs`);
|
|
331
|
+
const metaFile = `${registryFile}.json`;
|
|
332
|
+
try {
|
|
333
|
+
const meta = JSON.parse(fs.readFileSync(metaFile, "utf8"));
|
|
334
|
+
if (meta.key === key && fs.existsSync(registryFile) && manifestValid(meta.manifest)) {
|
|
335
|
+
if (diagnostics) {
|
|
336
|
+
console.log(
|
|
337
|
+
`[vitest-native] (native) reusing precompiled RN registry (${meta.count} modules)`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return registryFile;
|
|
341
|
+
}
|
|
342
|
+
} catch {
|
|
343
|
+
// No usable cache entry — build one below.
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const started = Date.now();
|
|
347
|
+
const assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
|
|
348
|
+
const options = { projectRoot, platform, reactNativeVersion, assetExtSet };
|
|
349
|
+
const modules = new Map();
|
|
350
|
+
const manifest = [];
|
|
351
|
+
try {
|
|
352
|
+
const entry = createRequire(path.join(projectRoot, "package.json")).resolve("react-native");
|
|
353
|
+
const queue = [entry];
|
|
354
|
+
while (queue.length > 0) {
|
|
355
|
+
const file = queue.pop();
|
|
356
|
+
if (modules.has(file)) continue;
|
|
357
|
+
const { code, scan } = sourceFor(file, options);
|
|
358
|
+
const deps = {};
|
|
359
|
+
if (scan) {
|
|
360
|
+
for (const match of code.matchAll(REQUIRE_RE)) {
|
|
361
|
+
const request = match[2];
|
|
362
|
+
if (request in deps) continue;
|
|
363
|
+
const target = resolveTarget(request, file, platform);
|
|
364
|
+
// Only React Native's own graph is inlined. Everything else — react,
|
|
365
|
+
// invariant, JSON manifests, native addons — stays a normal Node require
|
|
366
|
+
// at a pre-resolved absolute path, so those modules keep their usual
|
|
367
|
+
// identity and are shared with the rest of the worker.
|
|
368
|
+
const internal =
|
|
369
|
+
target !== null &&
|
|
370
|
+
RN_PATH.test(target.replace(/\\/g, "/")) &&
|
|
371
|
+
!PASSTHROUGH_EXT.has(path.extname(target).toLowerCase());
|
|
372
|
+
deps[request] = target;
|
|
373
|
+
if (internal) queue.push(target);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
modules.set(file, { code, deps });
|
|
377
|
+
const st = fs.statSync(file);
|
|
378
|
+
manifest.push([file, st.mtimeMs, st.size]);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const files = [...modules.keys()];
|
|
382
|
+
const { code, map } = emit(files, modules);
|
|
383
|
+
// Write via a unique temp file then rename: several workers may race here on a
|
|
384
|
+
// cold cache, and a reader must never observe a partially written registry.
|
|
385
|
+
// The map lands before the registry that points at it, so a reader can never
|
|
386
|
+
// find the reference without the file.
|
|
387
|
+
const mapFile = `${registryFile}.map`;
|
|
388
|
+
const mapTmp = `${mapFile}.${process.pid}.tmp`;
|
|
389
|
+
fs.writeFileSync(mapTmp, JSON.stringify(map));
|
|
390
|
+
fs.renameSync(mapTmp, mapFile);
|
|
391
|
+
const tmp = `${registryFile}.${process.pid}.tmp`;
|
|
392
|
+
fs.writeFileSync(tmp, `${code}\n//# sourceMappingURL=${path.basename(mapFile)}\n`);
|
|
393
|
+
fs.renameSync(tmp, registryFile);
|
|
394
|
+
fs.writeFileSync(
|
|
395
|
+
`${metaFile}.${process.pid}.tmp`,
|
|
396
|
+
JSON.stringify({ key, count: files.length, manifest }),
|
|
397
|
+
);
|
|
398
|
+
fs.renameSync(`${metaFile}.${process.pid}.tmp`, metaFile);
|
|
399
|
+
if (diagnostics) {
|
|
400
|
+
console.log(
|
|
401
|
+
`[vitest-native] (native) precompiled RN registry: ${files.length} modules in ${Date.now() - started}ms`,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
return registryFile;
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (diagnostics) {
|
|
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
|
+
}
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Serve React Native from the precompiled registry in this worker.
|
|
418
|
+
*
|
|
419
|
+
* Installed BEFORE the require hooks so that the hooks' preset-mock redirect wraps
|
|
420
|
+
* (and therefore takes precedence over) this one — a preset-shadowed package must
|
|
421
|
+
* still win over anything RN's own graph would provide.
|
|
422
|
+
*/
|
|
423
|
+
export function installRegistry(registryFile, projectRoot) {
|
|
424
|
+
if (globalThis.__vitest_native_registry_installed) return true;
|
|
425
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
426
|
+
// Must precede the require below: Node reads `//# sourceMappingURL` when a script
|
|
427
|
+
// is COMPILED, so enabling support afterwards leaves this registry unmapped and
|
|
428
|
+
// every React Native stack frame pointing at the cache file instead of the RN
|
|
429
|
+
// source it came from.
|
|
430
|
+
try {
|
|
431
|
+
process.setSourceMapsEnabled?.(true);
|
|
432
|
+
} catch {
|
|
433
|
+
// Older Node, or a host that has locked this down — frames stay unmapped.
|
|
434
|
+
}
|
|
435
|
+
let registry;
|
|
436
|
+
try {
|
|
437
|
+
registry = req(registryFile).__vitestNativeRegistry;
|
|
438
|
+
if (!registry) return false;
|
|
439
|
+
} catch {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
globalThis.__vitest_native_registry_installed = true;
|
|
443
|
+
|
|
444
|
+
const idOf = new Map(registry.ids.map((f, i) => [f, i]));
|
|
445
|
+
const entryId = idOf.get(registry.entry);
|
|
446
|
+
const origLoad = Module._load;
|
|
447
|
+
Module._load = function (request, parent, ...rest) {
|
|
448
|
+
if (request === "react-native") return registry.load(entryId);
|
|
449
|
+
// An absolute path lands here when something re-enters through Node's loader
|
|
450
|
+
// with an already-resolved file — most importantly the ESM loader's
|
|
451
|
+
// `react-native/index.js` facade, which requires the real index by path.
|
|
452
|
+
const direct = idOf.get(request);
|
|
453
|
+
if (direct !== undefined) return registry.load(direct);
|
|
454
|
+
// Deep imports of RN internals (`react-native/Libraries/…`) and of the
|
|
455
|
+
// @react-native/* packages inlined alongside it must resolve to the SAME
|
|
456
|
+
// instances the entry graph uses, or RN's singletons would exist twice.
|
|
457
|
+
if (request.startsWith("react-native/") || request.startsWith("@react-native/")) {
|
|
458
|
+
const resolver = parent?.filename ? createRequire(parent.filename) : req;
|
|
459
|
+
let resolved;
|
|
460
|
+
try {
|
|
461
|
+
resolved = resolver.resolve(request);
|
|
462
|
+
} catch {
|
|
463
|
+
resolved = null;
|
|
464
|
+
}
|
|
465
|
+
const id = resolved === null ? undefined : idOf.get(resolved);
|
|
466
|
+
if (id !== undefined) return registry.load(id);
|
|
467
|
+
}
|
|
468
|
+
return origLoad.call(this, request, parent, ...rest);
|
|
469
|
+
};
|
|
470
|
+
return true;
|
|
471
|
+
}
|
package/dist/native/reset.mjs
CHANGED
|
@@ -34,8 +34,9 @@
|
|
|
34
34
|
// 2b. process.env — restored to the worker boot snapshot.
|
|
35
35
|
// 3. Vitest timers/global/env stubs — restored by setup.mjs before this reset.
|
|
36
36
|
// 4. Boundary/preset mocks that registered callbacks in
|
|
37
|
-
// globalThis.__vitest_native_resets (
|
|
38
|
-
//
|
|
37
|
+
// globalThis.__vitest_native_resets (the turboStubs register one per
|
|
38
|
+
// native-module name to clear per-file overrides; runs before the
|
|
39
|
+
// value-restores, which route through those stubs).
|
|
39
40
|
// 5. globalThis keys added by a file — deleted. The baseline starts at the
|
|
40
41
|
// first per-file call (after Vitest injected its per-batch globals) and
|
|
41
42
|
// never grows implicitly. Mutations of pre-existing keys are not restored
|
|
@@ -147,6 +148,21 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
|
|
|
147
148
|
// act/auto-cleanup machinery corrupted rendering for every later file
|
|
148
149
|
// when the consumer's graph inlines RNTL (found via Rocket.Chat).
|
|
149
150
|
|
|
151
|
+
// (4) Boundary/preset mock reset callbacks — BEFORE the value-restore:
|
|
152
|
+
// these clear per-file overrides on the boundary stubs (spies, direct
|
|
153
|
+
// method assignments), and the value-restore below routes through those
|
|
154
|
+
// very stubs (Appearance.setColorScheme → NativeAppearance). Restoring
|
|
155
|
+
// first would send the restore through a previous file's dead override
|
|
156
|
+
// and then clear it one step too late.
|
|
157
|
+
const resets = globalThis.__vitest_native_resets;
|
|
158
|
+
if (Array.isArray(resets)) {
|
|
159
|
+
for (const fn of resets) {
|
|
160
|
+
try {
|
|
161
|
+
fn();
|
|
162
|
+
} catch {}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
150
166
|
// (2) Restore mutable resident RN state (value-restore, always safe).
|
|
151
167
|
if (dims) {
|
|
152
168
|
try {
|
|
@@ -157,16 +173,6 @@ export function installHotReset({ projectRoot, diagnostics, preserveGlobals = []
|
|
|
157
173
|
RN.Appearance.setColorScheme?.(colorScheme);
|
|
158
174
|
} catch {}
|
|
159
175
|
|
|
160
|
-
// (4) Boundary/preset mock reset callbacks.
|
|
161
|
-
const resets = globalThis.__vitest_native_resets;
|
|
162
|
-
if (Array.isArray(resets)) {
|
|
163
|
-
for (const fn of resets) {
|
|
164
|
-
try {
|
|
165
|
-
fn();
|
|
166
|
-
} catch {}
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
|
|
170
176
|
if (!armed) return; // no bless yet → cannot attribute; fail open
|
|
171
177
|
|
|
172
178
|
// (1) Remove the previous file's test-phase RN event listeners.
|
package/dist/native/runner.mjs
CHANGED
|
@@ -8,17 +8,23 @@
|
|
|
8
8
|
// (resident-library lazy init — must be preserved across files, it never
|
|
9
9
|
// re-runs) and test-phase state (pollution the next file's reset removes).
|
|
10
10
|
// See reset.mjs for the full attribution model.
|
|
11
|
-
// vitest >=4.1 exports TestRunner from the main entry;
|
|
12
|
-
// VitestTestRunner via the
|
|
13
|
-
// main entry
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
11
|
+
// vitest >=4.1 exports TestRunner from the main entry; 4.0.x only exposes it as
|
|
12
|
+
// VitestTestRunner via the "vitest/runners" subpath, which vitest 5 REMOVED.
|
|
13
|
+
// Prefer the main entry, and reach for the old subpath only when the main export
|
|
14
|
+
// is absent.
|
|
15
|
+
//
|
|
16
|
+
// The fallback specifier is computed rather than written literally, because a
|
|
17
|
+
// literal is resolved when this module is TRANSFORMED, not when the branch runs.
|
|
18
|
+
// Against vitest 5 that resolution fails ("./runners" is not exported), and the
|
|
19
|
+
// failure is silent in the worst way: the run reports unhandled errors, executes
|
|
20
|
+
// no tests, and still exits 0. A computed specifier keeps the branch invisible to
|
|
21
|
+
// the resolver, so 4.0.x keeps its fallback and 5 never looks for it.
|
|
17
22
|
import * as vitest from "vitest";
|
|
18
23
|
|
|
19
24
|
let TestRunner = vitest.TestRunner;
|
|
20
25
|
if (!TestRunner) {
|
|
21
|
-
|
|
26
|
+
const legacyRunners = ["vitest", "runners"].join("/");
|
|
27
|
+
({ VitestTestRunner: TestRunner } = await import(/* @vite-ignore */ legacyRunners));
|
|
22
28
|
}
|
|
23
29
|
|
|
24
30
|
export default class NativeHotRunner extends TestRunner {
|