vitest-native 0.8.0 → 0.9.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 (46) hide show
  1. package/CHANGELOG.md +332 -0
  2. package/README.md +15 -1
  3. package/dist/cli.cjs +506 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +502 -0
  7. package/dist/ecosystem-BIWaVwYL.cjs +294 -0
  8. package/dist/ecosystem-EFtHnKS9.mjs +256 -0
  9. package/dist/{index-vlK4zxuK.d.mts → index-CEgRDdhd.d.cts} +13 -3
  10. package/dist/{index-YjjYELG7.d.cts → index-j-0tueBr.d.mts} +11 -5
  11. package/dist/index.cjs +345 -200
  12. package/dist/index.d.cts +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +341 -196
  15. package/dist/jest-compat/setup.mjs +65 -1
  16. package/dist/native/boundary.mjs +108 -30
  17. package/dist/native/compile-cache.mjs +10 -5
  18. package/dist/native/explain.mjs +69 -0
  19. package/dist/native/hooks.mjs +76 -3
  20. package/dist/native/loader.mjs +35 -6
  21. package/dist/native/match.mjs +107 -8
  22. package/dist/native/registry.mjs +471 -0
  23. package/dist/native/reset.mjs +18 -12
  24. package/dist/native/runner.mjs +13 -7
  25. package/dist/native/setup.mjs +15 -1
  26. package/dist/native/transform.mjs +88 -19
  27. package/dist/native/worker.mjs +10 -1
  28. package/dist/pool-CJmjRgsB.mjs +117 -0
  29. package/dist/pool-DzsEo9vv.cjs +121 -0
  30. package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-CG4FMtsl.cjs} +1 -0
  31. package/dist/{preset-map-DCWaM08s.mjs → preset-map-CNsZKfvu.mjs} +1 -0
  32. package/dist/{presets-7eMfp7o2.cjs → presets-C4faM3ds.cjs} +133 -2
  33. package/dist/{presets-23FJ76O4.mjs → presets-CuDrNA_W.mjs} +128 -3
  34. package/dist/presets.cjs +2 -1
  35. package/dist/presets.d.cts +2 -2
  36. package/dist/presets.d.mts +2 -2
  37. package/dist/presets.mjs +2 -2
  38. package/dist/setup.cjs +318 -130
  39. package/dist/setup.mjs +318 -130
  40. package/docs/hot-default-design.md +129 -0
  41. package/docs/migrating-from-jest.md +43 -7
  42. package/docs/migrating-from-vitest-react-native.md +1 -1
  43. package/docs/release-readiness.md +2 -1
  44. package/package.json +17 -5
  45. package/dist/pool-B7LBfcMQ.mjs +0 -67
  46. package/dist/pool-p54QV1dQ.cjs +0 -69
