vitest-native 0.8.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 +1063 -0
- package/README.md +47 -2
- package/dist/cli.cjs +642 -0
- package/dist/cli.d.cts +4 -0
- package/dist/cli.d.mts +4 -0
- package/dist/cli.mjs +638 -0
- package/dist/ecosystem-CO5vqExO.mjs +318 -0
- package/dist/ecosystem-IuZ-Gv0R.cjs +356 -0
- 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-vlK4zxuK.d.mts → index-BJL4cQ-l.d.cts} +22 -7
- package/dist/{index-YjjYELG7.d.cts → index-CvCU0cLl.d.mts} +20 -9
- package/dist/index.d.mts +8 -6
- package/dist/index.mjs +563 -232
- package/dist/jest-compat/interop.mjs +15 -0
- package/dist/jest-compat/setup.mjs +164 -5
- package/dist/matchers.cjs +16 -7
- package/dist/matchers.mjs +16 -7
- package/dist/native/boundary.mjs +108 -30
- package/dist/native/compile-cache.mjs +10 -5
- package/dist/native/explain.mjs +69 -0
- package/dist/native/hooks.mjs +151 -4
- package/dist/native/loader.mjs +61 -12
- package/dist/native/match.mjs +107 -8
- package/dist/native/module-reset.mjs +63 -0
- package/dist/native/registry.mjs +540 -0
- package/dist/native/reset.mjs +18 -12
- package/dist/native/resolve.d.mts +22 -0
- package/dist/native/resolve.mjs +21 -13
- package/dist/native/runner.mjs +34 -7
- package/dist/native/setup.mjs +19 -3
- package/dist/native/transform.mjs +195 -21
- package/dist/native/worker.mjs +69 -17
- package/dist/pool-Bcxp4Qrg.mjs +118 -0
- package/dist/pool-CFND7plG.cjs +122 -0
- package/dist/{preset-map-DCWaM08s.mjs → preset-map-BpDG_D5m.mjs} +1 -1
- package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-DxilQ4pI.cjs} +1 -1
- package/dist/{presets-7eMfp7o2.cjs → presets-BGTqVH6C.cjs} +227 -52
- package/dist/{presets-23FJ76O4.mjs → presets-CK85x8ey.mjs} +222 -53
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/rntl-matchers.d.ts +35 -0
- package/dist/serializer.cjs +33 -3
- package/dist/serializer.mjs +33 -3
- package/dist/setup.mjs +544 -193
- 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 +24 -6
- package/docs/versioning.md +133 -0
- package/package.json +40 -38
- package/dist/index.cjs +0 -643
- package/dist/index.d.cts +0 -14
- package/dist/pool-B7LBfcMQ.mjs +0 -67
- package/dist/pool-p54QV1dQ.cjs +0 -69
- package/dist/presets.cjs +0 -17
- package/dist/presets.d.cts +0 -2
- package/dist/setup.cjs +0 -2514
- package/dist/setup.d.cts +0 -1
|
@@ -0,0 +1,540 @@
|
|
|
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, TRANSFORM_CACHE_VERSION } from "./transform.mjs";
|
|
34
|
+
|
|
35
|
+
import { boundarySourceFor, BOUNDARY_SOURCES } from "./boundary.mjs";
|
|
36
|
+
import { resolvePlatformFile } from "./resolve.mjs";
|
|
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
|
+
|
|
86
|
+
const RN_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
87
|
+
// Bump when the emitted registry's shape or the walk's semantics change, so a
|
|
88
|
+
// stale on-disk registry from an older vitest-native can never be reused.
|
|
89
|
+
const REGISTRY_FORMAT_VERSION = 2;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Literal `require('…')` / `require("…")` calls. The leading class excludes
|
|
93
|
+
* property access (`foo.require(...)`) and identifiers ending in "require"
|
|
94
|
+
* (`__webpack_require__(...)`), which are not Node requires.
|
|
95
|
+
*
|
|
96
|
+
* Computed requires (`require(someVar)`) are invisible to this scan by design:
|
|
97
|
+
* they resolve at runtime and fall through to the per-file hooks, which is why
|
|
98
|
+
* the hooks must stay installed alongside the registry.
|
|
99
|
+
*/
|
|
100
|
+
const REQUIRE_RE = /(?:^|[^.\w$])require\(\s*(['"])([^'"]+)\1\s*\)/g;
|
|
101
|
+
|
|
102
|
+
/** Extensions Node handles natively and that must not be inlined as JS. */
|
|
103
|
+
const PASSTHROUGH_EXT = new Set([".json", ".node", ".wasm"]);
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Source for one file, applying the same precedence the per-file hooks use:
|
|
107
|
+
* asset stub → native-boundary mock → Flow-stripped RN → verbatim.
|
|
108
|
+
*/
|
|
109
|
+
function sourceFor(file, { projectRoot, platform, reactNativeVersion, assetExtSet }) {
|
|
110
|
+
const norm = file.replace(/\\/g, "/");
|
|
111
|
+
const ext = path.extname(norm).slice(1).toLowerCase();
|
|
112
|
+
if (ext && assetExtSet.has(ext)) {
|
|
113
|
+
const basename = norm.split("/").pop() || norm;
|
|
114
|
+
return { code: `module.exports = ${JSON.stringify(basename)};`, scan: false };
|
|
115
|
+
}
|
|
116
|
+
const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
|
|
117
|
+
if (boundary != null) return { code: boundary, scan: true };
|
|
118
|
+
const src = fs.readFileSync(file, "utf8");
|
|
119
|
+
if (norm.endsWith(".js") && isFlow(src)) {
|
|
120
|
+
return { code: transformRN(file, src, projectRoot, platform), scan: true };
|
|
121
|
+
}
|
|
122
|
+
return { code: src, scan: true };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Resolve one require target from a file, applying the platform-extension
|
|
127
|
+
* resolution the hooks apply inside node_modules (`./Foo` → `Foo.ios.js`).
|
|
128
|
+
* Returns an absolute path, or null when the target cannot be resolved.
|
|
129
|
+
*/
|
|
130
|
+
function resolveTarget(request, fromFile, platform) {
|
|
131
|
+
if (request.startsWith(".") && !path.extname(request)) {
|
|
132
|
+
const hit = resolvePlatformFile(path.resolve(path.dirname(fromFile), request), platform);
|
|
133
|
+
if (hit) return hit;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
return createRequire(fromFile).resolve(request);
|
|
137
|
+
} catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** This package's own version — part of the cache key (see registryKey). */
|
|
143
|
+
function ownVersion() {
|
|
144
|
+
try {
|
|
145
|
+
return createRequire(import.meta.url)("../../package.json").version ?? "0";
|
|
146
|
+
} catch {
|
|
147
|
+
return "0";
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Identity of every input that determines the emitted registry's contents.
|
|
153
|
+
*
|
|
154
|
+
* The boundary mocks are compiled INTO the registry, so their SOURCE is hashed,
|
|
155
|
+
* not just their module names: editing a mock's body has to invalidate the cache
|
|
156
|
+
* the same way a Babel upgrade does. Hashing only the names meant a maintainer
|
|
157
|
+
* changing a mock, or a user upgrading to a release that changed one, kept getting
|
|
158
|
+
* the previous behaviour out of the cache with nothing to indicate it.
|
|
159
|
+
*
|
|
160
|
+
* This package's version is in the key for the same reason, covering everything
|
|
161
|
+
* else it contributes — the transform's Babel options, platform resolution, the
|
|
162
|
+
* emitted registry's own shape.
|
|
163
|
+
*
|
|
164
|
+
* Exported for tests. Not part of the public surface — see docs/versioning.md.
|
|
165
|
+
*/
|
|
166
|
+
export function registryKey({ projectRoot, platform, reactNativeVersion }) {
|
|
167
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
168
|
+
const version = (name) => {
|
|
169
|
+
try {
|
|
170
|
+
return req(`${name}/package.json`).version ?? "0";
|
|
171
|
+
} catch {
|
|
172
|
+
return "0";
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const boundaries = crypto.createHash("sha1");
|
|
176
|
+
for (const suffix of Object.keys(BOUNDARY_SOURCES).sort()) {
|
|
177
|
+
boundaries.update(suffix);
|
|
178
|
+
boundaries.update("\0");
|
|
179
|
+
boundaries.update(
|
|
180
|
+
String(boundarySourceFor(`/react-native/${suffix}`, platform, reactNativeVersion)),
|
|
181
|
+
);
|
|
182
|
+
boundaries.update("\0");
|
|
183
|
+
}
|
|
184
|
+
return crypto
|
|
185
|
+
.createHash("sha1")
|
|
186
|
+
.update(
|
|
187
|
+
[
|
|
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}`,
|
|
196
|
+
ownVersion(),
|
|
197
|
+
platform,
|
|
198
|
+
reactNativeVersion,
|
|
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"),
|
|
211
|
+
version("@react-native/babel-preset"),
|
|
212
|
+
version("@babel/core"),
|
|
213
|
+
process.env.BABEL_ENV || process.env.NODE_ENV || "none",
|
|
214
|
+
boundaries.digest("hex"),
|
|
215
|
+
].join("\0"),
|
|
216
|
+
)
|
|
217
|
+
.digest("hex")
|
|
218
|
+
.slice(0, 16);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* True when every file the cached registry was built from is still present and
|
|
223
|
+
* unchanged (same size and mtime). ~440 stats, a few milliseconds — cheap enough
|
|
224
|
+
* to pay per run, and it means an edited or reinstalled React Native rebuilds
|
|
225
|
+
* instead of silently serving stale code.
|
|
226
|
+
*/
|
|
227
|
+
function manifestValid(manifest) {
|
|
228
|
+
if (!Array.isArray(manifest) || manifest.length === 0) return false;
|
|
229
|
+
for (const [file, mtimeMs, size] of manifest) {
|
|
230
|
+
let st;
|
|
231
|
+
try {
|
|
232
|
+
st = fs.statSync(file);
|
|
233
|
+
} catch {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
if (st.size !== size || st.mtimeMs !== mtimeMs) return false;
|
|
237
|
+
}
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Base64-VLQ encode one signed integer (source-map segment field). */
|
|
242
|
+
function vlq(value) {
|
|
243
|
+
const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
244
|
+
let v = value < 0 ? (-value << 1) | 1 : value << 1;
|
|
245
|
+
let out = "";
|
|
246
|
+
do {
|
|
247
|
+
let digit = v & 31;
|
|
248
|
+
v >>>= 5;
|
|
249
|
+
if (v > 0) digit |= 32;
|
|
250
|
+
out += B64[digit];
|
|
251
|
+
} while (v > 0);
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* A source map attributing each emitted line to the React Native file it came from.
|
|
257
|
+
*
|
|
258
|
+
* Without it, every stack frame from inside React Native reports the registry's
|
|
259
|
+
* cache path — `rn-ios-<hash>.cjs:253:7638` instead of
|
|
260
|
+
* `Libraries/Animated/nodes/AnimatedInterpolation.js`. The file is the useful part
|
|
261
|
+
* of such a frame, and losing it makes an RN-internal failure far harder to read.
|
|
262
|
+
*
|
|
263
|
+
* Line granularity is enough here, and deliberately so: the Babel output for an RN
|
|
264
|
+
* module is a single line, so the original line is always 1 and only the FILE is in
|
|
265
|
+
* question. One segment per generated line keeps the map small (no `sourcesContent`
|
|
266
|
+
* — the real files are on disk at these very paths) and costs nothing at runtime.
|
|
267
|
+
*/
|
|
268
|
+
function sourceMapFor(lineOwners, files) {
|
|
269
|
+
let previousSource = 0;
|
|
270
|
+
const mappings = lineOwners.map((owner) => {
|
|
271
|
+
if (owner === null) return "";
|
|
272
|
+
const segment = vlq(0) + vlq(owner - previousSource) + vlq(0) + vlq(0);
|
|
273
|
+
previousSource = owner;
|
|
274
|
+
return segment;
|
|
275
|
+
});
|
|
276
|
+
return { version: 3, sources: files, names: [], mappings: mappings.join(";") };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Emit the registry source for the walked module set, plus the source map that
|
|
281
|
+
* keeps React Native's own files identifiable in stack traces.
|
|
282
|
+
*/
|
|
283
|
+
function emit(files, modules) {
|
|
284
|
+
const idOf = new Map(files.map((f, i) => [f, i]));
|
|
285
|
+
const deps = files.map((f) => {
|
|
286
|
+
const out = {};
|
|
287
|
+
for (const [request, target] of Object.entries(modules.get(f).deps)) {
|
|
288
|
+
out[request] = target === null ? null : (idOf.get(target) ?? target);
|
|
289
|
+
}
|
|
290
|
+
return JSON.stringify(out);
|
|
291
|
+
});
|
|
292
|
+
const prologue = [
|
|
293
|
+
`"use strict";`,
|
|
294
|
+
// __ext is this file's own require: the escape hatch for targets outside the
|
|
295
|
+
// registry (react, invariant, JSON, anything computed). Pre-resolved absolute
|
|
296
|
+
// paths make those lookups exact rather than re-running Node resolution.
|
|
297
|
+
`const __ext = require, __f = [], __m = [];`,
|
|
298
|
+
`const __ids = ${JSON.stringify(files)};`,
|
|
299
|
+
`const __deps = [${deps.join(",")}];`,
|
|
300
|
+
`const __dirs = __ids.map((f) => f.slice(0, Math.max(f.lastIndexOf("/"), f.lastIndexOf("\\\\"))));`,
|
|
301
|
+
`function __req(i) {`,
|
|
302
|
+
` const map = __deps[i];`,
|
|
303
|
+
` const r = function (q) {`,
|
|
304
|
+
` const t = map[q];`,
|
|
305
|
+
` if (t === undefined || t === null) return __ext(q);`,
|
|
306
|
+
` return typeof t === "number" ? __r(t) : __ext(t);`,
|
|
307
|
+
` };`,
|
|
308
|
+
` r.resolve = function (q) {`,
|
|
309
|
+
` const t = map[q];`,
|
|
310
|
+
` if (t === undefined || t === null) return __ext.resolve(q);`,
|
|
311
|
+
` return typeof t === "number" ? __ids[t] : t;`,
|
|
312
|
+
` };`,
|
|
313
|
+
` r.cache = __ext.cache;`,
|
|
314
|
+
` return r;`,
|
|
315
|
+
`}`,
|
|
316
|
+
// Cyclic requires resolve against the partially-filled exports object, exactly
|
|
317
|
+
// as Node's loader does: the module record is published before its factory runs.
|
|
318
|
+
`function __r(i) {`,
|
|
319
|
+
` const hit = __m[i];`,
|
|
320
|
+
` if (hit !== undefined) return hit.exports;`,
|
|
321
|
+
` const mod = { id: __ids[i], filename: __ids[i], exports: {}, loaded: false, children: [], paths: [] };`,
|
|
322
|
+
` __m[i] = mod;`,
|
|
323
|
+
` try {`,
|
|
324
|
+
` __f[i](mod, mod.exports, __req(i), __ids[i], __dirs[i]);`,
|
|
325
|
+
` } catch (e) {`,
|
|
326
|
+
` __m[i] = undefined;`,
|
|
327
|
+
` throw e;`,
|
|
328
|
+
` }`,
|
|
329
|
+
` mod.loaded = true;`,
|
|
330
|
+
` return mod.exports;`,
|
|
331
|
+
`}`,
|
|
332
|
+
];
|
|
333
|
+
const epilogue = [
|
|
334
|
+
// The entry's exports are the module's value, so `require(registry)` behaves
|
|
335
|
+
// like `require('react-native')`. __registry is the lookup surface the install
|
|
336
|
+
// hook uses to serve deep paths from the same instances.
|
|
337
|
+
`const __entry = __r(0);`,
|
|
338
|
+
`module.exports = __entry;`,
|
|
339
|
+
`Object.defineProperty(module.exports, "__vitestNativeRegistry", {`,
|
|
340
|
+
` value: { ids: __ids, load: __r, entry: __ids[0], reset: () => { __m.length = 0; } },`,
|
|
341
|
+
` enumerable: false, configurable: true,`,
|
|
342
|
+
`});`,
|
|
343
|
+
];
|
|
344
|
+
|
|
345
|
+
// Track which module each emitted line belongs to, so the source map can point
|
|
346
|
+
// stack frames back at the real React Native file. A factory body may span
|
|
347
|
+
// several lines (the boundary mocks do), and every one of those lines is
|
|
348
|
+
// attributed, so a frame can never bleed onto the previous module's mapping.
|
|
349
|
+
const lines = [...prologue];
|
|
350
|
+
const lineOwners = prologue.map(() => null);
|
|
351
|
+
files.forEach((f, i) => {
|
|
352
|
+
const factory = `__f[${i}] = function (module, exports, require, __filename, __dirname) {${modules.get(f).code}\n};`;
|
|
353
|
+
for (const line of factory.split("\n")) {
|
|
354
|
+
lines.push(line);
|
|
355
|
+
lineOwners.push(i);
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
for (const line of epilogue) {
|
|
359
|
+
lines.push(line);
|
|
360
|
+
lineOwners.push(null);
|
|
361
|
+
}
|
|
362
|
+
return { code: lines.join("\n"), map: sourceMapFor(lineOwners, files) };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Build (or reuse) the precompiled registry for a project. Returns the registry
|
|
367
|
+
* file path, or null when a registry cannot be produced — in which case the caller
|
|
368
|
+
* simply keeps using the per-file hooks.
|
|
369
|
+
*/
|
|
370
|
+
export function buildRegistry({
|
|
371
|
+
projectRoot,
|
|
372
|
+
platform = "ios",
|
|
373
|
+
reactNativeVersion = "0.0.0",
|
|
374
|
+
assetExts = [],
|
|
375
|
+
diagnostics = false,
|
|
376
|
+
}) {
|
|
377
|
+
// See warnRegistryUnavailable: this is the one path that stays quiet, because
|
|
378
|
+
// the user asked for it.
|
|
379
|
+
//
|
|
380
|
+
// Escape hatch. The registry is transparent by design, but it is also the piece
|
|
381
|
+
// most likely to be implicated if a project sees something unexpected from React
|
|
382
|
+
// Native — so there is a way to take it out of the picture and get the per-file
|
|
383
|
+
// loader back without downgrading.
|
|
384
|
+
if (process.env.VITEST_NATIVE_NO_REGISTRY === "1") {
|
|
385
|
+
if (diagnostics) {
|
|
386
|
+
console.log(
|
|
387
|
+
"[vitest-native] (native) VITEST_NATIVE_NO_REGISTRY=1 — using per-file module loading",
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
let dir;
|
|
393
|
+
let key;
|
|
394
|
+
try {
|
|
395
|
+
key = registryKey({ projectRoot, platform, reactNativeVersion });
|
|
396
|
+
dir = path.join(cacheRootFor(projectRoot), "registry");
|
|
397
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
398
|
+
} catch (error) {
|
|
399
|
+
warnRegistryUnavailable(error?.message ?? "cache directory unavailable");
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const registryFile = path.join(dir, `rn-${platform}-${key}.cjs`);
|
|
404
|
+
const metaFile = `${registryFile}.json`;
|
|
405
|
+
try {
|
|
406
|
+
const meta = JSON.parse(fs.readFileSync(metaFile, "utf8"));
|
|
407
|
+
if (meta.key === key && fs.existsSync(registryFile) && manifestValid(meta.manifest)) {
|
|
408
|
+
if (diagnostics) {
|
|
409
|
+
console.log(
|
|
410
|
+
`[vitest-native] (native) reusing precompiled RN registry (${meta.count} modules)`,
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
return registryFile;
|
|
414
|
+
}
|
|
415
|
+
} catch {
|
|
416
|
+
// No usable cache entry — build one below.
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const started = Date.now();
|
|
420
|
+
const assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
|
|
421
|
+
const options = { projectRoot, platform, reactNativeVersion, assetExtSet };
|
|
422
|
+
const modules = new Map();
|
|
423
|
+
const manifest = [];
|
|
424
|
+
try {
|
|
425
|
+
const entry = createRequire(path.join(projectRoot, "package.json")).resolve("react-native");
|
|
426
|
+
const queue = [entry];
|
|
427
|
+
while (queue.length > 0) {
|
|
428
|
+
const file = queue.pop();
|
|
429
|
+
if (modules.has(file)) continue;
|
|
430
|
+
const { code, scan } = sourceFor(file, options);
|
|
431
|
+
const deps = {};
|
|
432
|
+
if (scan) {
|
|
433
|
+
for (const match of code.matchAll(REQUIRE_RE)) {
|
|
434
|
+
const request = match[2];
|
|
435
|
+
if (request in deps) continue;
|
|
436
|
+
const target = resolveTarget(request, file, platform);
|
|
437
|
+
// Only React Native's own graph is inlined. Everything else — react,
|
|
438
|
+
// invariant, JSON manifests, native addons — stays a normal Node require
|
|
439
|
+
// at a pre-resolved absolute path, so those modules keep their usual
|
|
440
|
+
// identity and are shared with the rest of the worker.
|
|
441
|
+
const internal =
|
|
442
|
+
target !== null &&
|
|
443
|
+
RN_PATH.test(target.replace(/\\/g, "/")) &&
|
|
444
|
+
!PASSTHROUGH_EXT.has(path.extname(target).toLowerCase());
|
|
445
|
+
deps[request] = target;
|
|
446
|
+
if (internal) queue.push(target);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
modules.set(file, { code, deps });
|
|
450
|
+
const st = fs.statSync(file);
|
|
451
|
+
manifest.push([file, st.mtimeMs, st.size]);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const files = [...modules.keys()];
|
|
455
|
+
const { code, map } = emit(files, modules);
|
|
456
|
+
// Write via a unique temp file then rename: several workers may race here on a
|
|
457
|
+
// cold cache, and a reader must never observe a partially written registry.
|
|
458
|
+
// The map lands before the registry that points at it, so a reader can never
|
|
459
|
+
// find the reference without the file.
|
|
460
|
+
const mapFile = `${registryFile}.map`;
|
|
461
|
+
const mapTmp = `${mapFile}.${process.pid}.tmp`;
|
|
462
|
+
fs.writeFileSync(mapTmp, JSON.stringify(map));
|
|
463
|
+
fs.renameSync(mapTmp, mapFile);
|
|
464
|
+
const tmp = `${registryFile}.${process.pid}.tmp`;
|
|
465
|
+
fs.writeFileSync(tmp, `${code}\n//# sourceMappingURL=${path.basename(mapFile)}\n`);
|
|
466
|
+
fs.renameSync(tmp, registryFile);
|
|
467
|
+
fs.writeFileSync(
|
|
468
|
+
`${metaFile}.${process.pid}.tmp`,
|
|
469
|
+
JSON.stringify({ key, count: files.length, manifest }),
|
|
470
|
+
);
|
|
471
|
+
fs.renameSync(`${metaFile}.${process.pid}.tmp`, metaFile);
|
|
472
|
+
if (diagnostics) {
|
|
473
|
+
console.log(
|
|
474
|
+
`[vitest-native] (native) precompiled RN registry: ${files.length} modules in ${Date.now() - started}ms`,
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
return registryFile;
|
|
478
|
+
} catch (error) {
|
|
479
|
+
warnRegistryUnavailable(error?.message ?? "unknown error");
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Serve React Native from the precompiled registry in this worker.
|
|
486
|
+
*
|
|
487
|
+
* Installed BEFORE the require hooks so that the hooks' preset-mock redirect wraps
|
|
488
|
+
* (and therefore takes precedence over) this one — a preset-shadowed package must
|
|
489
|
+
* still win over anything RN's own graph would provide.
|
|
490
|
+
*/
|
|
491
|
+
export function installRegistry(registryFile, projectRoot) {
|
|
492
|
+
if (globalThis.__vitest_native_registry_installed) return true;
|
|
493
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
494
|
+
// Must precede the require below: Node reads `//# sourceMappingURL` when a script
|
|
495
|
+
// is COMPILED, so enabling support afterwards leaves this registry unmapped and
|
|
496
|
+
// every React Native stack frame pointing at the cache file instead of the RN
|
|
497
|
+
// source it came from.
|
|
498
|
+
try {
|
|
499
|
+
process.setSourceMapsEnabled?.(true);
|
|
500
|
+
} catch {
|
|
501
|
+
// Older Node, or a host that has locked this down — frames stay unmapped.
|
|
502
|
+
}
|
|
503
|
+
let registry;
|
|
504
|
+
try {
|
|
505
|
+
registry = req(registryFile).__vitestNativeRegistry;
|
|
506
|
+
if (!registry) return false;
|
|
507
|
+
} catch {
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
globalThis.__vitest_native_registry_installed = true;
|
|
511
|
+
globalThis.__vitest_native_registry_reset = () => registry.reset();
|
|
512
|
+
|
|
513
|
+
const idOf = new Map(registry.ids.map((f, i) => [f, i]));
|
|
514
|
+
const entryId = idOf.get(registry.entry);
|
|
515
|
+
const origLoad = Module._load;
|
|
516
|
+
Module._load = function (request, parent, ...rest) {
|
|
517
|
+
if (request === "react-native") return registry.load(entryId);
|
|
518
|
+
// An absolute path lands here when something re-enters through Node's loader
|
|
519
|
+
// with an already-resolved file — most importantly the ESM loader's
|
|
520
|
+
// `react-native/index.js` facade, which requires the real index by path.
|
|
521
|
+
const direct = idOf.get(request);
|
|
522
|
+
if (direct !== undefined) return registry.load(direct);
|
|
523
|
+
// Deep imports of RN internals (`react-native/Libraries/…`) and of the
|
|
524
|
+
// @react-native/* packages inlined alongside it must resolve to the SAME
|
|
525
|
+
// instances the entry graph uses, or RN's singletons would exist twice.
|
|
526
|
+
if (request.startsWith("react-native/") || request.startsWith("@react-native/")) {
|
|
527
|
+
const resolver = parent?.filename ? createRequire(parent.filename) : req;
|
|
528
|
+
let resolved;
|
|
529
|
+
try {
|
|
530
|
+
resolved = resolver.resolve(request);
|
|
531
|
+
} catch {
|
|
532
|
+
resolved = null;
|
|
533
|
+
}
|
|
534
|
+
const id = resolved === null ? undefined : idOf.get(resolved);
|
|
535
|
+
if (id !== undefined) return registry.load(id);
|
|
536
|
+
}
|
|
537
|
+
return origLoad.call(this, request, parent, ...rest);
|
|
538
|
+
};
|
|
539
|
+
return true;
|
|
540
|
+
}
|
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.
|
|
@@ -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;
|
package/dist/native/resolve.mjs
CHANGED
|
@@ -4,21 +4,29 @@
|
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Metro's default `sourceExts`, in its order. Kept as data rather than spelled out
|
|
9
|
+
* per platform so the Vite graph and the Node graph cannot drift apart — both build
|
|
10
|
+
* their list from this one array (see `getPlatformExtensions` in ../resolve.ts).
|
|
11
|
+
*
|
|
12
|
+
* The order is load-bearing where a module has more than one variant on disk:
|
|
13
|
+
* Metro picks `Foo.js` over `Foo.tsx`, so this list must too, or a project with a
|
|
14
|
+
* compiled file beside its source tests a different file than it ships. `json` is
|
|
15
|
+
* a source extension to Metro, which is why `import config from './config'`
|
|
16
|
+
* resolves `config.json` in an app.
|
|
17
|
+
*/
|
|
18
|
+
export const METRO_SOURCE_EXTS = ["js", "jsx", "json", "ts", "tsx"];
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Metro tries every platform-suffixed variant first, then every `.native` one,
|
|
22
|
+
* then the bare extensions — not extension-major.
|
|
23
|
+
*/
|
|
24
|
+
export function extensionsFor(platform) {
|
|
8
25
|
const suffix = platform === "android" ? "android" : "ios";
|
|
9
26
|
return [
|
|
10
|
-
`.${suffix}
|
|
11
|
-
|
|
12
|
-
`.${
|
|
13
|
-
`.${suffix}.js`,
|
|
14
|
-
".native.tsx",
|
|
15
|
-
".native.ts",
|
|
16
|
-
".native.jsx",
|
|
17
|
-
".native.js",
|
|
18
|
-
".tsx",
|
|
19
|
-
".ts",
|
|
20
|
-
".jsx",
|
|
21
|
-
".js",
|
|
27
|
+
...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
|
|
28
|
+
...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
|
|
29
|
+
...METRO_SOURCE_EXTS.map((e) => `.${e}`),
|
|
22
30
|
];
|
|
23
31
|
}
|
|
24
32
|
|