vitest-native 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/README.md +1 -0
  3. package/dist/cli.cjs +25 -7
  4. package/dist/cli.mjs +22 -4
  5. package/dist/{ecosystem-IuZ-Gv0R.cjs → ecosystem-BJzJU3Cf.cjs} +226 -14
  6. package/dist/{ecosystem-CO5vqExO.mjs → ecosystem-C4qT_vl3.mjs} +200 -12
  7. package/dist/helpers.cjs +1 -1
  8. package/dist/helpers.mjs +1 -1
  9. package/dist/{index-BJL4cQ-l.d.cts → index-CrMeE8rd.d.mts} +5 -5
  10. package/dist/{index-CvCU0cLl.d.mts → index-DIMbjH8R.d.cts} +6 -3
  11. package/dist/index.d.mts +1 -2
  12. package/dist/index.mjs +78 -48
  13. package/dist/jest-compat.cjs +4 -4
  14. package/dist/jest-compat.d.cts +0 -1
  15. package/dist/jest-compat.d.mts +0 -1
  16. package/dist/jest-compat.mjs +2 -2
  17. package/dist/native/hooks.mjs +77 -12
  18. package/dist/native/loader.mjs +10 -5
  19. package/dist/native/match.d.mts +33 -0
  20. package/dist/native/match.mjs +94 -22
  21. package/dist/native/registry.mjs +30 -2
  22. package/dist/{pool-CFND7plG.cjs → pool-BU-1ecIF.cjs} +6 -6
  23. package/dist/{pool-Bcxp4Qrg.mjs → pool-Bcxn9a3I.mjs} +3 -3
  24. package/dist/{preset-map-DxilQ4pI.cjs → preset-map-BoG19dLa.cjs} +1 -0
  25. package/dist/{preset-map-BpDG_D5m.mjs → preset-map-DuX0ocdn.mjs} +1 -0
  26. package/dist/{presets-BGTqVH6C.cjs → presets-CwO_c4aL.cjs} +131 -6
  27. package/dist/{presets-CK85x8ey.mjs → presets-IStcJEOa.mjs} +123 -4
  28. package/dist/presets.d.mts +2 -2
  29. package/dist/presets.mjs +2 -2
  30. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  31. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  32. package/dist/serializer.cjs +1 -1
  33. package/dist/serializer.mjs +1 -1
  34. package/dist/setup.d.mts +1 -1
  35. package/dist/setup.mjs +5 -5
  36. package/docs/versioning.md +1 -1
  37. package/package.json +17 -15
  38. /package/dist/{errors-flXDIeWk.cjs → errors-B3lJK46O.cjs} +0 -0
  39. /package/dist/{errors-Dm5yLNTF.mjs → errors-CxoBUfVJ.mjs} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,195 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.11.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 912fb81: Add a `netInfo` preset for `@react-native-community/netinfo`
