vitest-native 0.14.0-rc.9 → 0.14.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.
Files changed (97) hide show
  1. package/README.md +94 -961
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +286 -97
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-BAAAlSkO.mjs +1028 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-aNBCTfA5.d.mts} +35 -55
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +463 -595
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +28 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +278 -61
  39. package/dist/native/loader.mjs +390 -23
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +119 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +73 -0
  56. package/dist/native/setup.mjs +96 -70
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +65 -36
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +82 -16
  79. package/docs/release-readiness.md +1 -1
  80. package/package.json +119 -102
  81. package/CHANGELOG.md +0 -2491
  82. package/dist/cli.cjs +0 -1951
  83. package/dist/cli.d.cts +0 -3
  84. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  85. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  86. package/dist/errors-B3lJK46O.cjs +0 -75
  87. package/dist/errors-CxoBUfVJ.mjs +0 -64
  88. package/dist/index-xw43lBlv.d.mts +0 -481
  89. package/dist/memory-6EPHrJA1.cjs +0 -144
  90. package/dist/pool-B4yesGhI.cjs +0 -121
  91. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  92. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  93. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  94. package/dist/presets-9f83H0WW.cjs +0 -3939
  95. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  96. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  97. package/docs/hot-default-design.md +0 -216
@@ -1,144 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- let node_os = require("node:os");
3
- node_os = require_rolldown_runtime.__toESM(node_os, 1);
4
- //#region src/native/memory.mjs
5
- var memory_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
6
- createHotMemoryPlan: () => createHotMemoryPlan,
7
- defaultRequestedWorkers: () => defaultRequestedWorkers,
8
- effectiveMemoryLimit: () => effectiveMemoryLimit,
9
- formatBytes: () => formatBytes,
10
- formatHotMemoryPlan: () => formatHotMemoryPlan,
11
- resolveRequestedWorkers: () => resolveRequestedWorkers
12
- });
13
- const MIB = 1048576;
14
- const MIN_WORKER_HEAP = 96 * MIB;
15
- const MAX_WORKER_HEAP = 512 * MIB;
16
- const MAIN_PROCESS_RESERVE = 256 * MIB;
17
- const REPLACEMENT_OVERLAP_RESERVE = 192 * MIB;
18
- const WORKER_RSS_ADMISSION_COST = 256 * MIB;
19
- const MAX_AUTO_WORKERS = 4;
20
- function finitePositive(value) {
21
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
22
- }
23
- function effectiveMemoryLimit({ totalMemory, constrainedMemory }) {
24
- const total = finitePositive(totalMemory);
25
- const constrained = finitePositive(constrainedMemory);
26
- if (total === null && constrained === null) return {
27
- bytes: null,
28
- source: "unknown"
29
- };
30
- if (total === null) return {
31
- bytes: constrained,
32
- source: "constrained"
33
- };
34
- if (constrained === null || total <= constrained) return {
35
- bytes: total,
36
- source: "host"
37
- };
38
- return {
39
- bytes: constrained,
40
- source: "constrained"
41
- };
42
- }
43
- function defaultRequestedWorkers(parallelism = node_os.default.availableParallelism?.() ?? node_os.default.cpus().length) {
44
- return Math.max(1, Math.floor(parallelism) - 1);
45
- }
46
- /** Resolve Vitest's number/percentage worker option without importing Vitest internals. */
47
- function resolveRequestedWorkers(value, { parallelism, fileParallelism = true } = {}) {
48
- if (fileParallelism === false) return 1;
49
- const cpus = Math.max(1, Math.floor(parallelism ?? node_os.default.availableParallelism?.() ?? node_os.default.cpus().length));
50
- if (typeof value === "number" && Number.isFinite(value)) return Math.max(1, Math.floor(value));
51
- if (typeof value === "string") {
52
- const trimmed = value.trim();
53
- if (/^\d+(?:\.\d+)?%$/.test(trimmed)) return Math.max(1, Math.floor(cpus * Number.parseFloat(trimmed) / 100));
54
- if (/^\d+$/.test(trimmed)) return Math.max(1, Number.parseInt(trimmed, 10));
55
- }
56
- return Math.max(1, cpus - 1);
57
- }
58
- /**
59
- * Compute the automatic hot-runtime envelope.
60
- *
61
- * The reserves and four-worker cap were earned by the packed 406-file RNTL
62
- * experiment. They are conservative defaults, not portable benchmark claims.
63
- */
64
- function createHotMemoryPlan({ totalMemory = node_os.default.totalmem(), constrainedMemory = process.constrainedMemory?.() ?? 0, requestedWorkers = defaultRequestedWorkers() } = {}) {
65
- const effective = effectiveMemoryLimit({
66
- totalMemory,
67
- constrainedMemory
68
- });
69
- const requested = Math.max(1, Math.floor(requestedWorkers));
70
- if (effective.bytes === null) return Object.freeze({
71
- version: 1,
72
- source: effective.source,
73
- effectiveLimit: null,
74
- softRssLimit: null,
75
- hardRssLimit: null,
76
- requestedWorkers: requested,
77
- admittedWorkers: Math.min(MAX_AUTO_WORKERS, requested),
78
- maxWorkers: Math.min(MAX_AUTO_WORKERS, requested),
79
- workerHeapLimit: 256 * MIB,
80
- mainProcessReserve: MAIN_PROCESS_RESERVE,
81
- replacementOverlapReserve: REPLACEMENT_OVERLAP_RESERVE
82
- });
83
- const softRssLimit = Math.floor(effective.bytes * .8);
84
- const hardRssLimit = Math.floor(effective.bytes * .9);
85
- const workerEnvelope = Math.max(0, softRssLimit - MAIN_PROCESS_RESERVE - REPLACEMENT_OVERLAP_RESERVE);
86
- const admittedWorkers = Math.max(1, Math.min(MAX_AUTO_WORKERS, Math.floor(workerEnvelope / WORKER_RSS_ADMISSION_COST)));
87
- const maxWorkers = Math.min(requested, admittedWorkers);
88
- const perWorkerEnvelope = workerEnvelope / maxWorkers;
89
- const workerHeapLimit = Math.min(MAX_WORKER_HEAP, Math.max(MIN_WORKER_HEAP, Math.floor(perWorkerEnvelope * .65)));
90
- return Object.freeze({
91
- version: 1,
92
- source: effective.source,
93
- effectiveLimit: effective.bytes,
94
- softRssLimit,
95
- hardRssLimit,
96
- requestedWorkers: requested,
97
- admittedWorkers,
98
- maxWorkers,
99
- workerHeapLimit,
100
- mainProcessReserve: MAIN_PROCESS_RESERVE,
101
- replacementOverlapReserve: REPLACEMENT_OVERLAP_RESERVE
102
- });
103
- }
104
- function formatBytes(bytes) {
105
- if (bytes == null) return "unknown";
106
- return `${Math.round(bytes / MIB)} MiB`;
107
- }
108
- function formatHotMemoryPlan(plan) {
109
- return [
110
- `effective limit: ${formatBytes(plan.effectiveLimit)} (${plan.source})`,
111
- `RSS soft/hard: ${formatBytes(plan.softRssLimit)} / ${formatBytes(plan.hardRssLimit)}`,
112
- `workers requested/admitted/selected: ${plan.requestedWorkers} / ${plan.admittedWorkers} / ${plan.maxWorkers}`,
113
- `worker heap recycle threshold: ${formatBytes(plan.workerHeapLimit)}`,
114
- `reserves main/replacement: ${formatBytes(plan.mainProcessReserve)} / ${formatBytes(plan.replacementOverlapReserve)}`
115
- ];
116
- }
117
- Object.freeze({
118
- MIB,
119
- MIN_WORKER_HEAP,
120
- MAX_WORKER_HEAP,
121
- MAIN_PROCESS_RESERVE,
122
- REPLACEMENT_OVERLAP_RESERVE,
123
- WORKER_RSS_ADMISSION_COST,
124
- MAX_AUTO_WORKERS
125
- });
126
- //#endregion
127
- Object.defineProperty(exports, "createHotMemoryPlan", {
128
- enumerable: true,
129
- get: function() {
130
- return createHotMemoryPlan;
131
- }
132
- });
133
- Object.defineProperty(exports, "formatHotMemoryPlan", {
134
- enumerable: true,
135
- get: function() {
136
- return formatHotMemoryPlan;
137
- }
138
- });
139
- Object.defineProperty(exports, "memory_exports", {
140
- enumerable: true,
141
- get: function() {
142
- return memory_exports;
143
- }
144
- });
@@ -1,121 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_errors = require("./errors-B3lJK46O.cjs");
3
- const require_worker_vitest = require("./worker-vitest-BfiQB8ND.cjs");
4
- let node_path = require("node:path");
5
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
6
- let vitest_node = require("vitest/node");
7
- //#region src/native/pool.ts
8
- function deepEqual(a, b) {
9
- if (a === b) return true;
10
- if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
11
- const ka = Object.keys(a);
12
- const kb = Object.keys(b);
13
- if (ka.length !== kb.length) return false;
14
- return ka.every((k) => kb.includes(k) && deepEqual(a[k], b[k]));
15
- }
16
- var NativeMemoryCoordinator = class {
17
- recyclingWorker = null;
18
- tryRecycle(worker) {
19
- if (this.recyclingWorker !== null) return this.recyclingWorker === worker;
20
- this.recyclingWorker = worker;
21
- return true;
22
- }
23
- finished(worker) {
24
- if (this.recyclingWorker === worker) this.recyclingWorker = null;
25
- }
26
- };
27
- var NativePoolWorker = class extends vitest_node.ThreadsPoolWorker {
28
- name = "vitest-native";
29
- reportMemory;
30
- entrypoint;
31
- environment;
32
- recycleAfterFiles;
33
- memoryLimit;
34
- memoryPlan;
35
- memoryCoordinator;
36
- allowUnboundedMemory;
37
- sampleRss;
38
- diagnostics;
39
- filesRun = 0;
40
- lastHeapUsed = 0;
41
- memoryListenerAttached = false;
42
- batchWarningShown = false;
43
- constructor(options, native, memoryCoordinator) {
44
- super(options);
45
- this.entrypoint = node_path.default.resolve(native.workerEntry);
46
- this.environment = options.environment;
47
- this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
48
- this.memoryLimit = native.memoryLimit ?? 0;
49
- this.memoryPlan = native.memoryPlan;
50
- this.memoryCoordinator = memoryCoordinator;
51
- this.allowUnboundedMemory = native.allowUnboundedMemory ?? false;
52
- this.sampleRss = native.sampleRss ?? (() => process.memoryUsage.rss());
53
- this.diagnostics = native.diagnostics ?? false;
54
- this.reportMemory = this.memoryLimit > 0;
55
- }
56
- async start() {
57
- this.assertInsideHardRssLimit("starting another worker");
58
- await super.start();
59
- if (this.reportMemory && !this.memoryListenerAttached) {
60
- this.memoryListenerAttached = true;
61
- this.on("message", (message) => {
62
- if (message?.__vitest_worker_response__ && typeof message.usedMemory === "number") this.lastHeapUsed = message.usedMemory;
63
- });
64
- }
65
- }
66
- async stop() {
67
- try {
68
- await super.stop();
69
- } finally {
70
- this.memoryCoordinator.finished(this);
71
- }
72
- }
73
- assertInsideHardRssLimit(action) {
74
- const hard = this.allowUnboundedMemory ? null : this.memoryPlan?.hardRssLimit;
75
- if (hard == null) return;
76
- const rss = this.sampleRss();
77
- if (rss < hard) return;
78
- throw new require_errors.VitestNativeError("HOT_MEMORY_BUDGET_EXCEEDED", `hotRuntime stopped before ${action}: process RSS is ${Math.round(rss / 1024 / 1024)} MiB, at or above the ${Math.round(hard / 1024 / 1024)} MiB hard limit derived from ${this.memoryPlan?.source ?? "the effective memory ceiling"}. Continuing could let the OS or container kill the test process without a useful result. Reduce maxWorkers, run without hotRuntime, or set hotRuntime.allowUnboundedMemory:true only when an external scheduler provides the memory boundary.`);
79
- }
80
- send(message) {
81
- if (message.type === "run" || message.type === "collect") {
82
- this.assertInsideHardRssLimit("starting the next test task");
83
- if (!this.batchWarningShown && message.context.files.length > 1 && (this.recycleAfterFiles > 0 || this.memoryLimit > 0)) {
84
- this.batchWarningShown = true;
85
- const explanation = `Vitest batched ${message.context.files.length} files into one task in single-worker mode, so hotRuntime cannot recycle at file boundaries and its memory limits are inert.`;
86
- if (!this.allowUnboundedMemory) throw new require_errors.VitestNativeError("HOT_MEMORY_UNBOUNDED", `${explanation} Use maxWorkers >= 2, disable hotRuntime, or explicitly accept this risk with hotRuntime:{ allowUnboundedMemory:true }.`);
87
- console.warn(`[vitest-native] ${explanation} Continuing because allowUnboundedMemory:true was set.`);
88
- }
89
- this.filesRun += message.context.files.length;
90
- }
91
- super.send(message);
92
- }
93
- canReuse(task) {
94
- let recycleReason = null;
95
- if (this.recycleAfterFiles > 0 && this.filesRun >= this.recycleAfterFiles) recycleReason = `${this.filesRun} files`;
96
- else if (this.memoryLimit > 0 && this.lastHeapUsed >= this.memoryLimit) recycleReason = `${Math.round(this.lastHeapUsed / 1024 / 1024)} MiB worker heap`;
97
- else {
98
- const soft = this.allowUnboundedMemory ? null : this.memoryPlan?.softRssLimit;
99
- const rss = soft == null ? 0 : this.sampleRss();
100
- if (soft != null && rss >= soft) recycleReason = `${Math.round(rss / 1024 / 1024)} MiB process RSS`;
101
- }
102
- if (recycleReason !== null && this.memoryCoordinator.tryRecycle(this)) {
103
- if (this.diagnostics) console.log(`[vitest-native] recycling hot worker after ${recycleReason}`);
104
- return false;
105
- }
106
- const env = task.context.environment;
107
- return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
108
- }
109
- };
110
- /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
111
- function nativePool(options) {
112
- const mismatch = require_worker_vitest.workerVitestMismatch(node_path.default.resolve(options.workerEntry), options.projectRoot);
113
- if (mismatch) throw require_worker_vitest.workerVitestMismatchError(mismatch);
114
- const memoryCoordinator = new NativeMemoryCoordinator();
115
- return {
116
- name: "vitest-native",
117
- createPoolWorker: (poolOptions) => new NativePoolWorker(poolOptions, options, memoryCoordinator)
118
- };
119
- }
120
- //#endregion
121
- exports.nativePool = nativePool;
@@ -1,241 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- let node_fs = require("node:fs");
3
- node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
4
- let node_path = require("node:path");
5
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
6
- //#region src/preset-map.ts
7
- /**
8
- * Map of npm package names to their built-in preset export names.
9
- * Shared between plugin.ts (Vite main process) and setup.ts (Vitest workers).
10
- */
11
- const AUTO_DETECT_PRESETS = {
12
- "react-native-reanimated": "reanimated",
13
- "react-native-worklets": "worklets",
14
- "react-native-gesture-handler": "gestureHandler",
15
- "react-native-safe-area-context": "safeAreaContext",
16
- "@react-navigation/native": "navigation",
17
- "@react-navigation/native-stack": "navigation",
18
- "@react-navigation/bottom-tabs": "navigation",
19
- "@react-navigation/elements": "navigation",
20
- "@react-navigation/drawer": "navigation",
21
- "@react-native-async-storage/async-storage": "asyncStorage",
22
- "react-native-screens": "screens",
23
- "expo-constants": "expo",
24
- "react-native-device-info": "deviceInfo",
25
- "react-native-mmkv": "mmkv",
26
- "@react-native-community/netinfo": "netInfo",
27
- "react-native-svg": "svg",
28
- "react-native-webview": "webview",
29
- "@react-native-vector-icons/common": "vectorIcons",
30
- "@shopify/flash-list": "flashList",
31
- "@gorhom/bottom-sheet": "bottomSheet",
32
- "react-native-keyboard-controller": "keyboardController",
33
- "react-native-unistyles": "unistyles",
34
- "react-native-skia": "skia",
35
- "@shopify/react-native-skia": "skia"
36
- };
37
- /**
38
- * Packages whose own JavaScript switches to a built-in in-memory implementation under
39
- * Vitest, from the given major on. Their preset would replace the real library with a
40
- * hand-written approximation, so it steps aside and the library tests itself:
41
- * - react-native-mmkv 3+: `isTest()` checks `VITEST_WORKER_ID` (and Jest's
42
- * `JEST_WORKER_ID`), and `createMMKV` then returns `createMockMMKV()` — the real
43
- * API (v4's `remove`, change listeners) with no native module. v4 imports
44
- * react-native-nitro-modules at load time, which the native engine's Nitro boundary
45
- * satisfies (see native/boundary.mjs). Before v3 there was no Vitest check.
46
- */
47
- const SELF_TESTING_FROM_MAJOR = { "react-native-mmkv": 3 };
48
- /**
49
- * Presets the native engine does not apply unless asked to, because the packages they
50
- * cover run as themselves there. The native engine runs a package's own JavaScript and
51
- * substitutes only its native module, the way jest-expo runs Expo packages: the real
52
- * code is the whole API, current with every SDK, where a replacement covers only what
53
- * was written into it.
54
- *
55
- * - expo: expo-constants, expo-font, expo-asset, expo-splash-screen, expo-linking and
56
- * expo-status-bar run against the engine's Expo runtime (native/globals.mjs) and
57
- * their own native-module mocks (native/expo-module-mocks.mjs). Measured on an
58
- * Expo SDK 58 app against jest-expo: 17 of 17 probes of these packages matched with
59
- * the preset off, 4 with it on. The preset was missing API (`hide`, `setOptions`,
60
- * `useAssets`, `canOpenURL` …) and answered with values jest-expo never gives
61
- * (`Constants.expoConfig.name === 'test-app'`).
62
- *
63
- * The mock engine has no real React Native to run them on, so it keeps these presets.
64
- * `presets: { expo: true }` applies one under the native engine too.
65
- */
66
- const NATIVE_ENGINE_RUNS_PACKAGES = ["expo"];
67
- /**
68
- * Whether an auto-detected preset applies under `engine`, given the `presets` option:
69
- * every one under the mock engine, and under the native engine all but those in
70
- * NATIVE_ENGINE_RUNS_PACKAGES, unless the option turns one on (`{ expo: true }`).
71
- */
72
- function autoDetectedPresetApplies(preset, engine, presetsOption) {
73
- if (engine === "mock" || !NATIVE_ENGINE_RUNS_PACKAGES.includes(preset)) return true;
74
- return presetsOption !== null && typeof presetsOption === "object" && !Array.isArray(presetsOption) && presetsOption[preset] === true;
75
- }
76
- /** Whether `pkgName` at `version` runs its own test mode (SELF_TESTING_FROM_MAJOR). */
77
- function testsItself(pkgName, version) {
78
- const floor = SELF_TESTING_FROM_MAJOR[pkgName];
79
- if (floor === void 0 || typeof version !== "string") return false;
80
- const major = Number.parseInt(version, 10);
81
- return !Number.isNaN(major) && major >= floor;
82
- }
83
- /**
84
- * The installed version, from the package's own manifest on disk. Not
85
- * `require('<pkg>/package.json')`: a package whose `exports` map omits ./package.json
86
- * throws there, and a gate that fails closed would put the preset back over a library
87
- * that tests itself, silently.
88
- */
89
- function installedVersion(pkgName, req) {
90
- let dir;
91
- try {
92
- dir = node_path.default.dirname(req.resolve(pkgName));
93
- } catch {
94
- return;
95
- }
96
- for (;;) {
97
- const file = node_path.default.join(dir, "package.json");
98
- if (node_fs.default.existsSync(file)) try {
99
- const manifest = JSON.parse(node_fs.default.readFileSync(file, "utf8"));
100
- if (manifest.name === pkgName) return manifest.version;
101
- } catch {}
102
- const up = node_path.default.dirname(dir);
103
- if (up === dir) return void 0;
104
- dir = up;
105
- }
106
- }
107
- /**
108
- * The preset that shadows `pkgName` in this project, or null when the package is not
109
- * installed or tests itself (SELF_TESTING_FROM_MAJOR). Every place that decides which
110
- * presets are active asks this, so the plugin, the worker setup and ecosystem
111
- * detection cannot disagree about a package.
112
- */
113
- function presetForInstalled(pkgName, req) {
114
- try {
115
- req.resolve(pkgName);
116
- } catch {
117
- return null;
118
- }
119
- if (testsItself(pkgName, installedVersion(pkgName, req))) return null;
120
- return AUTO_DETECT_PRESETS[pkgName] ?? null;
121
- }
122
- /**
123
- * The module ids each preset shadows — `Object.keys(preset().modules)`, written out.
124
- *
125
- * The CLI states what a preset covers (`migrate`: "the expo preset shadows
126
- * expo-constants, …"; "__mocks__/x — the y preset shadows it"), and a claim like that
127
- * must come from the preset itself. The presets cannot be imported to ask: they load
128
- * `vitest` and `react`, which the CLI must not require (doctor runs in projects where
129
- * neither resolves yet). So the ids are listed here, and `tests/preset-map.test.ts`
130
- * calls every preset factory and fails if a list and its preset disagree in either
131
- * direction, so the two cannot drift without a red build.
132
- */
133
- const PRESET_MODULES = {
134
- reanimated: ["react-native-reanimated"],
135
- worklets: ["react-native-worklets"],
136
- gestureHandler: ["react-native-gesture-handler"],
137
- safeAreaContext: ["react-native-safe-area-context"],
138
- navigation: [
139
- "@react-navigation/native",
140
- "@react-navigation/native-stack",
141
- "@react-navigation/bottom-tabs",
142
- "@react-navigation/drawer",
143
- "@react-navigation/elements"
144
- ],
145
- asyncStorage: ["@react-native-async-storage/async-storage"],
146
- screens: ["react-native-screens"],
147
- expo: [
148
- "expo-constants",
149
- "expo-font",
150
- "expo-asset",
151
- "expo-splash-screen",
152
- "expo-linking",
153
- "expo-status-bar"
154
- ],
155
- deviceInfo: ["react-native-device-info"],
156
- mmkv: ["react-native-mmkv"],
157
- netInfo: ["@react-native-community/netinfo"],
158
- svg: ["react-native-svg"],
159
- webview: ["react-native-webview"],
160
- vectorIcons: ["@react-native-vector-icons/common"],
161
- flashList: ["@shopify/flash-list"],
162
- bottomSheet: ["@gorhom/bottom-sheet"],
163
- keyboardController: ["react-native-keyboard-controller"],
164
- unistyles: ["react-native-unistyles", "react-native-unistyles/reanimated"],
165
- skia: ["react-native-skia", "@shopify/react-native-skia"]
166
- };
167
- /** The preset that shadows `moduleId`, or undefined when none does. */
168
- function presetShadowing(moduleId) {
169
- for (const [preset, modules] of Object.entries(PRESET_MODULES)) if (modules.includes(moduleId)) return preset;
170
- }
171
- /**
172
- * Asset extensions the plugin handles before any Metro profile or `assetExts` option
173
- * adds more. Kept here, not in plugin.ts, so the CLI can say which of a Jest asset
174
- * mapper's extensions are covered without loading the plugin.
175
- */
176
- const DEFAULT_ASSET_EXTS = [
177
- "png",
178
- "jpg",
179
- "jpeg",
180
- "gif",
181
- "bmp",
182
- "webp",
183
- "svg",
184
- "tiff",
185
- "heic",
186
- "heif",
187
- "mp4",
188
- "mp3",
189
- "wav",
190
- "aac",
191
- "m4a",
192
- "mov",
193
- "webm",
194
- "ttf",
195
- "otf",
196
- "woff",
197
- "woff2"
198
- ];
199
- //#endregion
200
- Object.defineProperty(exports, "AUTO_DETECT_PRESETS", {
201
- enumerable: true,
202
- get: function() {
203
- return AUTO_DETECT_PRESETS;
204
- }
205
- });
206
- Object.defineProperty(exports, "DEFAULT_ASSET_EXTS", {
207
- enumerable: true,
208
- get: function() {
209
- return DEFAULT_ASSET_EXTS;
210
- }
211
- });
212
- Object.defineProperty(exports, "PRESET_MODULES", {
213
- enumerable: true,
214
- get: function() {
215
- return PRESET_MODULES;
216
- }
217
- });
218
- Object.defineProperty(exports, "autoDetectedPresetApplies", {
219
- enumerable: true,
220
- get: function() {
221
- return autoDetectedPresetApplies;
222
- }
223
- });
224
- Object.defineProperty(exports, "presetForInstalled", {
225
- enumerable: true,
226
- get: function() {
227
- return presetForInstalled;
228
- }
229
- });
230
- Object.defineProperty(exports, "presetShadowing", {
231
- enumerable: true,
232
- get: function() {
233
- return presetShadowing;
234
- }
235
- });
236
- Object.defineProperty(exports, "testsItself", {
237
- enumerable: true,
238
- get: function() {
239
- return testsItself;
240
- }
241
- });
@@ -1,53 +0,0 @@
1
- const require_errors = require("./errors-B3lJK46O.cjs");
2
- //#region src/preset-modules.mjs
3
- const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
4
- const RESERVED = new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield".split(" "));
5
- /**
6
- * The preset a preset module exports: its default export, either a preset or a
7
- * function returning one (called with no arguments).
8
- */
9
- function presetFromModule(namespace, file) {
10
- const exported = namespace?.default;
11
- const preset = typeof exported === "function" ? exported() : exported;
12
- const isObject = (value) => value !== null && typeof value === "object";
13
- if (typeof preset?.then === "function") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} default-exports an async function. The plugin reads the preset synchronously; put async work in the preset's prepare(), which the test workers await before any test file loads.`);
14
- if (!isObject(preset) || typeof preset.name !== "string" || !preset.name || !isObject(preset.modules)) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} must default-export a preset ({ name, modules }) or a function that returns one.`);
15
- for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
16
- if (!isObject(presetModule) || typeof presetModule.factory !== "function" || !(Array.isArray(presetModule.exports) || typeof presetModule.exportsFor === "function")) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} declares '${moduleName}' without a factory function and an exports array.`);
17
- for (const name of presetModule.exports ?? []) if (typeof name !== "string" || !IDENTIFIER.test(name) || RESERVED.has(name)) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} lists ${JSON.stringify(name)} among the exports of '${moduleName}'. Each must be a name a variable could have` + (name === "default" ? `; the default import is the whole module object the factory returns.` : `.`));
18
- }
19
- return preset;
20
- }
21
- /** The preset module paths the plugin passed this worker, absolute. */
22
- function presetModulePaths() {
23
- const raw = process.env.VITEST_NATIVE_PRESET_MODULES;
24
- if (!raw) return [];
25
- try {
26
- return JSON.parse(raw);
27
- } catch (cause) {
28
- throw new require_errors.VitestNativeTypeError("INVALID_OPTION", "VITEST_NATIVE_PRESET_MODULES, which the plugin sets for its setup file, is not valid JSON.", { cause });
29
- }
30
- }
31
- /** Imports a preset module in a test worker, through Vitest so TypeScript loads. */
32
- async function importPresetModule(vi, file) {
33
- return presetFromModule(await vi.importActual(file), file);
34
- }
35
- //#endregion
36
- Object.defineProperty(exports, "importPresetModule", {
37
- enumerable: true,
38
- get: function() {
39
- return importPresetModule;
40
- }
41
- });
42
- Object.defineProperty(exports, "presetFromModule", {
43
- enumerable: true,
44
- get: function() {
45
- return presetFromModule;
46
- }
47
- });
48
- Object.defineProperty(exports, "presetModulePaths", {
49
- enumerable: true,
50
- get: function() {
51
- return presetModulePaths;
52
- }
53
- });
@@ -1,36 +0,0 @@
1
- import { n as VitestNativeTypeError } from "./errors-CxoBUfVJ.mjs";
2
- //#region src/preset-modules.mjs
3
- const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
4
- const RESERVED = new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield".split(" "));
5
- /**
6
- * The preset a preset module exports: its default export, either a preset or a
7
- * function returning one (called with no arguments).
8
- */
9
- function presetFromModule(namespace, file) {
10
- const exported = namespace?.default;
11
- const preset = typeof exported === "function" ? exported() : exported;
12
- const isObject = (value) => value !== null && typeof value === "object";
13
- if (typeof preset?.then === "function") throw new VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} default-exports an async function. The plugin reads the preset synchronously; put async work in the preset's prepare(), which the test workers await before any test file loads.`);
14
- if (!isObject(preset) || typeof preset.name !== "string" || !preset.name || !isObject(preset.modules)) throw new VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} must default-export a preset ({ name, modules }) or a function that returns one.`);
15
- for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
16
- if (!isObject(presetModule) || typeof presetModule.factory !== "function" || !(Array.isArray(presetModule.exports) || typeof presetModule.exportsFor === "function")) throw new VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} declares '${moduleName}' without a factory function and an exports array.`);
17
- for (const name of presetModule.exports ?? []) if (typeof name !== "string" || !IDENTIFIER.test(name) || RESERVED.has(name)) throw new VitestNativeTypeError("INVALID_OPTION", `The preset module ${file} lists ${JSON.stringify(name)} among the exports of '${moduleName}'. Each must be a name a variable could have` + (name === "default" ? `; the default import is the whole module object the factory returns.` : `.`));
18
- }
19
- return preset;
20
- }
21
- /** The preset module paths the plugin passed this worker, absolute. */
22
- function presetModulePaths() {
23
- const raw = process.env.VITEST_NATIVE_PRESET_MODULES;
24
- if (!raw) return [];
25
- try {
26
- return JSON.parse(raw);
27
- } catch (cause) {
28
- throw new VitestNativeTypeError("INVALID_OPTION", "VITEST_NATIVE_PRESET_MODULES, which the plugin sets for its setup file, is not valid JSON.", { cause });
29
- }
30
- }
31
- /** Imports a preset module in a test worker, through Vitest so TypeScript loads. */
32
- async function importPresetModule(vi, file) {
33
- return presetFromModule(await vi.importActual(file), file);
34
- }
35
- //#endregion
36
- export { presetFromModule as n, presetModulePaths as r, importPresetModule as t };