package/dist/cli.cjs ADDED
@@ -0,0 +1,506 @@
1
+ #!/usr/bin/env node
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const require_chunk = require("./chunk-CZWwpsFl.cjs");
4
+ const require_ecosystem = require("./ecosystem-BIWaVwYL.cjs");
5
+ const require_preset_map = require("./preset-map-CG4FMtsl.cjs");
6
+ let node_path = require("node:path");
7
+ node_path = require_chunk.__toESM(node_path, 1);
8
+ let node_fs = require("node:fs");
9
+ node_fs = require_chunk.__toESM(node_fs, 1);
10
+ let node_module = require("node:module");
11
+ //#region src/cli/doctor.ts
12
+ /**
13
+ * `vitest-native doctor` — diagnose the project's environment: peer versions,
14
+ * engine resolution (and why), detected presets, RNTL/Node compatibility, and
15
+ * config presence. Read-only; never mutates the project.
16
+ */
17
+ function packageVersion(root, name) {
18
+ try {
19
+ return (0, node_module.createRequire)(node_path.default.join(root, "package.json"))(`${name}/package.json`).version ?? null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+ function findConfigFile(root) {
25
+ for (const name of [
26
+ "vitest.config.ts",
27
+ "vitest.config.mts",
28
+ "vitest.config.js",
29
+ "vitest.config.mjs",
30
+ "vitest.config.cts",
31
+ "vitest.config.cjs"
32
+ ]) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
33
+ return null;
34
+ }
35
+ function runDoctor(root, nodeVersion = process.versions.node) {
36
+ const lines = [];
37
+ let ok = true;
38
+ const pass = (s) => lines.push(` ✓ ${s}`);
39
+ const warn = (s) => lines.push(` ⚠ ${s}`);
40
+ const fail = (s) => {
41
+ ok = false;
42
+ lines.push(` ✗ ${s}`);
43
+ };
44
+ lines.push(`vitest-native doctor — ${root}`);
45
+ lines.push("", "Runtime");
46
+ const nodeMajorMinor = nodeVersion.split(".").slice(0, 2).map(Number);
47
+ if (nodeMajorMinor[0] >= 20) pass(`Node ${nodeVersion} (floor: 20)`);
48
+ else fail(`Node ${nodeVersion} — vitest-native requires Node >= 20.`);
49
+ lines.push("", "Peer dependencies");
50
+ for (const { name, minimum, maximumMajor, minimumByMajor } of require_ecosystem.PEER_REQUIREMENTS) {
51
+ const error = require_ecosystem.validatePeerDependency(name, minimum, root, maximumMajor, minimumByMajor);
52
+ if (error) fail(error);
53
+ else pass(`${name} ${packageVersion(root, name)}`);
54
+ }
55
+ lines.push("", "Engine");
56
+ const rnVersion = packageVersion(root, "react-native");
57
+ if (require_ecosystem.detectEngine("auto", root).engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with @react-native/babel-preset + @babel/core present.`);
58
+ else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but @react-native/babel-preset and/or @babel/core do not resolve. Install both as devDependencies to run the real-RN native engine.`);
59
+ else warn("engine 'auto' resolves to MOCK: react-native is not installed. That is fine for pure-logic suites; install react-native (+ its babel preset) for the native engine.");
60
+ lines.push("", "Testing library");
61
+ const rntl = packageVersion(root, "@testing-library/react-native");
62
+ if (!rntl) warn("@testing-library/react-native not found — optional, but required for render()/screen queries.");
63
+ else {
64
+ const rntlMajor = Number(rntl.split(".")[0]);
65
+ if (rntlMajor < 12 || rntlMajor >= 15) fail(`@testing-library/react-native ${rntl} — supported range is >=12 <15.`);
66
+ 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.`);
67
+ else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
68
+ }
69
+ lines.push("", "Auto-detected presets");
70
+ const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
71
+ const detected = [];
72
+ for (const [pkg, preset] of Object.entries(require_preset_map.AUTO_DETECT_PRESETS)) try {
73
+ req.resolve(pkg);
74
+ detected.push(`${pkg} → ${preset}`);
75
+ } catch {}
76
+ if (detected.length) for (const d of detected) pass(d);
77
+ else lines.push(" (none — no preset-covered packages installed)");
78
+ const expo = packageVersion(root, "expo");
79
+ if (expo) {
80
+ lines.push("", "Expo");
81
+ warn(`expo ${expo} detected. Expo-module components work via the auto-detected preset; suites that import Expo CORE internals (expo-router setups, dev-client wiring) can hit known limits — see the Jest migration guide's Expo notes.`);
82
+ }
83
+ lines.push("", "Config");
84
+ const configFile = findConfigFile(root);
85
+ if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
86
+ else {
87
+ const content = node_fs.default.readFileSync(node_path.default.join(root, configFile), "utf8");
88
+ if (content.includes("vitest-native") || content.includes("reactNative(")) pass(`${configFile} uses vitest-native.`);
89
+ else warn(`${configFile} exists but does not reference vitest-native.`);
90
+ }
91
+ lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
92
+ return {
93
+ lines,
94
+ ok
95
+ };
96
+ }
97
+ //#endregion
98
+ //#region src/cli/init.ts
99
+ /**
100
+ * `vitest-native init` — write a ready-to-run Vitest config. Two shapes:
101
+ * the zero-config default, and the jest-compat variant (the exact block the
102
+ * migration guide documents, so docs and CLI can never drift apart by shape).
103
+ */
104
+ const PLAIN_CONFIG = `import { defineConfig } from 'vitest/config'
105
+ import { reactNative } from 'vitest-native'
106
+
107
+ export default defineConfig({
108
+ // Zero config: engine 'auto' runs REAL React Native (mocking only the native
109
+ // boundary) when @react-native/babel-preset + @babel/core are present, and
110
+ // falls back to the pure-JS mock engine otherwise.
111
+ plugins: [reactNative()],
112
+ test: {
113
+ environment: 'node',
114
+ },
115
+ })
116
+ `;
117
+ const JEST_COMPAT_CONFIG = `import { defineConfig } from 'vitest/config'
118
+ import { reactNative } from 'vitest-native'
119
+ import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
120
+
121
+ export default defineConfig({
122
+ // jestMockTransform() must come AFTER reactNative() and stay normal-order:
123
+ // it rewrites top-level jest.mock(...) into hoisted vi.mock(...).
124
+ plugins: [reactNative(), jestMockTransform()],
125
+ resolve: {
126
+ dedupe: ['react', 'react-test-renderer', 'react-is'],
127
+ alias: { ...jestCompatAliases() },
128
+ },
129
+ test: {
130
+ globals: true,
131
+ environment: 'node',
132
+ setupFiles: [jestCompatSetup],
133
+ },
134
+ })
135
+ `;
136
+ function renderInitConfig(jestCompat) {
137
+ return jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
138
+ }
139
+ function existingConfig(root) {
140
+ for (const name of [
141
+ "vitest.config.ts",
142
+ "vitest.config.mts",
143
+ "vitest.config.js",
144
+ "vitest.config.mjs",
145
+ "vitest.config.cts",
146
+ "vitest.config.cjs"
147
+ ]) if (node_fs.default.existsSync(node_path.default.join(root, name))) return name;
148
+ return null;
149
+ }
150
+ function runInit(root, opts = {}) {
151
+ const lines = [];
152
+ const existing = existingConfig(root);
153
+ if (existing && !opts.force) return {
154
+ lines: [`✗ ${existing} already exists — not overwriting. Re-run with --force to replace it,`, ` or run \`vitest-native migrate\` to analyze an existing Jest setup first.`],
155
+ ok: false
156
+ };
157
+ const file = node_fs.default.existsSync(node_path.default.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
158
+ const target = node_path.default.join(root, file);
159
+ node_fs.default.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false));
160
+ lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
161
+ if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
162
+ lines.push("", "Next steps:", ` 1. add a script: "test": "vitest"`, ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
163
+ if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
164
+ return {
165
+ lines,
166
+ ok: true,
167
+ wrote: file
168
+ };
169
+ }
170
+ //#endregion
171
+ //#region src/cli/migrate.ts
172
+ /**
173
+ * `vitest-native migrate` — analyze a project's Jest configuration and report,
174
+ * key by key, what maps automatically, what the presets already cover (delete
175
+ * it), and what needs a human. Dry-run by default; --write emits the suggested
176
+ * Vitest config. It never edits test files: `jestMockTransform()` handles
177
+ * top-level `jest.mock` at runtime, so file codemods aren't required to start.
178
+ */
179
+ /**
180
+ * Extract package names from Jest's classic transformIgnorePatterns allowlist
181
+ * (`node_modules/(?!(?:pkg1|@scope/pkg2|...)/)`). Best-effort by design: the
182
+ * raw pattern is always surfaced in the report alongside the extraction, and
183
+ * entries the extraction cannot be confident about (capturing groups like
184
+ * `(jest-)?react-native`, whose strip would fabricate a package name) are
185
+ * returned separately instead of guessed at.
186
+ */
187
+ function extractAllowlistPackages(pattern) {
188
+ const m = /\(\?!((?:[^()]|\([^()]*\))*)\)/.exec(pattern);
189
+ if (!m) return {
190
+ packages: [],
191
+ unparseable: []
192
+ };
193
+ const packages = [];
194
+ const unparseable = [];
195
+ for (const raw of m[1].split("|")) {
196
+ const entry = raw.trim();
197
+ if (!entry) continue;
198
+ if (/\((?!\?)/.test(entry)) {
199
+ unparseable.push(entry);
200
+ continue;
201
+ }
202
+ const cleaned = entry.replace(/\(\?:/g, "").replace(/[()?*^$]/g, "").replace(/\\\//g, "/").replace(/\/\.$/, "").replace(/\/$/, "").replace(/\.$/, "").trim();
203
+ if (cleaned.length > 0 && !cleaned.includes("\\")) packages.push(cleaned);
204
+ else if (entry.length > 0) unparseable.push(entry);
205
+ }
206
+ return {
207
+ packages,
208
+ unparseable
209
+ };
210
+ }
211
+ function loadJestConfig(root) {
212
+ const req = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
213
+ for (const name of [
214
+ "jest.config.js",
215
+ "jest.config.cjs",
216
+ "jest.config.json"
217
+ ]) {
218
+ const file = node_path.default.join(root, name);
219
+ if (!node_fs.default.existsSync(file)) continue;
220
+ try {
221
+ const loaded = name.endsWith(".json") ? JSON.parse(node_fs.default.readFileSync(file, "utf8")) : req(file);
222
+ const config = loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
223
+ if (typeof config === "function") return {
224
+ source: name,
225
+ config: null
226
+ };
227
+ return {
228
+ source: name,
229
+ config
230
+ };
231
+ } catch {
232
+ return {
233
+ source: name,
234
+ config: null
235
+ };
236
+ }
237
+ }
238
+ for (const name of [
239
+ "jest.config.mjs",
240
+ "jest.config.ts",
241
+ "jest.config.mts"
242
+ ]) if (node_fs.default.existsSync(node_path.default.join(root, name))) return {
243
+ source: name,
244
+ config: null
245
+ };
246
+ try {
247
+ const pkg = JSON.parse(node_fs.default.readFileSync(node_path.default.join(root, "package.json"), "utf8"));
248
+ if (pkg.jest && typeof pkg.jest === "object") return {
249
+ source: "package.json#jest",
250
+ config: pkg.jest
251
+ };
252
+ } catch {}
253
+ return {
254
+ source: null,
255
+ config: null
256
+ };
257
+ }
258
+ function analyzeJestConfig(root) {
259
+ const { source, config } = loadJestConfig(root);
260
+ const automatic = [];
261
+ const attention = [];
262
+ const presetCovered = [];
263
+ const dropped = [];
264
+ const testEntries = [`globals: true`, `environment: 'node'`];
265
+ const setupFiles = ["jestCompatSetup"];
266
+ const aliasEntries = ["...jestCompatAliases()"];
267
+ const transformPkgs = [];
268
+ const autoInlined = new Set(require_ecosystem.detectEcosystemPackages(root));
269
+ let needsUrlImport = false;
270
+ const presetPkgs = new Set(Object.keys(require_preset_map.AUTO_DETECT_PRESETS));
271
+ if (config) {
272
+ const handled = /* @__PURE__ */ new Set();
273
+ const take = (key) => {
274
+ handled.add(key);
275
+ return config[key];
276
+ };
277
+ const preset = take("preset");
278
+ if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin.`);
279
+ else if (preset === "jest-expo") attention.push("preset: 'jest-expo' → the reactNative() plugin + auto-detected expo preset replace most of it, but suites importing Expo CORE internals can hit known limits (see the migration guide's Expo notes).");
280
+ else if (preset) attention.push(`preset: '${preset}' — unknown preset; review what it configured.`);
281
+ for (const key of ["setupFiles", "setupFilesAfterEnv"]) {
282
+ const files = take(key);
283
+ if (!files?.length) continue;
284
+ for (const f of files) if (/react-native\/jest\/setup|jest-expo/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
285
+ else {
286
+ setupFiles.push(JSON.stringify(f));
287
+ automatic.push(`${key}: '${f}' → test.setupFiles (its jest.* calls run under the jest-compat shim).`);
288
+ }
289
+ }
290
+ const mapper = take("moduleNameMapper");
291
+ if (mapper) for (const [pattern, target] of Object.entries(mapper)) if (/\\\./.test(pattern) && /\b(png|jpe?g|gif|webp|svg|ttf|otf|woff2?|mp4|mp3)\b/i.test(pattern)) presetCovered.push(`moduleNameMapper '${pattern}' — asset stubbing is built in; delete.`);
292
+ else if (/^\^?@\/|\^~\/|\^src\//.test(pattern)) {
293
+ const aliasKey = pattern.replace(/[\^$]/g, "").replace(/\((\.\*|\.\+)\)\$?$/, "").replace(/\/$/, "");
294
+ const aliasTarget = String(target).replace(/^<rootDir>\/?/, "./").replace(/\/\$1$/, "").replace(/\/$/, "");
295
+ if (/[(){}?+*\\[\]]/.test(aliasKey) || /[(){}?+*\\[\]$]/.test(aliasTarget)) attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
296
+ else {
297
+ aliasEntries.push(`${JSON.stringify(aliasKey)}: fileURLToPath(new URL(${JSON.stringify(aliasTarget)}, import.meta.url))`);
298
+ needsUrlImport = true;
299
+ automatic.push(`moduleNameMapper '${pattern}' → resolve.alias (absolute path).`);
300
+ }
301
+ } else attention.push(`moduleNameMapper '${pattern}' → '${String(target)}' — map manually to resolve.alias (regex mappers need rewriting).`);
302
+ const tip = take("transformIgnorePatterns");
303
+ if (tip?.length) {
304
+ const results = tip.map(extractAllowlistPackages);
305
+ const extracted = results.flatMap((r) => r.packages);
306
+ const unparseable = results.flatMap((r) => r.unparseable);
307
+ automatic.push(`transformIgnorePatterns (raw): ${JSON.stringify(tip)}`);
308
+ for (const entry of unparseable) attention.push(`transformIgnorePatterns entry '${entry}' — could not extract package names confidently; expand it by hand into reactNative({ transform: [...] }) if those packages ship untranspiled source.`);
309
+ if (extracted.length === 0 && unparseable.length === 0) attention.push(`transformIgnorePatterns: ${JSON.stringify(tip)} — could not extract an allowlist automatically; packages shipping untranspiled source go in reactNative({ transform: [...] }).`);
310
+ else for (const pkg of extracted) if (pkg === "react-native" || pkg.startsWith("@react-native")) automatic.push(`transformIgnorePatterns allows '${pkg}' — the native engine transforms RN itself; nothing to do.`);
311
+ else if (presetPkgs.has(pkg)) presetCovered.push(`transformIgnorePatterns allows '${pkg}' — shadowed by the auto-detected preset; nothing to do.`);
312
+ else if (autoInlined.has(pkg)) automatic.push(`transformIgnorePatterns allows '${pkg}' — declares react-native, so the engine compiles it automatically; nothing to do.`);
313
+ else {
314
+ transformPkgs.push(pkg);
315
+ automatic.push(`transformIgnorePatterns allows '${pkg}' → reactNative({ transform: [...] }).`);
316
+ }
317
+ }
318
+ const timeout = take("testTimeout");
319
+ if (typeof timeout === "number") {
320
+ testEntries.push(`testTimeout: ${timeout}`);
321
+ automatic.push(`testTimeout: ${timeout} → test.testTimeout.`);
322
+ }
323
+ const env = take("testEnvironment");
324
+ if (env && env !== "node") attention.push(`testEnvironment: '${env}' — vitest-native suites run under 'node'; review.`);
325
+ else handled.add("testEnvironment");
326
+ if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — configure per-suite with vi.useFakeTimers() (the jest-compat shim covers jest.useFakeTimers()).`);
327
+ const testMatch = take("testMatch");
328
+ if (testMatch?.length) {
329
+ testEntries.push(`include: [${testMatch.map((g) => JSON.stringify(g.replace("<rootDir>/", ""))).join(", ")}]`);
330
+ automatic.push(`testMatch → test.include.`);
331
+ }
332
+ const ignore = take("testPathIgnorePatterns");
333
+ if (ignore?.length) attention.push(`testPathIgnorePatterns: ${JSON.stringify(ignore)} — move to test.exclude (glob syntax, not regex).`);
334
+ const coverageFrom = take("collectCoverageFrom");
335
+ if (coverageFrom?.length) {
336
+ testEntries.push(`coverage: { include: [${coverageFrom.map((g) => JSON.stringify(g.replace(/^<rootDir>\//, ""))).join(", ")}] }`);
337
+ automatic.push(`collectCoverageFrom → test.coverage.include (install @vitest/coverage-v8).`);
338
+ }
339
+ take("coveragePathIgnorePatterns");
340
+ take("coverageThreshold");
341
+ if (config.coveragePathIgnorePatterns || config.coverageThreshold) attention.push(`coverage settings — map onto test.coverage.{exclude,thresholds}.`);
342
+ for (const key of [
343
+ "moduleFileExtensions",
344
+ "maxWorkers",
345
+ "verbose",
346
+ "clearMocks",
347
+ "resetMocks",
348
+ "restoreMocks",
349
+ "collectCoverage",
350
+ "coverageDirectory",
351
+ "coverageReporters",
352
+ "cacheDirectory",
353
+ "haste",
354
+ "watchPlugins",
355
+ "transform",
356
+ "globals",
357
+ "roots",
358
+ "testRegex",
359
+ "snapshotSerializers",
360
+ "reporters",
361
+ "modulePathIgnorePatterns"
362
+ ]) if (config[key] !== void 0) {
363
+ handled.add(key);
364
+ if (key === "transform") dropped.push(`transform — Babel/esbuild transforms are the plugin's job; dropped.`);
365
+ else if (key === "clearMocks" || key === "resetMocks" || key === "restoreMocks") {
366
+ automatic.push(`${key} → test.${key} (same name in Vitest).`);
367
+ testEntries.push(`${key}: ${JSON.stringify(config[key])}`);
368
+ } else if (key === "snapshotSerializers") attention.push(`snapshotSerializers — Vitest uses expect.addSnapshotSerializer; vitest-native ships one for RN trees.`);
369
+ else dropped.push(`${key} — no vitest-native equivalent needed; dropped.`);
370
+ }
371
+ for (const key of Object.keys(config)) if (!handled.has(key)) attention.push(`'${key}' — unrecognized Jest key; review manually.`);
372
+ }
373
+ const mocksDir = node_path.default.join(root, "__mocks__");
374
+ if (node_fs.default.existsSync(mocksDir)) for (const entry of node_fs.default.readdirSync(mocksDir)) {
375
+ const name = entry.replace(/\.(js|cjs|mjs|ts|tsx)$/, "");
376
+ const candidates = node_fs.default.statSync(node_path.default.join(mocksDir, entry)).isDirectory() ? node_fs.default.readdirSync(node_path.default.join(mocksDir, entry)).map((f) => `${name}/${f.replace(/\.(js|cjs|mjs|ts|tsx)$/, "")}`) : [name];
377
+ for (const candidate of candidates) if (presetPkgs.has(candidate)) {
378
+ const preset = require_preset_map.AUTO_DETECT_PRESETS[candidate];
379
+ presetCovered.push(`__mocks__/${candidate} — the ${preset} preset covers this; delete the manual mock.`);
380
+ }
381
+ }
382
+ const transformLine = transformPkgs.length ? `reactNative({ transform: [${transformPkgs.map((p) => JSON.stringify(p)).join(", ")}] })` : `reactNative()`;
383
+ return {
384
+ source,
385
+ automatic,
386
+ attention,
387
+ presetCovered,
388
+ dropped,
389
+ suggestedConfig: `import { defineConfig } from 'vitest/config'
390
+ import { reactNative } from 'vitest-native'
391
+ import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
392
+ ${needsUrlImport ? "import { fileURLToPath } from 'node:url'\n" : ""}
393
+ export default defineConfig({
394
+ plugins: [${transformLine}, jestMockTransform()],
395
+ resolve: {
396
+ dedupe: ['react', 'react-test-renderer', 'react-is'],
397
+ alias: { ${aliasEntries.join(", ")} },
398
+ },
399
+ test: {
400
+ ${testEntries.join(",\n ")},
401
+ setupFiles: [${setupFiles.join(", ")}],
402
+ },
403
+ })
404
+ `,
405
+ ok: source !== null
406
+ };
407
+ }
408
+ function renderMigrationReport(report) {
409
+ const lines = [];
410
+ if (!report.source) {
411
+ lines.push("✗ no Jest configuration found (package.json#jest or jest.config.{js,cjs,json}).", " Starting fresh? Run `vitest-native init` instead.");
412
+ return lines;
413
+ }
414
+ lines.push(`Analyzed ${report.source}`, "");
415
+ const section = (title, items) => {
416
+ if (!items.length) return;
417
+ lines.push(`${title}:`);
418
+ for (const i of items) lines.push(` • ${i}`);
419
+ lines.push("");
420
+ };
421
+ section("Mapped automatically", report.automatic);
422
+ section("Covered by presets — delete", report.presetCovered);
423
+ section("Needs your attention", report.attention);
424
+ section("Dropped (no equivalent needed)", report.dropped);
425
+ lines.push("Suggested vitest.config:", "");
426
+ lines.push(...report.suggestedConfig.split("\n").map((l) => ` ${l}`));
427
+ lines.push("Re-run with --write to save this config, then: npx vitest-native doctor && npx vitest");
428
+ return lines;
429
+ }
430
+ //#endregion
431
+ //#region src/cli/index.ts
432
+ /**
433
+ * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
434
+ * environment), `migrate` (analyze a Jest config and report the mapping).
435
+ * Deliberately vitest-free at module load — it runs via npx outside any test
436
+ * process.
437
+ */
438
+ const USAGE = `vitest-native — test React Native with Vitest
439
+
440
+ Usage:
441
+ vitest-native init [--jest-compat] [--force] write a ready-to-run vitest config
442
+ vitest-native doctor diagnose peers, engine, presets, RNTL/Node
443
+ vitest-native migrate [--write] [--force] analyze jest config → migration report
444
+ (--write also saves the suggested config)
445
+ Options:
446
+ --root <dir> project root (default: cwd)
447
+ --help this text
448
+
449
+ Docs: https://danfry1.github.io/vitest-native/`;
450
+ function main(argv, log = console.log) {
451
+ const args = argv.filter((a) => a !== "--");
452
+ const command = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "--root");
453
+ const has = (flag) => args.includes(flag);
454
+ const rootIdx = args.indexOf("--root");
455
+ const root = node_path.default.resolve(rootIdx !== -1 ? args[rootIdx + 1] ?? "." : ".");
456
+ if (has("--help") || has("-h")) {
457
+ log(USAGE);
458
+ return 0;
459
+ }
460
+ if (!command) {
461
+ log(USAGE);
462
+ return 1;
463
+ }
464
+ if (!node_fs.default.existsSync(node_path.default.join(root, "package.json"))) {
465
+ log(`✗ no package.json at ${root} — run from a project root or pass --root.`);
466
+ return 1;
467
+ }
468
+ switch (command) {
469
+ case "doctor": {
470
+ const result = runDoctor(root);
471
+ for (const line of result.lines) log(line);
472
+ return result.ok ? 0 : 1;
473
+ }
474
+ case "init": {
475
+ const result = runInit(root, {
476
+ jestCompat: has("--jest-compat"),
477
+ force: has("--force")
478
+ });
479
+ for (const line of result.lines) log(line);
480
+ return result.ok ? 0 : 1;
481
+ }
482
+ case "migrate": {
483
+ const report = analyzeJestConfig(root);
484
+ for (const line of renderMigrationReport(report)) log(line);
485
+ if (report.ok && has("--write")) {
486
+ const init = runInit(root, { force: has("--force") });
487
+ if (!init.ok) {
488
+ for (const line of init.lines) log(line);
489
+ return 1;
490
+ }
491
+ const target = node_path.default.join(root, init.wrote);
492
+ node_fs.default.writeFileSync(target, report.suggestedConfig);
493
+ log(`✓ wrote ${init.wrote} from the analysis above.`);
494
+ }
495
+ return report.ok ? 0 : 1;
496
+ }
497
+ default:
498
+ log(`✗ unknown command '${command}'.`);
499
+ log(USAGE);
500
+ return 1;
501
+ }
502
+ }
503
+ const entry = process.argv[1] ? node_path.default.basename(process.argv[1]) : "";
504
+ if (entry === "cli.mjs" || entry === "cli.cjs" || entry === "vitest-native") process.exit(main(process.argv.slice(2)));
505
+ //#endregion
506
+ exports.main = main;
package/dist/cli.d.cts ADDED
@@ -0,0 +1,4 @@
1
+ //#region src/cli/index.d.ts
2
+ declare function main(argv: string[], log?: (line: string) => void): number;
3
+ //#endregion
4
+ export { main };
package/dist/cli.d.mts ADDED
@@ -0,0 +1,4 @@
1
+ //#region src/cli/index.d.ts
2
+ declare function main(argv: string[], log?: (line: string) => void): number;
3
+ //#endregion
4
+ export { main };