8
+
9
+ NetInfo was detected and compiled correctly, and still failed at the native-module
10
+ boundary. The generic stub answers any method with `undefined`; NetInfo awaits
11
+ `getCurrentState()` and reads `state.isInternetReachable` off the result, so a test
12
+ that called `NetInfo.fetch()` died on a TypeError and an unhandled rejection.
13
+
14
+ No generic stub can infer that shape, which is what earns a preset. It is auto-detected
15
+ like the others, and covers the package's real runtime surface: `configure`, `fetch`,
16
+ `refresh`, `addEventListener`, `useNetInfo`, `useNetInfoInstance`, and the
17
+ `NetInfoStateType` / `NetInfoCellularGeneration` enums — which are TypeScript enums
18
+ re-exported through `export *`, so unlike the rest of that module they do have runtime
19
+ bindings.
20
+
21
+ The resting state is a connected wifi device. The real library starts at
22
+ `{ type: 'unknown', isConnected: null }` and resolves to the device a moment later; a
23
+ mock has no device, and a null resting state would send every component under test down
24
+ its offline branch. Tests can drive it, and `resetAllMocks()` restores it.
25
+
26
+ The package is now a devDependency, so the preset's declared exports are checked against
27
+ the real package's TypeScript surface by the existing fidelity gate rather than trusted.
28
+
29
+ ### Patch Changes
30
+
31
+ - f6e5a42: Check React Native API coverage on every pull request
32
+
33
+ The mock engine is documented as covering every stable React Native export, and
34
+ `check-compat` is the script that backs the claim: it parses the real `react-native`
35
+ index and fails when a stable export has no mock.
36
+
37
+ It ran only in the weekly compatibility workflow, and there against
38
+ `react-native@latest`. The version actually pinned in the repository was never checked
39
+ on a pull request. A change that moved the pinned React Native could add stable exports
40
+ the mock did not cover and still go green, with the gap appearing days later as a
41
+ canary failure against a different version.
42
+
43
+ It now runs in the pull-request gate against the pinned React Native, on the one matrix
44
+ leg where the React Native version is representative. The weekly canary keeps its own
45
+ edge run — the two answer different questions.
46
+
47
+ Currently 85 of 85 stable exports are covered.
48
+
49
+ - 12e1be3: Build with tsdown under bun's runtime
50
+
51
+ tsdown's bin declares a Node shebang, and from 0.22 it calls `Promise.withResolvers` —
52
+ an API Node did not ship until 21. Building on Node 20 therefore failed with
53
+ `TypeError: Promise.withResolvers is not a function`, which blocked the dev-dependency
54
+ updates that carry tsdown forward.
55
+
56
+ `build` now invokes `bunx --bun tsdown`, so the bundler runs under bun's runtime, which
57
+ has the API. The emitted `dist` is byte-identical either way, verified by hashing it
58
+ from both runtimes against tsdown 0.21 and 0.22.
59
+
60
+ This is a change to what the build toolchain runs on, not to what the package requires.
61
+ The published `engines` floor of Node >= 20.19 is unchanged, and the Node 20 CI legs —
62
+ which prove that floor and pin RNTL 12 and 13 as the lower-bound back-compat corners —
63
+ keep running everything they ran before.
64
+
65
+ - c0b3bb3: `doctor` reports the real Node floor, and catches RNTL 14's missing peer
66
+
67
+ Two cases where `doctor` said a project was fine while it was not.
68
+
69
+ **The Node floor was hardcoded and compared on the major only.** It printed
70
+ "floor: 20" and passed any Node 20.x, but the real floor moved to 20.19 — the version
71
+ that added `require(esm)`, which the root entry point now depends on. Node 20.0 through
72
+ 20.18 were reported as supported. The floor is now read from this package's own
73
+ `engines.node`, and compared as major and minor.
74
+
75
+ **RNTL 14 declares `test-renderer` as a non-optional peer** and reconciles through it.
76
+ Installing RNTL 14 without it is easy — npm only warns, and any `--legacy-peer-deps`
77
+ install is silent — and the result is that every `render()` throws `Cannot find module
78
+ 'test-renderer'`, naming no file and no package. `doctor` reported no blocking problems
79
+ for exactly that project. It now fails with the install command. RNTL 13 is unaffected
80
+ and is not asked for the package it does not use.
81
+
82
+ - d0fb6ba: Compile a detected package's dependencies too
83
+
84
+ `react-native-modal` — and any package like it — failed to import under the native
85
+ engine with a bare `SyntaxError: Unexpected token '<'`, naming no file and no package.
86
+
87
+ Detection asks each package's own manifest whether it declares `react-native`. The
88
+ untranspiled JSX was not in `react-native-modal`; it was in `react-native-animatable`,
89
+ which that package depends on. Nothing in the project declares it, so it was never a
90
+ candidate, and it names `react-native` in neither `dependencies` nor
91
+ `peerDependencies`, so the manifest test would have rejected it anyway. The documented
92
+ remedy, `transform: ['react-native-modal']`, does not help — only naming
93
+ `react-native-animatable` does, and nothing told anyone that.
94
+
95
+ A detected package's dependency closure is now compiled with it. Two exclusions keep
96
+ that safe, and both compute themselves rather than being lists to maintain:
97
+
98
+ - **React Native's own dependencies.** The precompiled registry reaches those through
99
+ pre-resolved absolute paths, so Node owns them; inlining one would give the same
100
+ package two owners and two instances.
101
+ - **The transform's own toolchain closure.** The transform runs `@babel/core`, so
102
+ inlining anything Babel reaches means loading it re-enters the transform while Babel
103
+ is mid-load.
104
+
105
+ Detection stays under a millisecond, and 120 isolated test files run in the same time
106
+ as before.
107
+
108
+ - cb98e1e: Never treat the package under test as an ecosystem dependency
109
+
110
+ Under `engine: 'native'` in a workspace, a test file's own
111
+ `import { describe, it, expect } from 'vitest'` could fail to load with:
112
+
113
+ ```
114
+ Error: Vitest cannot be imported in a CommonJS module using require().
115
+ Test Files 1 failed | Tests: no tests
116
+ ```
117
+
118
+ Auto-detection reads the manifests of every workspace member, so the package under
119
+ test appears in the candidate set whenever a sibling — or the repository root —
120
+ declares it as a dependency. It also declares React Native, because it _is_ React
121
+ Native code, so it was detected as a third-party ecosystem package: its directory
122
+ became a `server.deps.external` pattern, Vitest handed every file beneath it to Node,
123
+ and the loader compiled them to CommonJS. A test file's `import` then became
124
+ `require('vitest')`, which throws before a single test runs. Suites using Vitest
125
+ globals instead reported a pass while still running through Node's graph.
126
+
127
+ Because it depended on whether anything happened to declare the package, the failure
128
+ appeared in one workspace package and not another with an identical config, and was
129
+ easy to misattribute to the `react-native` export condition selecting a CommonJS build
130
+ of some dependency. It reproduces with no such dependency in the graph.
131
+
132
+ Two changes:
133
+
134
+ - A package whose directory contains the run root is the project, not a dependency,
135
+ and is excluded from detection — including when a detected sibling's dependency
136
+ closure reaches it. Workspace libraries the project merely depends on are still
137
+ detected, which is what keeps them to a single module instance.
138
+ - A first-party test file is never externalized, even when it sits inside a workspace
139
+ library that is legitimately detected — the case an Nx-style run from the repository
140
+ root produces. Test entries belong to Vitest, not to Node. Both conventions are
141
+ covered: `*.test.*` / `*.spec.*` names, and files under a `__tests__` directory.
142
+ - The same directory anchor is skipped for a package named in `transform: [...]`,
143
+ which never passes through detection. A migrated Jest `transformIgnorePatterns`
144
+ list naming the project's own package produced the identical failure.
145
+ - When the run root sits above the package under test, a `test.include` pattern
146
+ pointing into that package now identifies it, so its own source stays in Vite's
147
+ graph too rather than only its test entries. A pattern with nothing literal before
148
+ its first wildcard — Vitest's default — says nothing about which package is the
149
+ project and is ignored, so workspace libraries the run merely depends on are still
150
+ detected.
151
+ - `react` and `react-is` join the packages that are never claimed by detection,
152
+ alongside the test library and the renderers. A package declaring `react` as a
153
+ runtime dependency rather than a peer dependency pulled it into the closure walk,
154
+ leaving the engine's most duplication-sensitive package externalized and compiled
155
+ as though it were untranspiled React Native source.
156
+
157
+ One case remains where a package can still end up in both graphs, and it is now
158
+ reported rather than silent: when an installed React Native package depends on the
159
+ very package whose tests are running, Node loads that package's source alongside
160
+ Vite's copy, and module-level state stops being shared. The engine warns, naming the
161
+ file and the package that required it. It cannot be resolved by choosing an owner —
162
+ the dependency is usually declared but never loaded, and honouring it would put the
163
+ project's own test files back in Node's graph.
164
+
165
+ The ownership rule the engine follows is written down in the header of
166
+ `native/apply.ts`.
167
+
168
+ The consumer suite now runs the workspace library's own tests, from inside the package
169
+ and from the workspace root, and the whole monorepo fixture is exercised under pnpm as
170
+ well as npm.
171
+
172
+ - d7ffd0a: Invalidate the React Native registry when any baked-in dependency changes, not just React
173
+
174
+ The precompiled registry inlines React Native's own graph and leaves everything else —
175
+ `react`, `invariant`, `nullthrows`, `@babel/runtime`, `stacktrace-parser` and others —
176
+ as a normal `require` at a **pre-resolved absolute path** compiled into the emitted
177
+ file. Those paths are only correct while the packages they point at stay where they
178
+ were, but only React Native's own files were pinned against change.
179
+
180
+ A previous fix named `react` in the cache key after upgrading React produced a null
181
+ React dispatcher and React Native singletons that no longer compared equal. That fixed
182
+ one package out of eleven. Naming the rest in the key one at a time would be a list
183
+ that rots — the next dependency added to React Native's graph would not be on it.
184
+
185
+ The resolved external targets are now recorded in the registry's manifest alongside
186
+ React Native's own files, so the existing size-and-mtime check covers them. That works
187
+ for both `node_modules` layouts: under bun and pnpm a version change moves the path, so
188
+ the stat fails; under a flat npm or yarn tree the path survives but the file changes.
189
+
190
+ Eleven packages are pinned in this repository's build. Verified by changing `invariant`
191
+ under a warm cache: the registry rebuilds, where before it was reused unchanged.
192
+
3
193
  ## 0.10.0
