vitest-native 0.13.0 → 0.14.0-rc.1
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 +298 -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 +435 -95
- 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 +14 -3
- package/dist/native/resolve.mjs +10 -10
- 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 +21 -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/index.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
|
|
2
|
-
import { a as
|
|
2
|
+
import { a as findNativeOwnershipConflict, c as packageDirOf, d as validatePeerDependency, f as warnUnknownOptions, i as findNativeInlineConflicts, l as PEER_REQUIREMENTS, n as detectEngine, o as formatNativeOwnershipManifest, r as createNativeOwnershipPolicy, s as containsPath, t as detectEcosystemPackages, u as validateOptions } from "./ecosystem-DFbU_MPe.mjs";
|
|
3
3
|
import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
|
|
4
|
-
import { t as
|
|
4
|
+
import { t as workerVitestMismatch } from "./worker-vitest-BGPo0ek6.mjs";
|
|
5
|
+
import { t as presets_exports } from "./presets-DC-eM5IA.mjs";
|
|
5
6
|
import { createRequire } from "node:module";
|
|
6
7
|
import fs from "node:fs";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
10
|
+
import os from "node:os";
|
|
9
11
|
import flowRemoveTypes from "flow-remove-types";
|
|
10
12
|
//#region src/native/resolve.mjs
|
|
11
13
|
/**
|
|
@@ -40,10 +42,10 @@ const METRO_SOURCE_EXTS = [
|
|
|
40
42
|
* ships. The order is asserted against real metro-resolver by
|
|
41
43
|
* tests/metro-resolver-oracle.test.ts, not just against these literals.
|
|
42
44
|
*/
|
|
43
|
-
function extensionsFor(platform) {
|
|
45
|
+
function extensionsFor(platform, sourceExts = METRO_SOURCE_EXTS) {
|
|
44
46
|
const suffix = platform === "android" ? "android" : "ios";
|
|
45
47
|
const exts = [];
|
|
46
|
-
for (const e of
|
|
48
|
+
for (const e of sourceExts) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
|
|
47
49
|
return exts;
|
|
48
50
|
}
|
|
49
51
|
//#endregion
|
|
@@ -60,23 +62,62 @@ const PLATFORM_EXTENSIONS_ANDROID = extensionsFor("android");
|
|
|
60
62
|
function getPlatformExtensions(platform) {
|
|
61
63
|
return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
|
|
62
64
|
}
|
|
65
|
+
/** Build the shared Vite/Node candidate order for a resolved Metro profile. */
|
|
66
|
+
function getConfiguredPlatformExtensions(platform, sourceExts) {
|
|
67
|
+
return extensionsFor(platform, sourceExts);
|
|
68
|
+
}
|
|
63
69
|
//#endregion
|
|
64
|
-
//#region src/
|
|
70
|
+
//#region src/jest-compat/aliases.mjs
|
|
65
71
|
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
72
|
+
* The string-to-string entries of a Vite `resolve.alias`, in either of its shapes, with
|
|
73
|
+
* relative replacements made absolute against `root`. Regex `find`s and custom
|
|
74
|
+
* resolvers cannot cross into the test worker, so they are listed as `skipped` for the
|
|
75
|
+
* error that explains a miss.
|
|
68
76
|
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
77
|
+
* @param {unknown} alias `resolve.alias`: an object, or an array of `{ find, replacement }`
|
|
78
|
+
* @param {string} root project root, for relative replacements
|
|
79
|
+
* @returns {{ entries: [string, string][], skipped: string[] }}
|
|
72
80
|
*/
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
81
|
+
function serializableAliases(alias, root) {
|
|
82
|
+
const entries = [];
|
|
83
|
+
const skipped = [];
|
|
84
|
+
const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
|
|
85
|
+
find,
|
|
86
|
+
replacement
|
|
87
|
+
})) : [];
|
|
88
|
+
for (const item of list) {
|
|
89
|
+
const find = item?.find;
|
|
90
|
+
const replacement = item?.replacement;
|
|
91
|
+
if (typeof find !== "string" || typeof replacement !== "string" || item.customResolver) {
|
|
92
|
+
skipped.push(String(find));
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
entries.push([find, replacement.startsWith(".") ? path.resolve(root, replacement) : replacement]);
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
entries,
|
|
99
|
+
skipped
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/native/apply.ts
|
|
104
|
+
function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false, projectDirs = [], ownershipPolicy) {
|
|
105
|
+
const ownership = ownershipPolicy ?? createNativeOwnershipPolicy({
|
|
106
|
+
projectRoot,
|
|
107
|
+
explicitTransforms: transformPkgs,
|
|
108
|
+
ecosystemPackages: inlinePkgs,
|
|
109
|
+
projectDirs,
|
|
110
|
+
serverDepsInlineAll: userInlinesEverything
|
|
111
|
+
});
|
|
112
|
+
const nodeTransformed = ownership.nodeTransformPackages;
|
|
79
113
|
const fullEnv = { ...env };
|
|
114
|
+
const ownershipManifest = ownership.manifest();
|
|
115
|
+
fullEnv.VITEST_NATIVE_OWNERSHIP = JSON.stringify(ownershipManifest);
|
|
116
|
+
if (fullEnv.VITEST_NATIVE_DIAGNOSTICS === "true") for (const line of formatNativeOwnershipManifest(ownershipManifest)) {
|
|
117
|
+
const report = `[vitest-native] ownership: ${line}`;
|
|
118
|
+
if (line.startsWith("WARNING:")) console.warn(report);
|
|
119
|
+
else console.log(report);
|
|
120
|
+
}
|
|
80
121
|
if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
|
|
81
122
|
return {
|
|
82
123
|
...jsxTransform,
|
|
@@ -111,15 +152,12 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
|
|
|
111
152
|
...hot ? {
|
|
112
153
|
pool: hot.pool,
|
|
113
154
|
isolate: false,
|
|
114
|
-
runner: hot.runnerPath
|
|
155
|
+
runner: hot.runnerPath,
|
|
156
|
+
...hot.maxWorkers == null ? {} : { maxWorkers: hot.maxWorkers }
|
|
115
157
|
} : { pool: userPool ?? "threads" },
|
|
116
158
|
server: { deps: {
|
|
117
|
-
...userInlinesEverything ? {} : { inline:
|
|
118
|
-
external:
|
|
119
|
-
REACT_NATIVE_PATH,
|
|
120
|
-
...extraExternal,
|
|
121
|
-
...ecosystemExternal
|
|
122
|
-
]
|
|
159
|
+
...userInlinesEverything ? {} : { inline: ownership.testEntryPatterns },
|
|
160
|
+
external: ownership.externalPatterns
|
|
123
161
|
} }
|
|
124
162
|
}
|
|
125
163
|
};
|
|
@@ -149,6 +187,22 @@ const DEFAULT_ASSET_EXTS = [
|
|
|
149
187
|
"woff",
|
|
150
188
|
"woff2"
|
|
151
189
|
];
|
|
190
|
+
function uniqueExtensions(values) {
|
|
191
|
+
const seen = /* @__PURE__ */ new Set();
|
|
192
|
+
const result = [];
|
|
193
|
+
for (const value of values) {
|
|
194
|
+
const extension = value.replace(/^\./, "").toLowerCase();
|
|
195
|
+
if (extension && !seen.has(extension)) {
|
|
196
|
+
seen.add(extension);
|
|
197
|
+
result.push(extension);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
function assetExtensionsFor(sourceExts, metroAssets, user) {
|
|
203
|
+
const sources = new Set(sourceExts.map((extension) => extension.toLowerCase()));
|
|
204
|
+
return uniqueExtensions([...uniqueExtensions(metroAssets).filter((extension) => !sources.has(extension)), ...user]);
|
|
205
|
+
}
|
|
152
206
|
/** Strip Vite's /@fs/ prefix to get a real filesystem path. */
|
|
153
207
|
function stripFsPrefix(id) {
|
|
154
208
|
return id.startsWith("/@fs/") ? id.slice(4) : id;
|
|
@@ -267,13 +321,14 @@ function resolvePackageVersion(packageName, projectRoot) {
|
|
|
267
321
|
* Written to stderr: this is the plugin's only unconditional output, and stdout
|
|
268
322
|
* must stay parseable for pipelines like `vitest --reporter=json > results.json`.
|
|
269
323
|
*/
|
|
270
|
-
function printEngineBanner(engine, platform, projectRoot) {
|
|
324
|
+
function printEngineBanner(engine, platform, projectRoot, hotRuntime = false) {
|
|
271
325
|
const g = globalThis;
|
|
272
326
|
if (g.__vitest_native_banner_printed) return;
|
|
273
327
|
g.__vitest_native_banner_printed = true;
|
|
274
328
|
if (engine === "native") {
|
|
275
329
|
const rn = resolvePackageVersion("react-native", projectRoot);
|
|
276
|
-
|
|
330
|
+
const runtime = hotRuntime ? ", hot runtime" : "";
|
|
331
|
+
console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform}${runtime})`);
|
|
277
332
|
} else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
|
|
278
333
|
}
|
|
279
334
|
function getJsxTransformConfig(projectRoot) {
|
|
@@ -297,15 +352,37 @@ function getJsxTransformConfig(projectRoot) {
|
|
|
297
352
|
* real module in the native suite, across every React Native version in CI.
|
|
298
353
|
*/
|
|
299
354
|
function parseReactNativeExports(indexSource) {
|
|
355
|
+
return parseReactNativeMembers(indexSource).map((member) => member.name);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* The members of React Native's index that announce their own deprecation.
|
|
359
|
+
*
|
|
360
|
+
* React Native marks a deprecated or extracted export by calling `warnOnce` inside
|
|
361
|
+
* its getter, so reading the member is what prints the notice. The facade must not
|
|
362
|
+
* read these while it initialises, or every file that imports `Pressable` prints
|
|
363
|
+
* notices for `SafeAreaView`, `Clipboard` and the rest; it exposes them as getters
|
|
364
|
+
* instead, and the notice appears only where a test really uses one.
|
|
365
|
+
*/
|
|
366
|
+
function parseDeprecatedReactNativeExports(indexSource) {
|
|
367
|
+
return parseReactNativeMembers(indexSource).filter((member) => member.deprecated).map((member) => member.name);
|
|
368
|
+
}
|
|
369
|
+
function parseReactNativeMembers(indexSource) {
|
|
300
370
|
const start = indexSource.indexOf("module.exports = {");
|
|
301
371
|
if (start === -1) return [];
|
|
302
|
-
const
|
|
303
|
-
const
|
|
304
|
-
|
|
372
|
+
const end = indexSource.slice(start).search(/^\}/m);
|
|
373
|
+
const body = end === -1 ? indexSource.slice(start) : indexSource.slice(start, start + end);
|
|
374
|
+
const matches = [...body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)];
|
|
375
|
+
const members = /* @__PURE__ */ new Map();
|
|
376
|
+
matches.forEach((match, i) => {
|
|
305
377
|
const name = match[1];
|
|
306
|
-
if (name
|
|
307
|
-
|
|
308
|
-
|
|
378
|
+
if (name === "default" || name === "__esModule" || name === "get") return;
|
|
379
|
+
const text = body.slice(match.index, matches[i + 1]?.index ?? body.length);
|
|
380
|
+
members.set(name, (members.get(name) ?? false) || /\bwarnOnce\s*\(/.test(text));
|
|
381
|
+
});
|
|
382
|
+
return [...members].map(([name, deprecated]) => ({
|
|
383
|
+
name,
|
|
384
|
+
deprecated
|
|
385
|
+
}));
|
|
309
386
|
}
|
|
310
387
|
/**
|
|
311
388
|
* Build (or reuse) the precompiled React Native registry for a project.
|
|
@@ -319,27 +396,21 @@ function parseReactNativeExports(indexSource) {
|
|
|
319
396
|
async function buildRegistryFor(options) {
|
|
320
397
|
try {
|
|
321
398
|
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
322
|
-
return (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href)).
|
|
399
|
+
return (await import(pathToFileURL(path.resolve(dir, "native/registry-process.mjs")).href)).buildRegistryFor(options);
|
|
323
400
|
} catch (error) {
|
|
324
|
-
|
|
401
|
+
try {
|
|
402
|
+
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
403
|
+
(await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href))._warnRegistryUnavailable(error?.message ?? error);
|
|
404
|
+
} catch {
|
|
405
|
+
console.warn(`[vitest-native] (native) could not precompile the React Native registry (${error?.message ?? error}); using slower per-file module loading.`);
|
|
406
|
+
}
|
|
325
407
|
return null;
|
|
326
408
|
}
|
|
327
409
|
}
|
|
328
|
-
/**
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
* loaded through a computed path rather than a static import, and synchronously —
|
|
333
|
-
* Vite's transform hook may be sync and the module is already resident by the time
|
|
334
|
-
* any file reaches this point.
|
|
335
|
-
*/
|
|
336
|
-
let ecosystemTransformer = null;
|
|
337
|
-
function transformEcosystem(file, code, projectRoot, platform) {
|
|
338
|
-
if (!ecosystemTransformer) {
|
|
339
|
-
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
340
|
-
ecosystemTransformer = createRequire(import.meta.url)(path.resolve(dir, "native/transform.mjs")).transformRN;
|
|
341
|
-
}
|
|
342
|
-
return ecosystemTransformer(file, code, projectRoot, platform);
|
|
410
|
+
/** Load declarative Metro data without retaining Metro/Expo in Vite's process. */
|
|
411
|
+
async function loadProjectMetroProfile(options) {
|
|
412
|
+
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
413
|
+
return (await import(pathToFileURL(path.resolve(dir, "native/metro-profile.mjs")).href)).loadMetroProfile(options);
|
|
343
414
|
}
|
|
344
415
|
/**
|
|
345
416
|
* Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
|
|
@@ -369,11 +440,14 @@ function autoDetectPresetNames(projectRoot, diagnostics) {
|
|
|
369
440
|
}
|
|
370
441
|
return [...names];
|
|
371
442
|
}
|
|
372
|
-
|
|
443
|
+
/**
|
|
444
|
+
* `resolution` is the extension profile the plugin already settled on — Metro's when
|
|
445
|
+
* metroConfig is on, the built-in one otherwise — so it is computed in one place.
|
|
446
|
+
*/
|
|
447
|
+
async function resolveOptions(options = {}, projectRoot, resolution) {
|
|
373
448
|
const platform = options.platform ?? "ios";
|
|
374
449
|
const diagnostics = options.diagnostics ?? false;
|
|
375
450
|
const engine = options.engine === "native" ? "native" : "mock";
|
|
376
|
-
const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
|
|
377
451
|
let presets;
|
|
378
452
|
if (Array.isArray(options.presets)) presets = options.presets;
|
|
379
453
|
else {
|
|
@@ -385,10 +459,10 @@ async function resolveOptions(options = {}, projectRoot) {
|
|
|
385
459
|
platform,
|
|
386
460
|
engine,
|
|
387
461
|
diagnostics,
|
|
388
|
-
extensions:
|
|
462
|
+
extensions: resolution.extensions,
|
|
389
463
|
presets,
|
|
390
464
|
mocks: options.mocks ?? {},
|
|
391
|
-
assetExts:
|
|
465
|
+
assetExts: resolution.assetExts
|
|
392
466
|
};
|
|
393
467
|
}
|
|
394
468
|
/**
|
|
@@ -610,8 +684,9 @@ const FORMAT_ONLY_FIELDS = [
|
|
|
610
684
|
* cannot parse at all. Aligning upward would turn a wrong-value bug into a crash for
|
|
611
685
|
* any package the engine does not also transform.
|
|
612
686
|
*
|
|
613
|
-
* Packages the engine
|
|
614
|
-
*
|
|
687
|
+
* Packages the engine itself virtualizes are left alone. Node-owned ecosystem
|
|
688
|
+
* packages are intentionally not exempt: if Vite also reaches one, aligning a
|
|
689
|
+
* format-only field to Node's file prevents a silent second instance.
|
|
615
690
|
*
|
|
616
691
|
* @returns the absolute file to use, or null to leave resolution alone
|
|
617
692
|
*/
|
|
@@ -646,8 +721,134 @@ function disabledPresetNames(presets) {
|
|
|
646
721
|
if (!presets || Array.isArray(presets) || typeof presets !== "object") return /* @__PURE__ */ new Set();
|
|
647
722
|
return new Set(Object.entries(presets).filter(([, enabled]) => enabled === false).map(([name]) => name));
|
|
648
723
|
}
|
|
724
|
+
/**
|
|
725
|
+
* Config-time reasons that make automatic hot selection unsafe. Suites migrated from
|
|
726
|
+
* Jest (jestMockTransform(), the jest-compat setup) are not among them: the jest-compat
|
|
727
|
+
* surface has its own cross-file isolation gate under hot (tests-native/hot-jest-compat)
|
|
728
|
+
* and the hot runtime resets before user setup files run (tests-native/hot-user-setup).
|
|
729
|
+
*/
|
|
730
|
+
function hotAutoConfigDeclineReason(userPool, userIsolate) {
|
|
731
|
+
if (userIsolate !== void 0) return `test.isolate is explicitly ${String(userIsolate)}`;
|
|
732
|
+
if (userPool != null) return `${typeof userPool === "string" ? `'${userPool}'` : "a custom pool"} is explicitly configured`;
|
|
733
|
+
return null;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Why the resolved Vitest config overrides a hot runtime chosen at config time, or
|
|
737
|
+
* null. Vitest 4 applies CLI flags after plugins' config hooks, so `--maxWorkers=1`,
|
|
738
|
+
* `--no-file-parallelism`, `--pool` and `--isolate`/`--no-isolate` arrive only in the
|
|
739
|
+
* resolved config. `--no-isolate` sets the same `isolate: false` the hot runtime uses,
|
|
740
|
+
* so it is read from the CLI options themselves.
|
|
741
|
+
*/
|
|
742
|
+
function hotOverrideReason(resolved, cli, hotPool, singleWorkerAccepted = false) {
|
|
743
|
+
if (cli.isolate !== void 0) return `--${cli.isolate ? "" : "no-"}isolate was passed`;
|
|
744
|
+
const poolName = (pool) => typeof pool === "string" ? pool : pool !== null && typeof pool === "object" ? pool.name : void 0;
|
|
745
|
+
if (!(resolved.pool === hotPool || poolName(hotPool) !== void 0 && poolName(resolved.pool) === poolName(hotPool))) return `the pool '${typeof resolved.pool === "string" ? resolved.pool : "custom"}' was set`;
|
|
746
|
+
if (singleWorkerAccepted) return null;
|
|
747
|
+
if (resolved.fileParallelism === false) return "file parallelism is off";
|
|
748
|
+
if (typeof resolved.maxWorkers === "number" && resolved.maxWorkers < 2) return `maxWorkers is ${resolved.maxWorkers}`;
|
|
749
|
+
return null;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* The root Vitest gives a project: `test.root` over Vite's `root` (Vitest 4 and 5's
|
|
753
|
+
* resolveConfig). `vitest --root` arrives as `test.root`. Per-project state is keyed
|
|
754
|
+
* by it, since that is the root configureVitest sees.
|
|
755
|
+
*/
|
|
756
|
+
function vitestRootOf(config) {
|
|
757
|
+
const testRoot = config.test?.root;
|
|
758
|
+
const root = typeof testRoot === "string" && testRoot ? testRoot : config.root;
|
|
759
|
+
return path.resolve(typeof root === "string" && root ? root : process.cwd());
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Pin each inline project's `root` to the root it would inherit anyway, so Vitest 5
|
|
763
|
+
* resolves it through the config file with this plugin instead of sharing the
|
|
764
|
+
* declaring config's Vite server. A server-sharing project gets its `test` options
|
|
765
|
+
* from the user's raw config, captured before any plugin's config hook runs, so it
|
|
766
|
+
* would miss everything this plugin contributes to `test` — setup files, dependency
|
|
767
|
+
* ownership, env, the hot pool. Vitest shares a server only when an entry sets no
|
|
768
|
+
* Vite-level option; `root` is one, and pinning it to the inherited value changes
|
|
769
|
+
* nothing else. Unlike `sharedViteServer: false`, which Vitest reads from the
|
|
770
|
+
* top-level config alone, this works in a nested config too. Vitest 4 resolves every
|
|
771
|
+
* inline project through the config file already. Returns how many were pinned.
|
|
772
|
+
*/
|
|
773
|
+
function pinInlineProjectRoots(test, declaringRoot) {
|
|
774
|
+
const projects = test?.projects;
|
|
775
|
+
if (!Array.isArray(projects)) return 0;
|
|
776
|
+
let pinned = 0;
|
|
777
|
+
for (const entry of projects) {
|
|
778
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
779
|
+
const project = entry;
|
|
780
|
+
if (project.root !== void 0) continue;
|
|
781
|
+
project.root = declaringRoot;
|
|
782
|
+
pinned++;
|
|
783
|
+
}
|
|
784
|
+
return pinned;
|
|
785
|
+
}
|
|
786
|
+
function hasSetupFile(setupFiles, file) {
|
|
787
|
+
const real = (f) => {
|
|
788
|
+
try {
|
|
789
|
+
return fs.realpathSync(f);
|
|
790
|
+
} catch {
|
|
791
|
+
return path.resolve(f);
|
|
792
|
+
}
|
|
793
|
+
};
|
|
794
|
+
const wanted = real(file);
|
|
795
|
+
return Array.isArray(setupFiles) && setupFiles.some((f) => typeof f === "string" && real(f) === wanted);
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Why this project's worker count cannot coexist with another project's, or null.
|
|
799
|
+
* Vitest schedules projects that share a `sequence.groupOrder` (0 unless set) as one
|
|
800
|
+
* group, and throws when they resolve to different `maxWorkers` ("Projects … have
|
|
801
|
+
* different 'maxWorkers' but same 'sequence.groupOrder'", groupSpecs in Vitest 4 and
|
|
802
|
+
* 5). The hot runtime's memory plan caps workers (at most four), while a project
|
|
803
|
+
* beside it gets Vitest's default of one fewer than the CPUs, so a native project next
|
|
804
|
+
* to a mock or non-React-Native project failed on any machine with more than five
|
|
805
|
+
* cores. Mirrors Vitest's resolveMaxWorkers and its grouping, including the exemption
|
|
806
|
+
* for a single-worker isolated project in the default group.
|
|
807
|
+
*/
|
|
808
|
+
function sharedGroupConflict(self, others, root, cpus) {
|
|
809
|
+
const order = (p) => Number(p.config.sequence?.groupOrder ?? 0);
|
|
810
|
+
const workers = (p) => p.config.maxWorkers || root.maxWorkers || vitestMaxWorkers(void 0, root.watch === true, cpus);
|
|
811
|
+
const ownGroup = (p) => p.config.isolate === true && order(p) === 0 && p.config.maxWorkers === 1;
|
|
812
|
+
for (const other of others) {
|
|
813
|
+
if (other === self || ownGroup(other) || order(other) !== order(self)) continue;
|
|
814
|
+
if (workers(other) !== workers(self)) return `the project '${String(other.name ?? other.config.name ?? "another project")}' is in the same sequence.groupOrder (${order(self)}) with ${workers(other)} workers to this project's ${workers(self)}, which Vitest rejects (a distinct test.sequence.groupOrder runs them as separate groups)`;
|
|
815
|
+
}
|
|
816
|
+
return null;
|
|
817
|
+
}
|
|
818
|
+
function isVmPool(pool) {
|
|
819
|
+
return pool === "vmThreads" || pool === "vmForks";
|
|
820
|
+
}
|
|
821
|
+
function vmPoolUnsupported(pool) {
|
|
822
|
+
return new VitestNativeError("UNSUPPORTED_POOL", `engine:'native' cannot run on the '${pool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
|
|
823
|
+
}
|
|
824
|
+
function hotRuntimeOverridden(reason) {
|
|
825
|
+
return new VitestNativeError("HOT_RUNTIME_OVERRIDDEN", `hotRuntime was requested, but ${reason}, which the hot runtime cannot honour. Remove that setting, or use hotRuntime:'auto' to fall back to it automatically or hotRuntime:false.`);
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* The worker count Vitest would have used had the hot runtime not capped it: the
|
|
829
|
+
* user's own value (a count or a percentage of the CPUs), else Vitest's default.
|
|
830
|
+
* Mirrors Vitest 4/5's resolveMaxWorkers and getWorkersCountByPercentage.
|
|
831
|
+
*/
|
|
832
|
+
function vitestMaxWorkers(userValue, watch, cpus = os.availableParallelism?.() ?? os.cpus().length) {
|
|
833
|
+
if (typeof userValue === "number" && userValue > 0) return userValue;
|
|
834
|
+
if (typeof userValue === "string") {
|
|
835
|
+
const percent = /^(\d+)%$/.exec(userValue.trim());
|
|
836
|
+
if (percent) return Math.max(1, Math.min(cpus, Math.round(Number(percent[1]) / 100 * cpus)));
|
|
837
|
+
const count = Number.parseInt(userValue, 10);
|
|
838
|
+
if (count > 0) return count;
|
|
839
|
+
}
|
|
840
|
+
return watch ? Math.max(Math.floor(cpus / 2), 1) : Math.max(cpus - 1, 1);
|
|
841
|
+
}
|
|
842
|
+
/** Why hot cannot run here because its worker would load a different Vitest, or null. */
|
|
843
|
+
function workerVitestMismatchReason(workerEntry, projectRoot) {
|
|
844
|
+
const mismatch = workerVitestMismatch(workerEntry, projectRoot);
|
|
845
|
+
return mismatch ? `its worker would load vitest@${mismatch.worker.version} while this run uses vitest@${mismatch.project.version}` : null;
|
|
846
|
+
}
|
|
649
847
|
function reactNative(options) {
|
|
650
848
|
let jestMockTransformPresent = true;
|
|
849
|
+
const hotSelections = /* @__PURE__ */ new Map();
|
|
850
|
+
const nativeRoots = /* @__PURE__ */ new Set();
|
|
851
|
+
const contributedSetup = /* @__PURE__ */ new Map();
|
|
651
852
|
let warnedMissingJestMockTransform = false;
|
|
652
853
|
const warnIfJestMockUnhoisted = (code, id) => {
|
|
653
854
|
if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
|
|
@@ -666,10 +867,17 @@ function reactNative(options) {
|
|
|
666
867
|
let assetPattern;
|
|
667
868
|
let realRnPackageJson;
|
|
668
869
|
let rnFacadeExports = null;
|
|
870
|
+
let rnFacadeDeprecated = /* @__PURE__ */ new Set();
|
|
669
871
|
let rnFacadeRoot = "";
|
|
670
|
-
let
|
|
872
|
+
let nativeOwnership = null;
|
|
873
|
+
const assertInlineOwnership = (inline) => {
|
|
874
|
+
if (engine !== "native" || !nativeOwnership) return;
|
|
875
|
+
const conflicts = findNativeInlineConflicts(nativeOwnership, inline);
|
|
876
|
+
if (conflicts.length === 0) return;
|
|
877
|
+
const selection = conflicts.includes("*") ? "server.deps.inline:true" : `server.deps.inline overlaps Node-owned package${conflicts.length === 1 ? "" : "s"}: ${conflicts.join(", ")}`;
|
|
878
|
+
throw new VitestNativeError("INLINE_BREAKS_OWNERSHIP", `engine:'native' cannot run because ${selection}. Vitest gives inlining precedence over the engine's Node-ownership rules, so the same React Native package can load once through Vite and again through Node with separate module state. Remove the overlapping inline rule; use reactNative({ transform: [...] }) for Metro-source packages that need compiling.`);
|
|
879
|
+
};
|
|
671
880
|
let alignRoot = "";
|
|
672
|
-
let ecosystemRoot = "";
|
|
673
881
|
const alignedCache = /* @__PURE__ */ new Map();
|
|
674
882
|
const alignedResolution = (source, importer) => {
|
|
675
883
|
if (engine !== "native") return void 0;
|
|
@@ -714,17 +922,28 @@ function reactNative(options) {
|
|
|
714
922
|
if (fs.existsSync(srcPath)) setupFilePath = srcPath;
|
|
715
923
|
}
|
|
716
924
|
const nativeSetupPath = path.resolve(thisDir, "native/setup.mjs");
|
|
925
|
+
const EXPORT_RECOVERY_ARGV = ["--import", pathToFileURL(path.resolve(thisDir, "native/export-condition-recovery-preload.mjs")).href];
|
|
717
926
|
const nativeWorkerPath = path.resolve(thisDir, "native/worker.mjs");
|
|
718
927
|
const nativeRunnerPath = path.resolve(thisDir, "native/runner.mjs");
|
|
719
928
|
const platform = options?.platform ?? "ios";
|
|
720
929
|
const diagnostics = options?.diagnostics ?? false;
|
|
721
930
|
const requestedEngine = options?.engine ?? "auto";
|
|
722
931
|
const { include: transformPkgs, exclude: neverTransform } = normalizeTransformOption(options?.transform);
|
|
723
|
-
const
|
|
724
|
-
const
|
|
932
|
+
const hotRuntimeExplicit = options?.hotRuntime !== void 0;
|
|
933
|
+
const hotRuntimeOpt = options?.hotRuntime ?? "auto";
|
|
934
|
+
const hotRuntimeRequested = hotRuntimeOpt !== false;
|
|
935
|
+
const hotRuntimeAuto = hotRuntimeOpt === "auto";
|
|
725
936
|
const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
|
|
726
937
|
let engine = requestedEngine === "native" ? "native" : "mock";
|
|
727
|
-
|
|
938
|
+
let sourceExts = [
|
|
939
|
+
"js",
|
|
940
|
+
"jsx",
|
|
941
|
+
"json",
|
|
942
|
+
"ts",
|
|
943
|
+
"tsx"
|
|
944
|
+
];
|
|
945
|
+
let extensions = getPlatformExtensions(platform);
|
|
946
|
+
let assetExtList = assetExtensionsFor(sourceExts, DEFAULT_ASSET_EXTS, options?.assetExts ?? []);
|
|
728
947
|
const resolvePresetId = (source) => {
|
|
729
948
|
if (presetModules.has(source)) return `\0virtual:preset:${source}`;
|
|
730
949
|
if (!assetPattern) return void 0;
|
|
@@ -732,29 +951,57 @@ function reactNative(options) {
|
|
|
732
951
|
const pkg = packageNameOf(source);
|
|
733
952
|
if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
|
|
734
953
|
};
|
|
735
|
-
|
|
954
|
+
const pluginDefinition = {
|
|
736
955
|
name: "vitest-native",
|
|
737
956
|
enforce: "pre",
|
|
738
957
|
async config(userConfig, _env) {
|
|
739
958
|
const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
|
|
740
959
|
alignRoot = resolvedRoot;
|
|
960
|
+
const metroOption = options?.metroConfig;
|
|
961
|
+
if (metroOption === true || typeof metroOption === "object") {
|
|
962
|
+
const metroSettings = typeof metroOption === "object" ? metroOption : {};
|
|
963
|
+
let metro;
|
|
964
|
+
try {
|
|
965
|
+
metro = await loadProjectMetroProfile({
|
|
966
|
+
projectRoot: resolvedRoot,
|
|
967
|
+
platform,
|
|
968
|
+
configFile: metroSettings.configFile
|
|
969
|
+
});
|
|
970
|
+
} catch (error) {
|
|
971
|
+
const code = error?.code;
|
|
972
|
+
if (code !== void 0 && code !== "METRO_CONFIG_LOAD_FAILED") throw error;
|
|
973
|
+
throw new VitestNativeError("METRO_CONFIG_LOAD_FAILED", `${String(error?.message ?? error).replace(/^\[vitest-native\] /, "")}\nFix the Metro config, pass metroConfig:{ configFile:'...' } when it lives outside the project root, or use metroConfig:false to explicitly keep vitest-native's built-in React Native defaults.`, { cause: error });
|
|
974
|
+
}
|
|
975
|
+
if (metro.profile.customResolver) console.warn("[vitest-native] The Metro config installs resolver.resolveRequest, which is code and does not run under Vitest. Its source and asset extensions apply; a module it redirects resolves as Vite and Node resolve it. Where a redirect matters to tests, reproduce it with resolve.alias.");
|
|
976
|
+
sourceExts = [...metro.profile.sourceExts];
|
|
977
|
+
extensions = getConfiguredPlatformExtensions(platform, sourceExts);
|
|
978
|
+
assetExtList = assetExtensionsFor(sourceExts, metro.profile.assetExts, options?.assetExts ?? []);
|
|
979
|
+
if (diagnostics) {
|
|
980
|
+
const childRss = metro.evidence.rss ? `, child RSS ${Math.ceil(metro.evidence.rss / 1024 / 1024)} MiB` : "";
|
|
981
|
+
console.log(`[vitest-native] Metro profile: ${metro.profile.provenance}${metro.profile.configPath ? ` (${metro.profile.configPath})` : ""}; sourceExts=${sourceExts.join(",")}; assetExts=${assetExtList.join(",")}; loaded in ${metro.evidence.durationMs ?? "?"}ms${childRss}.`);
|
|
982
|
+
console.log(`[vitest-native] Metro resolverMainFields=${metro.profile.resolverMainFields.join(",")} and conditions=${metro.profile.conditionNames.join(",")} are observational; module ownership keeps the package-format policy authoritative.`);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
741
985
|
const jsxTransform = getJsxTransformConfig(resolvedRoot);
|
|
742
986
|
const decision = detectEngine(requestedEngine, resolvedRoot);
|
|
743
987
|
engine = decision.engine;
|
|
744
988
|
if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires react-native, '@react-native/babel-preset', and '@babel/core' to resolve from ${resolvedRoot} — missing: ${decision.missing.join(", ")}. React Native projects ship all three by default. Install what's missing (react-native as a dependency, the toolchain as devDependencies), or set engine:'mock' to run without a React Native install.`);
|
|
745
989
|
if (decision.notice) console.warn(decision.notice);
|
|
746
|
-
printEngineBanner(engine, platform, resolvedRoot);
|
|
990
|
+
if (engine !== "native") printEngineBanner(engine, platform, resolvedRoot);
|
|
747
991
|
const env = {
|
|
748
992
|
VITEST_NATIVE_PLATFORM: platform,
|
|
749
993
|
VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
|
|
750
994
|
VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
|
|
751
995
|
};
|
|
996
|
+
const requireAliases = serializableAliases(userConfig.resolve?.alias, resolvedRoot);
|
|
997
|
+
if (requireAliases.entries.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES = JSON.stringify(requireAliases.entries);
|
|
998
|
+
if (requireAliases.skipped.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES_SKIPPED = JSON.stringify(requireAliases.skipped);
|
|
752
999
|
const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
|
|
753
1000
|
if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
|
|
754
|
-
const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
|
|
755
1001
|
env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
|
|
756
|
-
if (
|
|
757
|
-
if (
|
|
1002
|
+
if (metroOption === true || typeof metroOption === "object") env.VITEST_NATIVE_SOURCE_EXTS = JSON.stringify(sourceExts);
|
|
1003
|
+
if (hotRuntimeRequested && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
|
|
1004
|
+
if (hotRuntimeRequested && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
|
|
758
1005
|
if (engine === "native") {
|
|
759
1006
|
if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
|
|
760
1007
|
const disabledNative = disabledPresetNames(options?.presets);
|
|
@@ -766,45 +1013,91 @@ function reactNative(options) {
|
|
|
766
1013
|
if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
|
|
767
1014
|
}
|
|
768
1015
|
const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
|
|
769
|
-
const
|
|
1016
|
+
const userInline = userConfig.test?.server?.deps?.inline;
|
|
1017
|
+
const userInlinesEverything = userInline === true;
|
|
1018
|
+
const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames);
|
|
770
1019
|
const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
|
|
771
1020
|
const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
|
|
772
1021
|
if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1022
|
+
nativeOwnership = createNativeOwnershipPolicy({
|
|
1023
|
+
projectRoot: resolvedRoot,
|
|
1024
|
+
explicitTransforms: transformPkgs,
|
|
1025
|
+
ecosystemPackages: ecosystem,
|
|
1026
|
+
runtimeTransformAugmentations: nativePresetNames.length > 0 ? ["preset-pass-through-modules"] : [],
|
|
1027
|
+
projectDirs,
|
|
1028
|
+
serverDepsInlineAll: userInlinesEverything
|
|
1029
|
+
});
|
|
1030
|
+
assertInlineOwnership(userInline);
|
|
1031
|
+
const userTest = userConfig.test;
|
|
1032
|
+
const userPool = userTest?.pool;
|
|
1033
|
+
if (isVmPool(userPool)) throw vmPoolUnsupported(userPool);
|
|
1034
|
+
nativeRoots.add(vitestRootOf(userConfig));
|
|
1035
|
+
let hotMemory;
|
|
1036
|
+
if (hotRuntimeRequested) {
|
|
1037
|
+
const { createHotMemoryPlan, formatHotMemoryPlan, resolveRequestedWorkers } = await import("./memory-FYbP0_gg.mjs").then((n) => n.r);
|
|
1038
|
+
const requestedWorkers = resolveRequestedWorkers(userTest?.maxWorkers, { fileParallelism: userTest?.fileParallelism });
|
|
1039
|
+
const plan = createHotMemoryPlan({ requestedWorkers });
|
|
1040
|
+
const allowUnboundedMemory = hotRecycle.allowUnboundedMemory === true;
|
|
1041
|
+
const configConflict = hotAutoConfigDeclineReason(userPool, userTest?.isolate);
|
|
1042
|
+
if (!hotRuntimeAuto && configConflict !== null) throw hotRuntimeOverridden(configConflict);
|
|
1043
|
+
const autoDeclineReason = hotRuntimeAuto ? configConflict ?? workerVitestMismatchReason(nativeWorkerPath, resolvedRoot) ?? (plan.maxWorkers < 2 ? `the ${plan.source} memory/scheduler plan selects only one unrecyclable worker` : null) : null;
|
|
1044
|
+
if (autoDeclineReason !== null) {
|
|
1045
|
+
if (hotRuntimeExplicit || diagnostics) console.warn(`[vitest-native] hotRuntime:'auto' kept default isolation: ${autoDeclineReason}.`);
|
|
1046
|
+
} else if (!allowUnboundedMemory && plan.maxWorkers < 2) throw new VitestNativeError("HOT_MEMORY_UNBOUNDED", `hotRuntime cannot enforce its memory budget with one worker because Vitest batches every file into one unrecyclable task. The effective ${plan.source} memory ceiling admits ${plan.admittedWorkers} worker, or this config explicitly selects one. Use hotRuntime:false, provide enough memory for at least two workers, or explicitly accept unbounded growth with hotRuntime:{ allowUnboundedMemory:true }.`);
|
|
1047
|
+
if (autoDeclineReason === null && (hotRuntimeExplicit || diagnostics) && !allowUnboundedMemory && userTest?.maxWorkers != null && plan.maxWorkers < requestedWorkers) console.warn(`[vitest-native] hotRuntime capped maxWorkers from ${requestedWorkers} to ${plan.maxWorkers} for the ${plan.source} memory budget. Set diagnostics:true to see the full envelope.`);
|
|
1048
|
+
if (autoDeclineReason === null && diagnostics) {
|
|
1049
|
+
for (const line of formatHotMemoryPlan(plan)) console.log(`[vitest-native] memory: ${line}`);
|
|
1050
|
+
if (allowUnboundedMemory) console.warn("[vitest-native] memory: allowUnboundedMemory:true disables the automatic worker cap and process-RSS enforcement.");
|
|
1051
|
+
}
|
|
1052
|
+
if (autoDeclineReason === null) {
|
|
1053
|
+
env.VITEST_NATIVE_MEMORY_PLAN = JSON.stringify({
|
|
1054
|
+
...plan,
|
|
1055
|
+
enforced: !allowUnboundedMemory
|
|
1056
|
+
});
|
|
1057
|
+
hotMemory = {
|
|
1058
|
+
plan,
|
|
1059
|
+
memoryLimit: hotRecycle.memoryLimit ?? plan.workerHeapLimit,
|
|
1060
|
+
allowUnboundedMemory
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
777
1063
|
}
|
|
778
1064
|
const registryFile = await buildRegistryFor({
|
|
779
1065
|
projectRoot: resolvedRoot,
|
|
780
1066
|
platform,
|
|
781
1067
|
reactNativeVersion: reactNativeVersion ?? "0.0.0",
|
|
782
1068
|
assetExts: assetExtList,
|
|
1069
|
+
sourceExts,
|
|
783
1070
|
diagnostics
|
|
784
1071
|
});
|
|
785
1072
|
if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
|
|
786
1073
|
let hot;
|
|
787
|
-
if (
|
|
788
|
-
const { nativePool
|
|
789
|
-
const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
|
|
1074
|
+
if (hotMemory) {
|
|
1075
|
+
const { nativePool } = await import("./pool-DjpOjOf3.mjs");
|
|
790
1076
|
hot = {
|
|
791
1077
|
pool: nativePool({
|
|
792
1078
|
workerEntry: nativeWorkerPath,
|
|
793
1079
|
projectRoot: resolvedRoot,
|
|
794
1080
|
recycleAfterFiles: hotRecycle.recycleAfterFiles,
|
|
795
|
-
memoryLimit,
|
|
1081
|
+
memoryLimit: hotMemory.memoryLimit,
|
|
1082
|
+
memoryPlan: hotMemory.plan,
|
|
1083
|
+
allowUnboundedMemory: hotMemory.allowUnboundedMemory,
|
|
796
1084
|
diagnostics
|
|
797
1085
|
}),
|
|
798
|
-
runnerPath: nativeRunnerPath
|
|
1086
|
+
runnerPath: nativeRunnerPath,
|
|
1087
|
+
maxWorkers: hotMemory.allowUnboundedMemory ? void 0 : hotMemory.plan.maxWorkers
|
|
799
1088
|
};
|
|
800
1089
|
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
1090
|
+
printEngineBanner(engine, platform, resolvedRoot, hot !== void 0);
|
|
1091
|
+
if (hot) hotSelections.set(vitestRootOf(userConfig), {
|
|
1092
|
+
pool: hot.pool,
|
|
1093
|
+
userPool,
|
|
1094
|
+
userMaxWorkers: userTest?.maxWorkers,
|
|
1095
|
+
singleWorkerAccepted: hotMemory?.allowUnboundedMemory === true
|
|
1096
|
+
});
|
|
1097
|
+
else hotSelections.delete(vitestRootOf(userConfig));
|
|
1098
|
+
return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything, projectDirs, nativeOwnership));
|
|
806
1099
|
}
|
|
807
|
-
if (
|
|
1100
|
+
if (hotRuntimeRequested && hotRuntimeExplicit) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
|
|
808
1101
|
if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
|
|
809
1102
|
if (Array.isArray(options?.presets)) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
|
|
810
1103
|
else {
|
|
@@ -846,6 +1139,8 @@ function reactNative(options) {
|
|
|
846
1139
|
},
|
|
847
1140
|
async configResolved(config) {
|
|
848
1141
|
jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
|
|
1142
|
+
const finalInline = config.test?.server?.deps?.inline;
|
|
1143
|
+
assertInlineOwnership(finalInline);
|
|
849
1144
|
const duplicateReact = findDuplicateReact((specifier, from) => {
|
|
850
1145
|
try {
|
|
851
1146
|
return createRequire(path.join(from, "package.json")).resolve(specifier);
|
|
@@ -870,7 +1165,10 @@ function reactNative(options) {
|
|
|
870
1165
|
const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
|
|
871
1166
|
if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
|
|
872
1167
|
}
|
|
873
|
-
resolved = await resolveOptions(options, config.root
|
|
1168
|
+
resolved = await resolveOptions(options, config.root, {
|
|
1169
|
+
extensions,
|
|
1170
|
+
assetExts: assetExtList
|
|
1171
|
+
});
|
|
874
1172
|
try {
|
|
875
1173
|
realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
|
|
876
1174
|
} catch {}
|
|
@@ -883,8 +1181,10 @@ function reactNative(options) {
|
|
|
883
1181
|
rnFacadeRoot = config.root;
|
|
884
1182
|
try {
|
|
885
1183
|
const indexPath = createRequire(path.join(config.root, "package.json")).resolve("react-native");
|
|
886
|
-
const
|
|
1184
|
+
const indexSource = fs.readFileSync(indexPath, "utf8");
|
|
1185
|
+
const names = parseReactNativeExports(indexSource);
|
|
887
1186
|
rnFacadeExports = names.length > 0 ? names : null;
|
|
1187
|
+
rnFacadeDeprecated = new Set(parseDeprecatedReactNativeExports(indexSource));
|
|
888
1188
|
} catch {
|
|
889
1189
|
rnFacadeExports = null;
|
|
890
1190
|
}
|
|
@@ -936,8 +1236,17 @@ function reactNative(options) {
|
|
|
936
1236
|
const code = [
|
|
937
1237
|
`import { createRequire } from "node:module";`,
|
|
938
1238
|
`const _rn = createRequire(${JSON.stringify(path.join(rnFacadeRoot, "package.json"))})("react-native");`,
|
|
939
|
-
...rnFacadeExports.map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
|
|
940
|
-
`export default _rn
|
|
1239
|
+
...rnFacadeExports.filter((n) => !rnFacadeDeprecated.has(n)).map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
|
|
1240
|
+
`export default _rn;`,
|
|
1241
|
+
...rnFacadeDeprecated.size > 0 ? [
|
|
1242
|
+
`for (const name of ${JSON.stringify([...rnFacadeDeprecated])}) {`,
|
|
1243
|
+
` Object.defineProperty(__vite_ssr_exports__, name, {`,
|
|
1244
|
+
` enumerable: true,`,
|
|
1245
|
+
` configurable: true,`,
|
|
1246
|
+
` get: () => _rn[name],`,
|
|
1247
|
+
` });`,
|
|
1248
|
+
`}`
|
|
1249
|
+
] : []
|
|
941
1250
|
].join("\n");
|
|
942
1251
|
virtualCodeCache.set(id, code);
|
|
943
1252
|
return code;
|
|
@@ -1000,17 +1309,10 @@ function reactNative(options) {
|
|
|
1000
1309
|
transform(code, id) {
|
|
1001
1310
|
warnIfJestMockUnhoisted(code, id);
|
|
1002
1311
|
if (engine === "native") {
|
|
1003
|
-
if (!
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
code: transformEcosystem(id, code, ecosystemRoot, platform),
|
|
1008
|
-
map: null
|
|
1009
|
-
};
|
|
1010
|
-
} catch (error) {
|
|
1011
|
-
if (diagnostics) console.warn(`[vitest-native] could not compile inlined ${id} (${error?.message}); serving it untouched.`);
|
|
1012
|
-
return;
|
|
1013
|
-
}
|
|
1312
|
+
if (!nativeOwnership) return void 0;
|
|
1313
|
+
const conflict = findNativeOwnershipConflict(nativeOwnership, id, "vite");
|
|
1314
|
+
if (!conflict) return void 0;
|
|
1315
|
+
throw new VitestNativeError("MODULE_OWNER_CONFLICT", `Vite attempted to transform '${id}', but the native ownership policy assigns that file to Node (${conflict.decision.reason}). Evaluating it in Vite would create a second module instance with separate state. Remove the inline/noExternal rule that claimed it; Metro-source packages belong in reactNative({ transform: [...] }).`);
|
|
1014
1316
|
}
|
|
1015
1317
|
if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
|
|
1016
1318
|
if (!code.includes("@flow")) return void 0;
|
|
@@ -1026,6 +1328,44 @@ function reactNative(options) {
|
|
|
1026
1328
|
}
|
|
1027
1329
|
}
|
|
1028
1330
|
};
|
|
1331
|
+
const configHandler = pluginDefinition.config;
|
|
1332
|
+
return {
|
|
1333
|
+
...pluginDefinition,
|
|
1334
|
+
config: {
|
|
1335
|
+
order: "post",
|
|
1336
|
+
async handler(userConfig, env) {
|
|
1337
|
+
const result = await configHandler.call(this, userConfig, env);
|
|
1338
|
+
pinInlineProjectRoots(userConfig.test, vitestRootOf(userConfig));
|
|
1339
|
+
const test = result?.test;
|
|
1340
|
+
if (Array.isArray(test?.setupFiles) && typeof test.setupFiles[0] === "string") contributedSetup.set(vitestRootOf(userConfig), test.setupFiles[0]);
|
|
1341
|
+
if (test) test.execArgv = [...test.execArgv ?? [], ...EXPORT_RECOVERY_ARGV];
|
|
1342
|
+
return result;
|
|
1343
|
+
}
|
|
1344
|
+
},
|
|
1345
|
+
configureVitest({ vitest, project }) {
|
|
1346
|
+
const projectConfig = project.config;
|
|
1347
|
+
const root = projectConfig.root ? path.resolve(projectConfig.root) : process.cwd();
|
|
1348
|
+
const setupFile = contributedSetup.get(root);
|
|
1349
|
+
if (setupFile && !hasSetupFile(projectConfig.setupFiles, setupFile)) throw new VitestNativeError("SHARED_VITE_SERVER", `A Vitest project under ${root} shares a Vite server without vitest-native's test config, so React Native's setup would not run. Give the project a \`root\`, or set \`test.sharedViteServer: false\` in the top-level Vitest config.`);
|
|
1350
|
+
const cli = vitest._cliOptions ?? vitest.config?.cliOptions ?? {};
|
|
1351
|
+
if (nativeRoots.has(root) && isVmPool(cli.pool)) throw vmPoolUnsupported(cli.pool);
|
|
1352
|
+
const selection = hotSelections.get(root);
|
|
1353
|
+
if (!selection) return;
|
|
1354
|
+
const reason = hotOverrideReason(projectConfig, cli, selection.pool, selection.singleWorkerAccepted) ?? sharedGroupConflict(project, vitest.projects ?? [], {
|
|
1355
|
+
maxWorkers: vitest.config?.maxWorkers,
|
|
1356
|
+
watch: vitest.config?.watch
|
|
1357
|
+
});
|
|
1358
|
+
if (reason === null) return;
|
|
1359
|
+
if (!hotRuntimeAuto) throw hotRuntimeOverridden(reason);
|
|
1360
|
+
projectConfig.pool = cli.pool ?? selection.userPool ?? "threads";
|
|
1361
|
+
projectConfig.isolate = cli.isolate ?? true;
|
|
1362
|
+
projectConfig.runner = void 0;
|
|
1363
|
+
if (cli.maxWorkers === void 0 && !process.env.VITEST_MAX_WORKERS) projectConfig.maxWorkers = projectConfig.fileParallelism === false ? 1 : selection.userMaxWorkers === void 0 && vitest.config !== projectConfig ? void 0 : vitestMaxWorkers(selection.userMaxWorkers, vitest.config?.watch === true);
|
|
1364
|
+
if (projectConfig.env) delete projectConfig.env.VITEST_NATIVE_MEMORY_PLAN;
|
|
1365
|
+
hotSelections.delete(root);
|
|
1366
|
+
console.error(`[vitest-native] hot runtime off: ${reason}; Vitest's settings apply.`);
|
|
1367
|
+
}
|
|
1368
|
+
};
|
|
1029
1369
|
}
|
|
1030
1370
|
//#endregion
|
|
1031
1371
|
export { disabledPresetNames, presets_exports as presets, reactNative };
|