vitest-native 0.13.0 → 0.14.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +339 -0
- package/README.md +138 -48
- package/dist/cli.cjs +70 -5
- package/dist/cli.d.cts +2 -3
- package/dist/cli.d.mts +2 -3
- package/dist/cli.mjs +70 -5
- package/dist/{ecosystem-Duw40-mO.mjs → ecosystem-DFbU_MPe.mjs} +389 -18
- package/dist/{ecosystem-CEIF_-jq.cjs → ecosystem-DI1AhK_k.cjs} +408 -25
- package/dist/errors.d.mts +12 -0
- package/dist/helpers.cjs +6 -3
- package/dist/helpers.d.cts +8 -9
- package/dist/helpers.d.mts +8 -9
- package/dist/helpers.mjs +6 -3
- package/dist/{index-CPGq6p95.d.cts → index-BxzW2D7K.d.cts} +33 -9
- package/dist/{index-CmETArCM.d.mts → index-CEbwa4QU.d.mts} +33 -9
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +537 -118
- package/dist/jest-compat/aliases.d.mts +5 -0
- package/dist/jest-compat/aliases.mjs +65 -0
- package/dist/jest-compat/caller.mjs +53 -0
- package/dist/jest-compat/setup.mjs +72 -36
- package/dist/jest-compat.cjs +1 -3
- package/dist/jest-compat.d.cts +4 -5
- package/dist/jest-compat.d.mts +4 -5
- package/dist/jest-compat.mjs +1 -1
- package/dist/matchers.d.cts +9 -9
- package/dist/matchers.d.mts +9 -9
- package/dist/memory-6EPHrJA1.cjs +144 -0
- package/dist/memory-FYbP0_gg.mjs +126 -0
- package/dist/native/boundary.mjs +13 -2
- package/dist/native/bounded-process.mjs +165 -0
- package/dist/native/export-condition-recovery-preload.mjs +5 -0
- package/dist/native/export-condition-recovery.mjs +195 -0
- package/dist/native/globals.mjs +133 -5
- package/dist/native/hooks.mjs +131 -71
- package/dist/native/loader.mjs +41 -28
- package/dist/native/match.d.mts +3 -0
- package/dist/native/match.mjs +38 -2
- package/dist/native/metro-profile-compiler.mjs +234 -0
- package/dist/native/metro-profile.mjs +115 -0
- package/dist/native/module-reset.mjs +111 -6
- package/dist/native/ownership.d.mts +105 -0
- package/dist/native/ownership.mjs +474 -0
- package/dist/native/registry-compiler.mjs +43 -0
- package/dist/native/registry-process.mjs +124 -0
- package/dist/native/registry.mjs +139 -32
- package/dist/native/reset.mjs +305 -135
- package/dist/native/resolve.d.mts +20 -3
- package/dist/native/resolve.mjs +32 -12
- package/dist/native/rntl-hooks.mjs +76 -0
- package/dist/native/setup.mjs +81 -32
- package/dist/native/state-manifest.d.mts +22 -0
- package/dist/native/state-manifest.mjs +136 -0
- package/dist/native/transform.mjs +29 -8
- package/dist/native/worker.mjs +52 -4
- package/dist/pool-B4yesGhI.cjs +121 -0
- package/dist/pool-DjpOjOf3.mjs +119 -0
- package/dist/{presets-CoNf4ByH.cjs → presets-BYHmi7-W.cjs} +117 -18
- package/dist/{presets-DGProTaA.mjs → presets-DC-eM5IA.mjs} +117 -18
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/rntl-matchers.d.ts +58 -12
- package/dist/serializer.cjs +4 -2
- package/dist/serializer.d.cts +3 -4
- package/dist/serializer.d.mts +3 -4
- package/dist/serializer.mjs +4 -2
- package/dist/setup.mjs +61 -50
- package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
- package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
- package/docs/hot-default-design.md +175 -88
- package/docs/migrating-from-jest.md +12 -5
- package/docs/migrating-from-vitest-react-native.md +4 -4
- package/docs/release-readiness.md +39 -13
- package/docs/versioning.md +19 -18
- package/package.json +42 -31
- package/dist/pool-BU-1ecIF.cjs +0 -122
- package/dist/pool-Bcxn9a3I.mjs +0 -118
package/dist/native/loader.mjs
CHANGED
|
@@ -5,15 +5,14 @@ import path from "node:path";
|
|
|
5
5
|
import fs from "node:fs";
|
|
6
6
|
import { transformRN, isFlow, cjsExportNames, needsTransform } from "./transform.mjs";
|
|
7
7
|
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
|
-
import { resolvePlatformFile, resolveDeepPackageFile } from "./resolve.mjs";
|
|
8
|
+
import { extensionsFor, resolvePlatformFile, resolveDeepPackageFile } from "./resolve.mjs";
|
|
9
|
+
import { NODE_MODULES_PATH, isUtilitySubpath, packageNameOf, subpathLeafOf } from "./match.mjs";
|
|
9
10
|
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
subpathLeafOf,
|
|
16
|
-
} from "./match.mjs";
|
|
11
|
+
createNativeOwnershipPolicy,
|
|
12
|
+
isRuntimeResidentFile,
|
|
13
|
+
isTestRuntimeResidentFile,
|
|
14
|
+
parseNativeOwnershipManifest,
|
|
15
|
+
} from "./ownership.mjs";
|
|
17
16
|
|
|
18
17
|
// Any file living under a node_modules directory. Platform-extension resolution
|
|
19
18
|
// (`.native.js` etc.) applies to every node_modules package, not just RN, matching
|
|
@@ -24,7 +23,6 @@ import {
|
|
|
24
23
|
const RN_INDEX = /[\\/]react-native[\\/]index\.js$/;
|
|
25
24
|
const TRANSFORMABLE = /\.(jsx?|tsx?|mjs|cjs)$/;
|
|
26
25
|
// Extensions/index candidates for bundler-style extensionless resolution.
|
|
27
|
-
const RESOLVE_EXTS = [".js", ".cjs", ".mjs", ".json", ".jsx", ".ts", ".tsx"];
|
|
28
26
|
|
|
29
27
|
/**
|
|
30
28
|
* Bundler-style resolution for an extensionless relative import: try `base+ext`
|
|
@@ -34,11 +32,14 @@ const RESOLVE_EXTS = [".js", ".cjs", ".mjs", ".json", ".jsx", ".ts", ".tsx"];
|
|
|
34
32
|
* `./WebView`). Returns the on-disk path, or null.
|
|
35
33
|
*/
|
|
36
34
|
function resolveExtensionless(base) {
|
|
37
|
-
|
|
35
|
+
const extensions = HAS_SOURCE_PROFILE
|
|
36
|
+
? extensionsFor(PLATFORM, SOURCE_EXTS)
|
|
37
|
+
: [".js", ".cjs", ".mjs", ".json", ".jsx", ".ts", ".tsx"];
|
|
38
|
+
for (const ext of extensions) {
|
|
38
39
|
const f = base + ext;
|
|
39
40
|
if (fs.existsSync(f)) return f;
|
|
40
41
|
}
|
|
41
|
-
for (const ext of
|
|
42
|
+
for (const ext of extensions) {
|
|
42
43
|
const f = path.join(base, "index" + ext);
|
|
43
44
|
if (fs.existsSync(f)) return f;
|
|
44
45
|
}
|
|
@@ -49,7 +50,10 @@ const PRESET_SCHEME = "vitest-native-preset:";
|
|
|
49
50
|
let PROJECT_ROOT = process.cwd();
|
|
50
51
|
let PLATFORM = "ios";
|
|
51
52
|
let REACT_NATIVE_VERSION = "0.0.0";
|
|
53
|
+
let SOURCE_EXTS = ["js", "jsx", "json", "ts", "tsx"];
|
|
54
|
+
let HAS_SOURCE_PROFILE = false;
|
|
52
55
|
let isExtra = () => false;
|
|
56
|
+
let ownership = createNativeOwnershipPolicy({ projectRoot: PROJECT_ROOT });
|
|
53
57
|
// Preset package name → its mock's named-export list (from the preset definition).
|
|
54
58
|
let presetExports = {};
|
|
55
59
|
// Asset file extensions (without leading dot, lower-cased) the loader should stub.
|
|
@@ -75,10 +79,6 @@ let assetExtSet = new Set();
|
|
|
75
79
|
*/
|
|
76
80
|
let genView = null;
|
|
77
81
|
const generationOf = () => (genView ? Atomics.load(genView, 0) : 0);
|
|
78
|
-
// Modules whose identity must be stable across files: dropping them makes a twin
|
|
79
|
-
// rather than a fresh copy. Mirrors KEEP_RESIDENT in module-reset.mjs.
|
|
80
|
-
const KEEP_RESIDENT =
|
|
81
|
-
/[\\/]node_modules[\\/](react|react-is|react-dom|scheduler|react-reconciler|react-test-renderer|test-renderer|@testing-library[\\/]react-native)[\\/]/;
|
|
82
82
|
// The test stack itself: Vitest's runtime, the chai it asserts through, and this
|
|
83
83
|
// engine. The worker's runtime holds instances of these from boot — the runner's
|
|
84
84
|
// SnapshotClient, chai's extended Assertion, the engine's registry and hooks — and a
|
|
@@ -92,10 +92,8 @@ const KEEP_RESIDENT =
|
|
|
92
92
|
// below exempts the engine by accident of layout. Only a packed install — the
|
|
93
93
|
// bake-off apps — puts the whole test stack under node_modules where stamping can
|
|
94
94
|
// reach it. That is how this list was earned: react-native-paper under the hot
|
|
95
|
-
// runtime, 603/678 -> 473/648, every extra failure a twin-runtime symptom.
|
|
96
|
-
|
|
97
|
-
/[\\/]node_modules[\\/](vitest|@vitest[\\/][^\\/]+|chai|vitest-native)[\\/]/;
|
|
98
|
-
|
|
95
|
+
// runtime, 603/678 -> 473/648, every extra failure a twin-runtime symptom. The
|
|
96
|
+
// actual resident package rules live once in ownership.mjs.
|
|
99
97
|
/** Should this resolved file carry a generation stamp? */
|
|
100
98
|
function versionable(url) {
|
|
101
99
|
if (!genView || !url.startsWith("file:")) return false;
|
|
@@ -103,16 +101,25 @@ function versionable(url) {
|
|
|
103
101
|
if (!NODE_MODULES_PATH.test(norm)) return false;
|
|
104
102
|
// React Native itself is preloaded once per worker and shared deliberately —
|
|
105
103
|
// re-instantiating it per file would undo the reason the worker stays warm.
|
|
106
|
-
if (
|
|
107
|
-
if (
|
|
104
|
+
if (ownership.isReactNativeFile(norm) || isRuntimeResidentFile(norm)) return false;
|
|
105
|
+
if (isTestRuntimeResidentFile(norm)) return false;
|
|
108
106
|
return true;
|
|
109
107
|
}
|
|
110
108
|
|
|
111
109
|
export async function initialize(data) {
|
|
112
110
|
if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
|
|
113
|
-
|
|
111
|
+
PLATFORM = data?.platform === "android" ? "android" : "ios";
|
|
114
112
|
if (data && data.reactNativeVersion) REACT_NATIVE_VERSION = data.reactNativeVersion;
|
|
115
|
-
|
|
113
|
+
HAS_SOURCE_PROFILE = Array.isArray(data?.sourceExts);
|
|
114
|
+
SOURCE_EXTS = HAS_SOURCE_PROFILE ? data.sourceExts : ["js", "jsx", "json", "ts", "tsx"];
|
|
115
|
+
const configuredOwnership = parseNativeOwnershipManifest(process.env.VITEST_NATIVE_OWNERSHIP);
|
|
116
|
+
ownership = createNativeOwnershipPolicy({
|
|
117
|
+
projectRoot: PROJECT_ROOT,
|
|
118
|
+
projectDirs: configuredOwnership?.projectDirs ?? [],
|
|
119
|
+
reactNativeRoots: configuredOwnership?.reactNativeRoots ?? [],
|
|
120
|
+
runtimeTransforms: data?.transformPkgs ?? [],
|
|
121
|
+
});
|
|
122
|
+
isExtra = ownership.matchesNodeTransformedFile;
|
|
116
123
|
if (data && data.presetExports) presetExports = data.presetExports;
|
|
117
124
|
if (data && data.assetExts)
|
|
118
125
|
assetExtSet = new Set(data.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
|
|
@@ -149,11 +156,15 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
149
156
|
let resolved;
|
|
150
157
|
if (
|
|
151
158
|
parent &&
|
|
152
|
-
(NODE_MODULES_PATH.test(parent) ||
|
|
159
|
+
(NODE_MODULES_PATH.test(parent) || ownership.isReactNativeFile(parent) || isExtra(parent)) &&
|
|
153
160
|
specifier.startsWith(".") &&
|
|
154
161
|
!path.extname(specifier)
|
|
155
162
|
) {
|
|
156
|
-
const hit = resolvePlatformFile(
|
|
163
|
+
const hit = resolvePlatformFile(
|
|
164
|
+
path.resolve(path.dirname(parent), specifier),
|
|
165
|
+
PLATFORM,
|
|
166
|
+
SOURCE_EXTS,
|
|
167
|
+
);
|
|
157
168
|
// Not returned directly: `json` is a Metro source extension, so this can now
|
|
158
169
|
// land on a .json file, which still needs the import attribute injected below.
|
|
159
170
|
if (hit) resolved = { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
@@ -177,6 +188,7 @@ export async function resolve(specifier, context, nextResolve) {
|
|
|
177
188
|
specifier,
|
|
178
189
|
parent ? path.dirname(parent) : PROJECT_ROOT,
|
|
179
190
|
PLATFORM,
|
|
191
|
+
SOURCE_EXTS,
|
|
180
192
|
);
|
|
181
193
|
if (deep) resolved = { url: pathToFileURL(deep).href, shortCircuit: true };
|
|
182
194
|
}
|
|
@@ -263,7 +275,8 @@ export async function load(url, context, nextLoad) {
|
|
|
263
275
|
};
|
|
264
276
|
}
|
|
265
277
|
|
|
266
|
-
const
|
|
278
|
+
const rnPath = ownership.reactNativePathFor(file);
|
|
279
|
+
const isRN = rnPath !== null;
|
|
267
280
|
if (!isRN && !isExtra(norm)) return nextLoad(url, context);
|
|
268
281
|
|
|
269
282
|
if (isRN) {
|
|
@@ -278,7 +291,7 @@ export async function load(url, context, nextLoad) {
|
|
|
278
291
|
// of react-native here goes through the separate Module._extensions hook
|
|
279
292
|
// (hooks.mjs), not this loader, so there's no recursion. Names come from the
|
|
280
293
|
// index's own `get X()` declarations.
|
|
281
|
-
if (RN_INDEX.test(
|
|
294
|
+
if (RN_INDEX.test(rnPath)) {
|
|
282
295
|
const src = fs.readFileSync(file, "utf8");
|
|
283
296
|
const names = [
|
|
284
297
|
...new Set([...src.matchAll(/\bget\s+([A-Za-z_$][\w$]*)\s*\(/g)].map((m) => m[1])),
|
|
@@ -290,7 +303,7 @@ export async function load(url, context, nextLoad) {
|
|
|
290
303
|
].join("\n");
|
|
291
304
|
return { format: "commonjs", source: facade, shortCircuit: true };
|
|
292
305
|
}
|
|
293
|
-
const boundary = boundarySourceFor(
|
|
306
|
+
const boundary = boundarySourceFor(rnPath, PLATFORM, REACT_NATIVE_VERSION);
|
|
294
307
|
if (boundary != null) return { format: "commonjs", source: boundary, shortCircuit: true };
|
|
295
308
|
if (norm.endsWith(".js")) {
|
|
296
309
|
const src = fs.readFileSync(file, "utf8");
|
package/dist/native/match.d.mts
CHANGED
|
@@ -7,6 +7,9 @@ export declare const REACT_NATIVE_PATH: RegExp;
|
|
|
7
7
|
/** Does `dir` contain `target` (or equal it)? Case-insensitive on Windows. */
|
|
8
8
|
export declare function containsPath(dir: string, target: string): boolean;
|
|
9
9
|
|
|
10
|
+
/** A consumer-visible package directory in node_modules at/above the project, or null. */
|
|
11
|
+
export declare function installedPackageDirOf(name: string, projectRoot: string): string | null;
|
|
12
|
+
|
|
10
13
|
/** The on-disk directory a package resolves to from `projectRoot`, or null. */
|
|
11
14
|
export declare function packageDirOf(name: string, projectRoot: string): string | null;
|
|
12
15
|
|
package/dist/native/match.mjs
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* would exist twice.
|
|
22
22
|
*/
|
|
23
23
|
import { createRequire } from "node:module";
|
|
24
|
+
import fs from "node:fs";
|
|
24
25
|
import path from "node:path";
|
|
25
26
|
|
|
26
27
|
/** Any file under a node_modules directory. */
|
|
@@ -33,6 +34,39 @@ export const NODE_MODULES_PATH = /[\\/]node_modules[\\/]/;
|
|
|
33
34
|
*/
|
|
34
35
|
export const REACT_NATIVE_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
|
|
35
36
|
|
|
37
|
+
/**
|
|
38
|
+
* A directory in the form Node's module loader reports paths: fs.realpathSync, not
|
|
39
|
+
* realpathSync.native. The native call expands Windows 8.3 short names (RUNNER~1) and
|
|
40
|
+
* rewrites letter case on case-insensitive disks, so a directory it returns can fail
|
|
41
|
+
* to contain the module ids Node hands the matchers.
|
|
42
|
+
*/
|
|
43
|
+
function canonicalDir(dir) {
|
|
44
|
+
try {
|
|
45
|
+
return fs.realpathSync(dir);
|
|
46
|
+
} catch {
|
|
47
|
+
return dir;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Resolve only from a physical node_modules directory at/above the project.
|
|
53
|
+
*
|
|
54
|
+
* Unlike createRequire.resolve(), this deliberately ignores NODE_PATH and loader
|
|
55
|
+
* hooks. It is for dependencies whose presence must be consumer-visible rather than
|
|
56
|
+
* borrowed from the test runner's own install.
|
|
57
|
+
*/
|
|
58
|
+
export function installedPackageDirOf(name, projectRoot) {
|
|
59
|
+
const packagePath = name.split("/");
|
|
60
|
+
let dir = path.resolve(projectRoot);
|
|
61
|
+
for (;;) {
|
|
62
|
+
const candidate = path.join(dir, "node_modules", ...packagePath);
|
|
63
|
+
if (fs.existsSync(path.join(candidate, "package.json"))) return canonicalDir(candidate);
|
|
64
|
+
const parent = path.dirname(dir);
|
|
65
|
+
if (parent === dir) return null;
|
|
66
|
+
dir = parent;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
36
70
|
/** Escape a string for literal use inside a RegExp. */
|
|
37
71
|
function escapeRe(value) {
|
|
38
72
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -76,7 +110,7 @@ export function containsPath(dir, target) {
|
|
|
76
110
|
export function packageDirOf(name, projectRoot) {
|
|
77
111
|
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
78
112
|
try {
|
|
79
|
-
return path.dirname(req.resolve(`${name}/package.json`));
|
|
113
|
+
return canonicalDir(path.dirname(req.resolve(`${name}/package.json`)));
|
|
80
114
|
} catch {}
|
|
81
115
|
let dir;
|
|
82
116
|
try {
|
|
@@ -86,7 +120,9 @@ export function packageDirOf(name, projectRoot) {
|
|
|
86
120
|
}
|
|
87
121
|
for (;;) {
|
|
88
122
|
try {
|
|
89
|
-
if (createRequire(path.join(dir, "index.js"))("./package.json").name === name)
|
|
123
|
+
if (createRequire(path.join(dir, "index.js"))("./package.json").name === name) {
|
|
124
|
+
return canonicalDir(dir);
|
|
125
|
+
}
|
|
90
126
|
} catch {}
|
|
91
127
|
const parent = path.dirname(dir);
|
|
92
128
|
if (parent === dir) return null;
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// Short-lived Metro configuration evaluator. Only JSON crosses fd 3.
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { VitestNativeError } from "../errors.mjs";
|
|
7
|
+
|
|
8
|
+
const BARE_SOURCE_EXTS = ["js", "jsx", "json", "ts", "tsx"];
|
|
9
|
+
const BARE_ASSET_EXTS = [
|
|
10
|
+
"bmp",
|
|
11
|
+
"gif",
|
|
12
|
+
"jpg",
|
|
13
|
+
"jpeg",
|
|
14
|
+
"png",
|
|
15
|
+
"psd",
|
|
16
|
+
"svg",
|
|
17
|
+
"webp",
|
|
18
|
+
"xml",
|
|
19
|
+
"m4v",
|
|
20
|
+
"mov",
|
|
21
|
+
"mp4",
|
|
22
|
+
"mpeg",
|
|
23
|
+
"mpg",
|
|
24
|
+
"webm",
|
|
25
|
+
"aac",
|
|
26
|
+
"aiff",
|
|
27
|
+
"caf",
|
|
28
|
+
"m4a",
|
|
29
|
+
"mp3",
|
|
30
|
+
"wav",
|
|
31
|
+
"html",
|
|
32
|
+
"pdf",
|
|
33
|
+
"yaml",
|
|
34
|
+
"yml",
|
|
35
|
+
"otf",
|
|
36
|
+
"ttf",
|
|
37
|
+
"zip",
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
// The message, not the stack: this becomes a user-facing configuration error.
|
|
41
|
+
function messageOf(error) {
|
|
42
|
+
return error instanceof Error ? error.message : String(error);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function respond(value) {
|
|
46
|
+
fs.writeSync(3, JSON.stringify(value));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function canResolve(req, id) {
|
|
50
|
+
try {
|
|
51
|
+
req.resolve(id);
|
|
52
|
+
return true;
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function findConfig(projectRoot, explicit) {
|
|
59
|
+
if (explicit) return path.resolve(projectRoot, explicit);
|
|
60
|
+
for (const relative of [
|
|
61
|
+
"metro.config.js",
|
|
62
|
+
"metro.config.cjs",
|
|
63
|
+
"metro.config.mjs",
|
|
64
|
+
"metro.config.json",
|
|
65
|
+
"metro.config.ts",
|
|
66
|
+
"metro.config.cts",
|
|
67
|
+
"metro.config.mts",
|
|
68
|
+
".config/metro.js",
|
|
69
|
+
".config/metro.cjs",
|
|
70
|
+
".config/metro.mjs",
|
|
71
|
+
".config/metro.json",
|
|
72
|
+
".config/metro.ts",
|
|
73
|
+
".config/metro.cts",
|
|
74
|
+
".config/metro.mts",
|
|
75
|
+
]) {
|
|
76
|
+
const candidate = path.join(projectRoot, relative);
|
|
77
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;
|
|
78
|
+
}
|
|
79
|
+
const packageFile = path.join(projectRoot, "package.json");
|
|
80
|
+
try {
|
|
81
|
+
const pkg = JSON.parse(fs.readFileSync(packageFile, "utf8"));
|
|
82
|
+
if (pkg.metro && typeof pkg.metro === "object" && !Array.isArray(pkg.metro)) {
|
|
83
|
+
return packageFile;
|
|
84
|
+
}
|
|
85
|
+
} catch {}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function importConfig(configPath, req) {
|
|
90
|
+
if (!configPath) return null;
|
|
91
|
+
if (path.basename(configPath) === "package.json") {
|
|
92
|
+
return JSON.parse(fs.readFileSync(configPath, "utf8")).metro;
|
|
93
|
+
}
|
|
94
|
+
let loaded;
|
|
95
|
+
try {
|
|
96
|
+
loaded = req(configPath);
|
|
97
|
+
} catch (requireError) {
|
|
98
|
+
// Retrying ordinary evaluation failures can execute side effects twice.
|
|
99
|
+
// Only a loader-format refusal warrants switching to dynamic import.
|
|
100
|
+
if (!["ERR_REQUIRE_ESM", "ERR_REQUIRE_ASYNC_MODULE"].includes(requireError.code)) {
|
|
101
|
+
throw requireError;
|
|
102
|
+
}
|
|
103
|
+
loaded = await import(pathToFileURL(configPath).href);
|
|
104
|
+
}
|
|
105
|
+
loaded = await loaded;
|
|
106
|
+
return loaded?.__esModule ? loaded.default : (loaded?.default ?? loaded);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function fallbackDefault(projectRoot) {
|
|
110
|
+
return {
|
|
111
|
+
projectRoot,
|
|
112
|
+
resolver: {
|
|
113
|
+
sourceExts: [...BARE_SOURCE_EXTS],
|
|
114
|
+
assetExts: [...BARE_ASSET_EXTS],
|
|
115
|
+
resolverMainFields: ["react-native", "browser", "main"],
|
|
116
|
+
unstable_conditionNames: ["react-native"],
|
|
117
|
+
unstable_conditionsByPlatform: {},
|
|
118
|
+
resolveRequest: null,
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function mergeFallback(base, next) {
|
|
124
|
+
return {
|
|
125
|
+
...base,
|
|
126
|
+
...next,
|
|
127
|
+
resolver: { ...base.resolver, ...next?.resolver },
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function loadFallback(projectRoot, configPath, req) {
|
|
132
|
+
const defaults = fallbackDefault(projectRoot);
|
|
133
|
+
const raw = await importConfig(configPath, req);
|
|
134
|
+
const resolved = typeof raw === "function" ? await raw(defaults) : raw;
|
|
135
|
+
return resolved ? mergeFallback(defaults, resolved) : defaults;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function loadReactNative(projectRoot, configPath, req) {
|
|
139
|
+
if (!canResolve(req, "@react-native/metro-config")) {
|
|
140
|
+
return { config: await loadFallback(projectRoot, configPath, req), framework: "fallback" };
|
|
141
|
+
}
|
|
142
|
+
const rnMetroPath = req.resolve("@react-native/metro-config");
|
|
143
|
+
const rnMetro = req(rnMetroPath);
|
|
144
|
+
const defaults = await rnMetro.getDefaultConfig(projectRoot);
|
|
145
|
+
if (!configPath) return { config: defaults, framework: "react-native" };
|
|
146
|
+
|
|
147
|
+
// Resolve/load through the exact metro-config paired with the project's RN
|
|
148
|
+
// configuration package. This preserves its JS/TS/ESM support and avoids a
|
|
149
|
+
// hidden dependency from vitest-native to a possibly incompatible Metro.
|
|
150
|
+
const metroReq = createRequire(rnMetroPath);
|
|
151
|
+
const metro = metroReq("metro-config");
|
|
152
|
+
const rawResult = await metro.resolveConfig(configPath, projectRoot);
|
|
153
|
+
const raw = rawResult.config;
|
|
154
|
+
const resolved = typeof raw === "function" ? await raw(defaults) : raw;
|
|
155
|
+
return {
|
|
156
|
+
config: resolved ? await metro.mergeConfig(defaults, resolved) : defaults,
|
|
157
|
+
framework: "react-native",
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function loadProject(input) {
|
|
162
|
+
const projectRoot = path.resolve(input.projectRoot);
|
|
163
|
+
// Configs commonly resolve relative paths from cwd. Each child belongs to one
|
|
164
|
+
// project, so workspace config evaluation cannot inherit another project's cwd.
|
|
165
|
+
process.chdir(projectRoot);
|
|
166
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
167
|
+
const configPath = findConfig(projectRoot, input.configFile);
|
|
168
|
+
let loaded;
|
|
169
|
+
if (canResolve(req, "expo/package.json")) {
|
|
170
|
+
const expoMetro = req("expo/metro-config");
|
|
171
|
+
if (typeof expoMetro.loadUserConfig === "function") {
|
|
172
|
+
loaded = {
|
|
173
|
+
config: await expoMetro.loadUserConfig({
|
|
174
|
+
projectRoot,
|
|
175
|
+
serverRoot: projectRoot,
|
|
176
|
+
overrideConfigPath: configPath ?? undefined,
|
|
177
|
+
}),
|
|
178
|
+
framework: "expo",
|
|
179
|
+
};
|
|
180
|
+
} else {
|
|
181
|
+
// Older Expo releases expose getDefaultConfig but not loadUserConfig.
|
|
182
|
+
// Evaluate the local override against Expo's own default and merge the
|
|
183
|
+
// declarative resolver portion; the child still dies after extraction.
|
|
184
|
+
const defaults = await expoMetro.getDefaultConfig(projectRoot);
|
|
185
|
+
const raw = await importConfig(configPath, req);
|
|
186
|
+
const resolved = typeof raw === "function" ? await raw(defaults) : raw;
|
|
187
|
+
loaded = {
|
|
188
|
+
config: resolved ? mergeFallback(defaults, resolved) : defaults,
|
|
189
|
+
framework: "expo",
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
} else {
|
|
193
|
+
loaded = await loadReactNative(projectRoot, configPath, req);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const resolver = loaded.config?.resolver;
|
|
197
|
+
if (!resolver || !Array.isArray(resolver.sourceExts) || !Array.isArray(resolver.assetExts)) {
|
|
198
|
+
throw new VitestNativeError(
|
|
199
|
+
"METRO_PROFILE_INVALID",
|
|
200
|
+
"resolved Metro config has no resolver.sourceExts/assetExts arrays",
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
const byPlatform = resolver.unstable_conditionsByPlatform?.[input.platform] ?? [];
|
|
204
|
+
return {
|
|
205
|
+
schemaVersion: 1,
|
|
206
|
+
framework: loaded.framework,
|
|
207
|
+
configPath,
|
|
208
|
+
sourceExts: resolver.sourceExts,
|
|
209
|
+
assetExts: resolver.assetExts,
|
|
210
|
+
resolverMainFields: resolver.resolverMainFields ?? ["react-native", "browser", "main"],
|
|
211
|
+
conditionNames: [...new Set([...(resolver.unstable_conditionNames ?? []), ...byPlatform])],
|
|
212
|
+
customResolver: typeof resolver.resolveRequest === "function",
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
try {
|
|
217
|
+
const input = JSON.parse(fs.readFileSync(0, "utf8"));
|
|
218
|
+
const started = performance.now();
|
|
219
|
+
const profile = await loadProject(input);
|
|
220
|
+
respond({
|
|
221
|
+
ok: true,
|
|
222
|
+
profile,
|
|
223
|
+
durationMs: Math.round(performance.now() - started),
|
|
224
|
+
heapUsed: process.memoryUsage().heapUsed,
|
|
225
|
+
rss: process.memoryUsage().rss,
|
|
226
|
+
});
|
|
227
|
+
// Exit explicitly: the config is arbitrary code, and a timer, watcher or socket it
|
|
228
|
+
// leaves open would otherwise hold the child until the parent's timeout, turning a
|
|
229
|
+
// profile already written to fd 3 into a timeout. respond() writes synchronously.
|
|
230
|
+
process.exit(0);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
respond({ ok: false, error: messageOf(error) });
|
|
233
|
+
process.exit(1);
|
|
234
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Parent-side loader for the small, declarative portion of Metro configuration
|
|
2
|
+
// that can safely inform the test resolver.
|
|
3
|
+
//
|
|
4
|
+
// Metro and Expo configuration bring a large build-tool graph with them and may
|
|
5
|
+
// execute user code. Keep that graph in a short-lived child and return data only;
|
|
6
|
+
// the Vite main process must never retain Metro module identities.
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { runBoundedProcess } from "./bounded-process.mjs";
|
|
9
|
+
import { VitestNativeError, VitestNativeTypeError } from "../errors.mjs";
|
|
10
|
+
|
|
11
|
+
const INITIAL_HEAP_MB = 128;
|
|
12
|
+
const RETRY_HEAP_MB = 256;
|
|
13
|
+
const TIMEOUT_MS = 30_000;
|
|
14
|
+
|
|
15
|
+
function stringArray(value, field, { allowEmpty = false } = {}) {
|
|
16
|
+
if (!Array.isArray(value) || (!allowEmpty && value.length === 0)) {
|
|
17
|
+
throw new VitestNativeTypeError(
|
|
18
|
+
"METRO_PROFILE_INVALID",
|
|
19
|
+
`Metro profile returned invalid ${field}`,
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
const result = [];
|
|
23
|
+
const seen = new Set();
|
|
24
|
+
for (const item of value) {
|
|
25
|
+
if (
|
|
26
|
+
typeof item !== "string" ||
|
|
27
|
+
item.length === 0 ||
|
|
28
|
+
// Metro accepts compound extensions such as `web.js`; separators never belong.
|
|
29
|
+
((field === "sourceExts" || field === "assetExts") &&
|
|
30
|
+
!/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*$/.test(item))
|
|
31
|
+
) {
|
|
32
|
+
throw new VitestNativeTypeError(
|
|
33
|
+
"METRO_PROFILE_INVALID",
|
|
34
|
+
`Metro profile returned invalid ${field}`,
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
if (!seen.has(item)) {
|
|
38
|
+
seen.add(item);
|
|
39
|
+
result.push(item);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Validate the untrusted child payload before it becomes resolver policy. */
|
|
46
|
+
export function validateMetroProfile(value, projectRoot) {
|
|
47
|
+
if (!value || typeof value !== "object" || value.schemaVersion !== 1) {
|
|
48
|
+
throw new VitestNativeTypeError(
|
|
49
|
+
"METRO_PROFILE_INVALID",
|
|
50
|
+
"Metro profile returned an unsupported schema",
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
if (!["expo", "react-native", "fallback"].includes(value.framework)) {
|
|
54
|
+
throw new VitestNativeTypeError(
|
|
55
|
+
"METRO_PROFILE_INVALID",
|
|
56
|
+
"Metro profile returned an invalid framework",
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
schemaVersion: 1,
|
|
61
|
+
projectRoot,
|
|
62
|
+
framework: value.framework,
|
|
63
|
+
configPath: typeof value.configPath === "string" ? value.configPath : null,
|
|
64
|
+
sourceExts: Object.freeze(stringArray(value.sourceExts, "sourceExts")),
|
|
65
|
+
assetExts: Object.freeze(stringArray(value.assetExts, "assetExts", { allowEmpty: true })),
|
|
66
|
+
resolverMainFields: Object.freeze(stringArray(value.resolverMainFields, "resolverMainFields")),
|
|
67
|
+
conditionNames: Object.freeze(
|
|
68
|
+
stringArray(value.conditionNames, "conditionNames", { allowEmpty: true }),
|
|
69
|
+
),
|
|
70
|
+
customResolver: value.customResolver === true,
|
|
71
|
+
provenance: value.configPath ? "metro-config" : `${value.framework}-default`,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Evaluate one project's Metro configuration in a bounded child. This is an
|
|
77
|
+
* opt-in experiment consumed by the plugin's metroConfig option.
|
|
78
|
+
*/
|
|
79
|
+
export async function loadMetroProfile(
|
|
80
|
+
{ projectRoot, platform = "ios", configFile },
|
|
81
|
+
runner = runBoundedProcess,
|
|
82
|
+
) {
|
|
83
|
+
const result = await runner(
|
|
84
|
+
fileURLToPath(new URL("./metro-profile-compiler.mjs", import.meta.url)),
|
|
85
|
+
{ projectRoot, platform, configFile },
|
|
86
|
+
{
|
|
87
|
+
initialHeapMb: INITIAL_HEAP_MB,
|
|
88
|
+
retryHeapMb: RETRY_HEAP_MB,
|
|
89
|
+
timeoutMs: TIMEOUT_MS,
|
|
90
|
+
label: "Metro profile loader",
|
|
91
|
+
},
|
|
92
|
+
);
|
|
93
|
+
if (!result.ok) {
|
|
94
|
+
throw new VitestNativeError(
|
|
95
|
+
"METRO_CONFIG_LOAD_FAILED",
|
|
96
|
+
`Could not load Metro profile: ${result.error ?? "unknown child failure"}`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
profile: validateMetroProfile(result.profile, projectRoot),
|
|
101
|
+
evidence: Object.freeze({
|
|
102
|
+
durationMs: result.durationMs,
|
|
103
|
+
heapUsed: result.heapUsed,
|
|
104
|
+
rss: result.rss,
|
|
105
|
+
heapMb: result.heapMb,
|
|
106
|
+
attempts: result.attempts,
|
|
107
|
+
}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const metroProfileProcessDefaults = Object.freeze({
|
|
112
|
+
initialHeapMb: INITIAL_HEAP_MB,
|
|
113
|
+
retryHeapMb: RETRY_HEAP_MB,
|
|
114
|
+
timeoutMs: TIMEOUT_MS,
|
|
115
|
+
});
|