4
194
 
5
195
  ### Minor Changes
package/README.md CHANGED
@@ -476,6 +476,7 @@ export default defineConfig({
476
476
  | `presets.expo()` | Expo modules |
477
477
  | `presets.deviceInfo()` | react-native-device-info |
478
478
  | `presets.mmkv()` | react-native-mmkv |
479
+ | `presets.netInfo()` | @react-native-community/netinfo |
479
480
  | `presets.svg()` | react-native-svg |
480
481
  | `presets.webview()` | react-native-webview |
481
482
  | `presets.vectorIcons()` | react-native-vector-icons |
package/dist/cli.cjs CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
4
- const require_ecosystem = require("./ecosystem-IuZ-Gv0R.cjs");
5
- const require_preset_map = require("./preset-map-DxilQ4pI.cjs");
3
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
4
+ const require_ecosystem = require("./ecosystem-BJzJU3Cf.cjs");
5
+ const require_preset_map = require("./preset-map-BoG19dLa.cjs");
6
6
  let node_fs = require("node:fs");
7
- node_fs = require_chunk.__toESM(node_fs, 1);
7
+ node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
8
8
  let node_path = require("node:path");
9
- node_path = require_chunk.__toESM(node_path, 1);
9
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
10
10
  let node_module = require("node:module");
11
11
  //#region src/cli/doctor.ts
12
12
  /**
@@ -22,6 +22,21 @@ function packageVersion(root, name) {
22
22
  }
23
23
  }
24
24
  /**
25
+ * The supported Node floor, as [major, minor], read from this package's own
26
+ * `engines.node`. Single source: the manifest is what a package manager enforces
27
+ * at install time, so a diagnostic must not carry its own copy of the number.
28
+ */
29
+ function nodeFloor() {
30
+ const fallback = [20, 19];
31
+ try {
32
+ const manifest = JSON.parse(node_fs.default.readFileSync(new URL("../../package.json", require("url").pathToFileURL(__filename).href), "utf8"));
33
+ const match = /(\d+)\.(\d+)/.exec(manifest.engines?.node ?? "");
34
+ return match ? [Number(match[1]), Number(match[2])] : fallback;
35
+ } catch {
36
+ return fallback;
37
+ }
38
+ }
39
+ /**
25
40
  * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
26
41
  * is used when there is none.
27
42
  *
@@ -165,8 +180,10 @@ function runDoctor(root, nodeVersion = process.versions.node) {
165
180
  lines.push(`vitest-native doctor — ${root}`);
166
181
  lines.push("", "Runtime");
167
182
  const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
168
- if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
169
- else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
183
+ const [floorMajor, floorMinor] = nodeFloor();
184
+ const floorText = `${floorMajor}.${floorMinor}`;
185
+ if (nodeMajorMinor[0] > floorMajor || nodeMajorMinor[0] === floorMajor && nodeMajorMinor[1] >= floorMinor) pass(`Node ${nodeVersion} (floor: ${floorText})`);
186
+ else fail(`Node ${nodeVersion} — vitest-native requires Node >= ${floorText}.`);
170
187
  lines.push("", "Peer dependencies");
171
188
  for (const { name, minimum, maximumMajor, minimumByMajor, optional } of require_ecosystem.PEER_REQUIREMENTS) {
172
189
  if (optional) continue;
@@ -192,6 +209,7 @@ function runDoctor(root, nodeVersion = process.versions.node) {
192
209
  const rntlError = rntlReq && require_ecosystem.validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
193
210
  if (rntlError) warn(rntlError);
194
211
  else if (rntlMajor >= 14 && (nodeMajorMinor[0] < 22 || nodeMajorMinor[0] === 22 && nodeMajorMinor[1] < 13)) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
212
+ else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
195
213
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
196
214
  }
197
215
  lines.push("", "Auto-detected presets");
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { a as validatePeerDependency, n as detectEngine, r as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-CO5vqExO.mjs";
3
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-BpDG_D5m.mjs";
2
+ import { l as validatePeerDependency, n as detectEngine, s as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-C4qT_vl3.mjs";
3
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
@@ -18,6 +18,21 @@ function packageVersion(root, name) {
18
18
  }
19
19
  }
20
20
  /**
21
+ * The supported Node floor, as [major, minor], read from this package's own
22
+ * `engines.node`. Single source: the manifest is what a package manager enforces
23
+ * at install time, so a diagnostic must not carry its own copy of the number.
24
+ */
25
+ function nodeFloor() {
26
+ const fallback = [20, 19];
27
+ try {
28
+ const manifest = JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
29
+ const match = /(\d+)\.(\d+)/.exec(manifest.engines?.node ?? "");
30
+ return match ? [Number(match[1]), Number(match[2])] : fallback;
31
+ } catch {
32
+ return fallback;
33
+ }
34
+ }
35
+ /**
21
36
  * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
22
37
  * is used when there is none.
23
38
  *
@@ -161,8 +176,10 @@ function runDoctor(root, nodeVersion = process.versions.node) {
161
176
  lines.push(`vitest-native doctor — ${root}`);
162
177
  lines.push("", "Runtime");
163
178
  const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
164
- if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
165
- else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
179
+ const [floorMajor, floorMinor] = nodeFloor();
180
+ const floorText = `${floorMajor}.${floorMinor}`;
181
+ if (nodeMajorMinor[0] > floorMajor || nodeMajorMinor[0] === floorMajor && nodeMajorMinor[1] >= floorMinor) pass(`Node ${nodeVersion} (floor: ${floorText})`);
182
+ else fail(`Node ${nodeVersion} — vitest-native requires Node >= ${floorText}.`);
166
183
  lines.push("", "Peer dependencies");
167
184
  for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
168
185
  if (optional) continue;
@@ -188,6 +205,7 @@ function runDoctor(root, nodeVersion = process.versions.node) {
188
205
  const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
189
206
  if (rntlError) warn(rntlError);
190
207
  else if (rntlMajor >= 14 && (nodeMajorMinor[0] < 22 || nodeMajorMinor[0] === 22 && nodeMajorMinor[1] < 13)) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
208
+ else if (rntlMajor >= 14 && !packageVersion(rootFor("test-renderer"), "test-renderer")) fail(`@testing-library/react-native ${rntl} requires the 'test-renderer' package, which is not installed. Every render() will fail with "Cannot find module 'test-renderer'". Install it:\n\n npm install -D test-renderer\n`);
191
209
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
192
210
  }
193
211
  lines.push("", "Auto-detected presets");
@@ -1,10 +1,10 @@
1
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
- const require_errors = require("./errors-flXDIeWk.cjs");
3
- const require_preset_map = require("./preset-map-DxilQ4pI.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-B3lJK46O.cjs");
3
+ const require_preset_map = require("./preset-map-BoG19dLa.cjs");
4
4
  let node_fs = require("node:fs");
5
- node_fs = require_chunk.__toESM(node_fs, 1);
5
+ node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
6
6
  let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path, 1);
7
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
8
8
  let node_module = require("node:module");
9
9
  //#region src/validate.ts
10
10
  const KNOWN_OPTIONS = [
@@ -128,6 +128,126 @@ const PEER_REQUIREMENTS = [
128
128
  optional: true
129
129
  }
130
130
  ];
131
+ //#endregion
132
+ //#region src/native/match.mjs
133
+ /**
134
+ * Which files belong to which package — the one place that decides it.
135
+ *
136
+ * The native engine splits the module graph between Vite and Node (the rule itself is
137
+ * written down in the header of apply.ts). Four places used to answer "does this file
138
+ * belong to a Node-owned package?" independently: the externalization patterns handed
139
+ * to Vitest, auto-detection, and the transform matchers in the require hook and the
140
+ * ESM loader. They agreed by construction rather than by structure, and three of the
141
+ * defects in this area were one of them disagreeing with the others — a directory
142
+ * anchor the transform side applied and the config side did not, a `node_modules`
143
+ * rule that also matched any folder sharing a package's name, and a separator
144
+ * mismatch that only appeared on Windows.
145
+ *
146
+ * Vitest's `server.deps.external` takes patterns rather than a predicate, so config
147
+ * time and run time cannot literally call the same function. They can be generated
148
+ * from the same rules, which is what `packagePatterns` is for: `buildPkgMatcher`
149
+ * tests exactly the patterns that were handed to Vitest.
150
+ *
151
+ * Everything here is pure. apply.ts bundles a copy into the plugin entry while the
152
+ * worker loads this file directly, so it must stay that way — module-level state
153
+ * would exist twice.
154
+ */
155
+ /**
156
+ * React Native's own source, including the `@react-native/*` packages. Node owns
157
+ * these unconditionally: the Flow strip, the boundary mocks and the precompiled
158
+ * registry are all Node loader hooks.
159
+ */
160
+ const REACT_NATIVE_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
161
+ /** Escape a string for literal use inside a RegExp. */
162
+ function escapeRe(value) {
163
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
164
+ }
165
+ /** Forward slashes, the form Vitest presents module ids in. */
166
+ function toPosix(value) {
167
+ return value.replace(/\\/g, "/");
168
+ }
169
+ /**
170
+ * Does `dir` contain `target` (or equal it)?
171
+ *
172
+ * Used to recognise the package the run lives in. A package directory containing the
173
+ * Vitest root is the project, not a dependency of it — externalizing it hands Vitest
174
+ * its own source and test files back through Node, where they are compiled to
175
+ * CommonJS.
176
+ *
177
+ * Compared case-insensitively on Windows: `require.resolve` reports the on-disk
178
+ * casing while a working directory carries whatever the shell supplied, and a
179
+ * drive-letter difference alone would silently defeat the check.
180
+ */
181
+ function containsPath(dir, target) {
182
+ const normalize = (value) => {
183
+ const resolved = node_path.default.resolve(value);
184
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
185
+ };
186
+ const outer = normalize(dir);
187
+ const inner = normalize(target);
188
+ return inner === outer || inner.startsWith(outer.endsWith(node_path.default.sep) ? outer : outer + node_path.default.sep);
189
+ }
190
+ /**
191
+ * The on-disk directory a package resolves to, or null.
192
+ *
193
+ * `pkg/package.json` is tried first because it names the package root exactly; some
194
+ * packages do not export it, so fall back to resolving the entry and walking up to
195
+ * the manifest that names them. Symlinked and workspace packages resolve to their
196
+ * real location, which is the whole point — see buildPkgMatcher.
197
+ */
198
+ function packageDirOf(name, projectRoot) {
199
+ const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
200
+ try {
201
+ return node_path.default.dirname(req.resolve(`${name}/package.json`));
202
+ } catch {}
203
+ let dir;
204
+ try {
205
+ dir = node_path.default.dirname(req.resolve(name));
206
+ } catch {
207
+ return null;
208
+ }
209
+ for (;;) {
210
+ try {
211
+ if ((0, node_module.createRequire)(node_path.default.join(dir, "index.js"))("./package.json").name === name) return dir;
212
+ } catch {}
213
+ const parent = node_path.default.dirname(dir);
214
+ if (parent === dir) return null;
215
+ dir = parent;
216
+ }
217
+ }
218
+ /**
219
+ * The patterns identifying one package's files. THE rule; everything else composes it.
220
+ *
221
+ * A bare `[/\]name[/\]` test — what this used to be — also matches any DIRECTORY
222
+ * that happens to share a package's name. A project folder called `expo`, or a source
223
+ * directory named after the library it implements, made every file beneath it look
224
+ * like third-party source to be compiled. That mis-compiled unrelated files, this
225
+ * package's own runtime among them.
226
+ *
227
+ * Anchoring on `node_modules` alone would fix that and break linked packages: a
228
+ * workspace or `file:` dependency resolves to its real path, which has no
229
+ * `node_modules` segment at all. So a file matches if it is either
230
+ *
231
+ * - under `node_modules/<name>/` (covers additional copies of a package that a
232
+ * single resolution cannot see, and projects where resolution fails), or
233
+ * - inside the package's resolved directory (exact; covers workspace links, and
234
+ * stores like pnpm's and bun's).
235
+ *
236
+ * The resolved-directory anchor is dropped when that directory CONTAINS the project
237
+ * root, because then it is the project. Externalizing the project hands Vitest its
238
+ * own source and test files back through Node, which compiles them to CommonJS: a
239
+ * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
240
+ *
241
+ * `projectRoot` is optional; without it only the `node_modules` rule applies, since
242
+ * there is nothing to resolve against.
243
+ */
244
+ function packagePatterns(name, projectRoot) {
245
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(name)}[\\\\/]`)];
246
+ if (!projectRoot) return patterns;
247
+ const dir = packageDirOf(name, projectRoot);
248
+ if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
249
+ return patterns;
250
+ }
131
251
  /** Can this project run the native engine? (Both transform deps resolvable.) */
132
252
  function isNativeCapable(projectRoot) {
133
253
  try {
@@ -177,12 +297,18 @@ function detectEngine(requested, projectRoot, opts) {
177
297
  * engine itself wires up; pulling a second copy of them into the module graph has
178
298
  * corrupted rendering before, in ways that surface as unrelated act() and
179
299
  * host-component failures.
300
+ *
301
+ * This list is one clause of the ownership rule; the whole of it is written down in
302
+ * the header of native/apply.ts, which is the file to read before changing what ends
303
+ * up in either graph.
180
304
  */
181
- const NEVER_INLINE = new Set([
305
+ const NEVER_INLINE = /* @__PURE__ */ new Set([
182
306
  "@testing-library/react-native",
183
307
  "react-test-renderer",
184
308
  "test-renderer",
185
- "react-native"
309
+ "react-native",
310
+ "react",
311
+ "react-is"
186
312
  ]);
187
313
  /** Manifest fields that make a package part of the React Native ecosystem. */
188
314
  function dependsOnReactNative(manifest) {
@@ -288,9 +414,9 @@ function manifestsFrom(projectRoot) {
288
414
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
289
415
  * in `transform` — that option keeps its existing meaning and takes precedence.
290
416
  */
291
- function detectEcosystemPackages(projectRoot, explicit = []) {
417
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
292
418
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
293
- const skip = new Set([
419
+ const skip = /* @__PURE__ */ new Set([
294
420
  ...NEVER_INLINE,
295
421
  ...Object.keys(require_preset_map.AUTO_DETECT_PRESETS),
296
422
  ...explicit
@@ -307,15 +433,77 @@ function detectEcosystemPackages(projectRoot, explicit = []) {
307
433
  if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
308
434
  }
309
435
  if (candidates.size === 0) return [];
436
+ /** Resolve a package's manifest from whichever root can see it. */
437
+ const manifestOf = (name) => {
438
+ for (const req of requires) try {
439
+ return req(`${name}/package.json`);
440
+ } catch {}
441
+ return null;
442
+ };
443
+ /**
444
+ * The packages the run itself lives in — the project, in other words.
445
+ *
446
+ * In a workspace, the package under test is usually declared as a dependency by a
447
+ * sibling or by the repository root, so it appears in the candidate set like any
448
+ * third-party library — and it declares React Native, because it is React Native
449
+ * code. Detecting it would claim the project's own source: its directory becomes a
450
+ * `server.deps.external` pattern, so Vitest hands every file under it to Node,
451
+ * where the loader compiles it to CommonJS. A test file's own
452
+ * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
453
+ * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
454
+ * appears in one workspace package and not another for no visible reason.
455
+ *
456
+ * A package cannot be its own dependency, so a manifest whose directory contains a
457
+ * run root belongs to the project. Read straight off the manifests already walked,
458
+ * which is both cheaper than resolving each candidate and independent of how a
459
+ * package manager happens to lay out its store — under pnpm every workspace member
460
+ * is additionally linked into a hidden directory on NODE_PATH, so a package can
461
+ * resolve its own name from its own directory, but nothing here depends on that.
462
+ *
463
+ * Workspace libraries the project merely depends on sit beside a run root rather
464
+ * than above it and are unaffected — detecting those is the point of the
465
+ * workspace-member walk above.
466
+ */
467
+ const ownerRoots = [...roots, ...testRoots];
468
+ const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
469
+ const ownsTheRun = (name) => runOwners.has(name);
310
470
  const detected = [];
311
471
  for (const name of candidates) {
312
472
  if (skip.has(name) || name.startsWith("@react-native/")) continue;
313
- for (const req of requires) try {
314
- if (dependsOnReactNative(req(`${name}/package.json`))) detected.push(name);
315
- break;
316
- } catch {}
473
+ const pkg = manifestOf(name);
474
+ if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
475
+ }
476
+ const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
477
+ /** Every package reachable from `roots` through runtime dependencies. */
478
+ const closureOf = (starts) => {
479
+ const seen = /* @__PURE__ */ new Set();
480
+ const pending = [...starts];
481
+ while (pending.length > 0) {
482
+ const name = pending.pop();
483
+ if (seen.has(name)) continue;
484
+ seen.add(name);
485
+ const deps = manifestOf(name)?.dependencies;
486
+ if (deps && typeof deps === "object") pending.push(...Object.keys(deps));
487
+ }
488
+ return seen;
489
+ };
490
+ const toolchain = closureOf(["@babel/core", "@react-native/babel-preset"]);
491
+ const inClosure = new Set(detected);
492
+ const queue = [...detected];
493
+ while (queue.length > 0) {
494
+ const deps = manifestOf(queue.pop())?.dependencies;
495
+ if (!deps || typeof deps !== "object") continue;
496
+ for (const dep of Object.keys(deps)) {
497
+ if (inClosure.has(dep) || skip.has(dep) || dep.startsWith("@react-native/")) continue;
498
+ if (rnOwned.has(dep)) continue;
499
+ if (toolchain.has(dep)) continue;
500
+ if (ownsTheRun(dep)) continue;
501
+ if (!manifestOf(dep)) continue;
502
+ inClosure.add(dep);
503
+ queue.push(dep);
504
+ }
317
505
  }
318
- return detected.sort();
506
+ return [...inClosure].sort();
319
507
  }
320
508
  //#endregion
321
509
  Object.defineProperty(exports, "PEER_REQUIREMENTS", {
@@ -324,6 +512,18 @@ Object.defineProperty(exports, "PEER_REQUIREMENTS", {
324
512
  return PEER_REQUIREMENTS;
325
513
  }
326
514
  });
515
+ Object.defineProperty(exports, "REACT_NATIVE_PATH", {
516
+ enumerable: true,
517
+ get: function() {
518
+ return REACT_NATIVE_PATH;
519
+ }
520
+ });
521
+ Object.defineProperty(exports, "containsPath", {
522
+ enumerable: true,
523
+ get: function() {
524
+ return containsPath;
525
+ }
526
+ });
327
527
  Object.defineProperty(exports, "detectEcosystemPackages", {
328
528
  enumerable: true,
329
529
  get: function() {
@@ -336,6 +536,18 @@ Object.defineProperty(exports, "detectEngine", {
336
536
  return detectEngine;
337
537
  }
338
538
  });
539
+ Object.defineProperty(exports, "packageDirOf", {
540
+ enumerable: true,
541
+ get: function() {
542
+ return packageDirOf;
543
+ }
544
+ });
545
+ Object.defineProperty(exports, "packagePatterns", {
546
+ enumerable: true,
547
+ get: function() {
548
+ return packagePatterns;
549
+ }
550
+ });
339
551
  Object.defineProperty(exports, "validateOptions", {
340
552
  enumerable: true,
341
553
  get: function() {