vitest-native 0.14.0-rc.9 → 0.14.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 (97) hide show
  1. package/README.md +76 -60
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +175 -63
  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-5o48Ujzs.mjs +939 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-DqU4YO3D.d.mts} +27 -49
  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 +271 -60
  39. package/dist/native/loader.mjs +378 -20
  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 +100 -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 +76 -12
  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
package/dist/cli.mjs CHANGED
@@ -1,28 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { f as validatePeerDependency, i as createNativeOwnershipPolicy, n as detectEngine, r as resolveTransformPreset, s as formatNativeOwnershipManifest, t as detectEcosystemPackages, u as PEER_REQUIREMENTS } from "./ecosystem-D6e1OVOg.mjs";
3
- import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-BlBriTA0.mjs";
4
- import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-FYbP0_gg.mjs";
2
+ import { c as detectEcosystemPackages, d as fsModuleCacheOnByDefault, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, o as usesVitePlus, p as PEER_REQUIREMENTS, r as installedViteVersion, v as validatePeerDependency } from "./host-5o48Ujzs.mjs";
3
+ import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.mjs";
4
+ import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
5
5
  import { createRequire } from "node:module";
6
- import fs from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
7
  import path from "node:path";
8
- //#region src/native/state-manifest.mjs
9
- const HOT_STATE_MANIFEST_ENTRIES = Object.freeze([
10
- "vitest-runtime",
11
- "native-boundary-mocks",
12
- "native-module-mocks",
13
- "react-native.dimensions",
14
- "react-native.appearance",
15
- "react-native.event-listeners",
16
- "process.env",
17
- "process.listeners",
18
- "global.descriptors",
19
- "console.descriptors",
20
- "react-native.error-utils",
21
- "expo.runtime",
22
- "jest-compat.node-mocks"
23
- ]);
24
- //#endregion
25
- //#region src/cli/manifest.ts
8
+ import fs from "node:fs";
9
+ import { createNativeOwnershipPolicy, formatNativeOwnershipManifest } from "./native/ownership.mjs";
10
+ import { resolveTransformPreset } from "./native/babel-preset.mjs";
11
+ import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
12
+ // src/cli/manifest.ts
26
13
  /**
27
14
  * Installed-package facts for the CLI, read from disk.
28
15
  *
@@ -72,8 +59,7 @@ function activePresets(root, disabled = [], engine = "native") {
72
59
  }
73
60
  return [...active];
74
61
  }
75
- //#endregion
76
- //#region src/cli/babel-config.ts
62
+ // src/cli/babel-config.ts
77
63
  /**
78
64
  * The project's Babel configuration, as `migrate` and `doctor` need to see it.
79
65
  *
@@ -297,7 +283,8 @@ function classifyBabelPlugins(report, root, active) {
297
283
  }
298
284
  /** The installed major version of `vite`, or null. */
299
285
  function viteMajor(root) {
300
- return installedMajor(root, "vite");
286
+ const major = Number(installedViteVersion(root)?.replace(/^[^0-9]*/, "").split(".")[0]);
287
+ return Number.isFinite(major) ? major : installedMajor(root, "vite");
301
288
  }
302
289
  /** Whether `name` is installed where the project resolves it. */
303
290
  function installed(root, name) {
@@ -331,8 +318,7 @@ function serializableOptions(entry) {
331
318
  };
332
319
  return entry.options === void 0 || plain(entry.options);
333
320
  }
334
- //#endregion
335
- //#region src/cli/doctor.ts
321
+ // src/cli/doctor.ts
336
322
  /**
337
323
  * `vitest-native doctor` — diagnose the project's environment: peer versions,
338
324
  * engine resolution (and why), detected presets, RNTL/Node compatibility, and
@@ -352,10 +338,18 @@ function packageVersion(root, name) {
352
338
  */
353
339
  function nodeRange() {
354
340
  const fallback = ">=22.13.0 <23 || >=24.3.0";
341
+ for (let dir = path.dirname(fileURLToPath(import.meta.url));; dir = path.dirname(dir)) {
342
+ const manifest = readManifest(path.join(dir, "package.json"));
343
+ if (manifest?.name === "vitest-native") return manifest.engines?.node?.trim() || fallback;
344
+ if (path.dirname(dir) === dir) return fallback;
345
+ }
346
+ }
347
+ /** A package.json, or null where there is none or it does not parse. */
348
+ function readManifest(file) {
355
349
  try {
356
- return JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8")).engines?.node?.trim() || fallback;
350
+ return JSON.parse(fs.readFileSync(file, "utf8"));
357
351
  } catch {
358
- return fallback;
352
+ return null;
359
353
  }
360
354
  }
361
355
  const versionParts = (version) => {
@@ -421,6 +415,67 @@ function findConfigFile(root) {
421
415
  function withoutComments(source) {
422
416
  return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
423
417
  }
418
+ const settingOf = (value) => value === void 0 ? null : value === "false" ? "off" : "set";
419
+ /**
420
+ * How a config sets Vitest's `fsModuleCache`, read as text, in each spelling: inside
421
+ * `experimental: { ... }` (Vitest 4.0.11 and later) and anywhere else (the top-level
422
+ * option, Vitest 5). `off` for a literal `false`, `set` for any other value, null when
423
+ * that spelling is absent.
424
+ */
425
+ function fsModuleCacheSetting(source) {
426
+ const code = withoutComments(source);
427
+ const nested = /\bexperimental\s*:\s*\{[^{}]*?\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(code);
428
+ const rest = nested ? code.replace(nested[0], " ") : code;
429
+ const top = /\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(rest);
430
+ return {
431
+ experimental: settingOf(nested?.[1]),
432
+ topLevel: settingOf(top?.[1])
433
+ };
434
+ }
435
+ /** Whether `version` is at or above `[major, minor, patch]`. */
436
+ function versionAtLeast(version, floor) {
437
+ const parts = version.replace(/^[^0-9]*/, "").split(/[.-]/).slice(0, 3).map(Number);
438
+ for (let i = 0; i < 3; i++) {
439
+ const part = parts[i] ?? 0;
440
+ if (part !== floor[i]) return part > floor[i];
441
+ }
442
+ return true;
443
+ }
444
+ /** The first Vitest with `experimental.fsModuleCache`. */
445
+ const EXPERIMENTAL_FS_MODULE_CACHE_FROM = [
446
+ 4,
447
+ 0,
448
+ 11
449
+ ];
450
+ const TROUBLESHOOTING_STALE_IMPORT = "https://danfry1.github.io/vitest-native/guide/troubleshooting#cannot-find-module-keeps-failing-after-the-missing-file-exists";
451
+ /**
452
+ * The transform-cache note for a Vitest the plugin does not turn the cache on for.
453
+ * Empty where it does (fsModuleCacheOnByDefault, which the plugin reads too), and where
454
+ * the config turns the cache off on purpose.
455
+ */
456
+ function transformCacheAdvice(vitestVersion, configSource) {
457
+ const major = Number(vitestVersion?.replace(/^[^0-9]*/, "").split(".")[0]);
458
+ if (!vitestVersion || !(major >= 4) || fsModuleCacheOnByDefault(major)) return [];
459
+ const setting = configSource === null ? {
460
+ experimental: null,
461
+ topLevel: null
462
+ } : fsModuleCacheSetting(configSource);
463
+ if (setting.experimental === "off") return [];
464
+ const hasOption = versionAtLeast(vitestVersion, EXPERIMENTAL_FS_MODULE_CACHE_FROM);
465
+ const caveat = `A Vitest bug can keep a "Cannot find module" failure cached after the file exists (reproduced on Vitest 5.0.5, unverified on 4); ${TROUBLESHOOTING_STALE_IMPORT} lists when it happens and how to recover.`;
466
+ if (setting.experimental === "set" && hasOption) return [`Vitest ${vitestVersion}: the config sets \`experimental.fsModuleCache\`; while it is on, transformed modules are kept on disk between runs. ${caveat}`];
467
+ const lines = [`Vitest ${vitestVersion} re-transforms every imported module on each run, about half a second per thousand imported modules on one benchmark. Vitest 5 keeps transformed modules on disk between runs, and vitest-native turns that on.`];
468
+ if (setting.topLevel !== null) lines.push("The config sets `test.fsModuleCache`, the Vitest 5 spelling, which has no effect on Vitest 4.");
469
+ lines.push(hasOption ? `To keep them on disk on Vitest 4, set \`test.experimental.fsModuleCache: true\`. ${caveat}` : `Vitest 4.0.11 adds \`test.experimental.fsModuleCache\` to keep them on disk.`);
470
+ return lines;
471
+ }
472
+ /**
473
+ * The Vitest that runs here, as the peer check reports it: the project's own, or under
474
+ * Vite+ the copy this package loads.
475
+ */
476
+ function runningVitestVersion(from) {
477
+ return packageVersion(from, "vitest") ?? (usesVitePlus(from) ? ownVitestPackage()?.version ?? null : null);
478
+ }
424
479
  /**
425
480
  * Whether a config is built on one imported from elsewhere — a shared preset in a
426
481
  * workspace, typically. Such a file legitimately never mentions vitest-native, and
@@ -539,10 +594,11 @@ function runDoctor(root, nodeVersion = process.versions.node) {
539
594
  for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
540
595
  if (optional) continue;
541
596
  const from = rootFor(name);
542
- const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor);
597
+ const running = name === "vite" ? installedViteVersion(from) : name === "vitest" ? runningVitestVersion(from) : null;
598
+ const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor, running);
543
599
  if (error) fail(error);
544
600
  else {
545
- pass(`${name} ${packageVersion(from, name)}`);
601
+ pass(`${name} ${running ?? packageVersion(from, name)}`);
546
602
  if (from !== root) lines.push(` (resolved from ${from}, not from here)`);
547
603
  }
548
604
  }
@@ -598,8 +654,12 @@ function runDoctor(root, nodeVersion = process.versions.node) {
598
654
  }
599
655
  if (detected.length) for (const d of detected) pass(d);
600
656
  else if (!installedAny) lines.push(" (none — no preset-covered packages installed)");
601
- const expo = packageVersion(rootFor("expo"), "expo");
602
- if (expo) {
657
+ const expo = installedExpoVersion(root) ?? (configRoot === root ? null : installedExpoVersion(configRoot));
658
+ const unsupported = expo && unsupportedExpoSdkMessage(expo);
659
+ if (unsupported) {
660
+ lines.push("", "Expo");
661
+ warn(unsupported);
662
+ } else if (expo) {
603
663
  lines.push("", "Expo");
604
664
  pass((decision.engine === "native" ? `expo ${expo} detected. Under the native engine Expo modules run their real JavaScript on native-module mocks, as under jest-expo (unless the config sets \`engine: 'mock'\` or \`presets: { expo: true }\`, where the expo preset shadows ${PRESET_MODULES.expo.join(", ")}). ` : `expo ${expo} detected. Under the mock engine the expo preset shadows ${PRESET_MODULES.expo.join(", ")}; other Expo modules load their real JavaScript. `) + `Coming from jest-expo, run \`vitest-native migrate\`. See https://danfry1.github.io/vitest-native/guide/expo`);
605
665
  }
@@ -617,28 +677,44 @@ function runDoctor(root, nodeVersion = process.versions.node) {
617
677
  }
618
678
  lines.push("", "Config");
619
679
  const configFile = findConfigFile(configRoot);
680
+ let configSource = null;
620
681
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
621
682
  else {
622
683
  const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
684
+ configSource = content;
623
685
  const usage = analyzeConfigUsage(content);
624
686
  if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
625
687
  else if (usage.imports) warn(`${configFile} imports vitest-native but never calls reactNative() — the plugin is not in \`plugins: [...]\`, so React Native imports will not resolve.`);
626
688
  else if (extendsSharedConfig(content)) lines.push(` · ${configFile} builds on a shared config, so this cannot tell from here whether the plugin is wired up. Check the config it extends.`);
627
689
  else warn(`${configFile} exists but does not import vitest-native` + (content.includes("vitest-native") ? " (it is only mentioned in a comment)" : "") + " — add `reactNative()` to `plugins: [...]`, or run `vitest-native init`.");
628
690
  }
691
+ const advice = transformCacheAdvice(runningVitestVersion(rootFor("vitest")), configSource);
692
+ if (advice.length) {
693
+ lines.push("", "Transform cache");
694
+ for (const line of advice) lines.push(` · ${line}`);
695
+ }
629
696
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
630
697
  return {
631
698
  lines,
632
699
  ok
633
700
  };
634
701
  }
635
- //#endregion
636
- //#region src/cli/init.ts
702
+ // src/cli/init.ts
637
703
  /**
638
704
  * `vitest-native init` — write a ready-to-run Vitest config. Two shapes:
639
705
  * the zero-config default, and the jest-compat variant (the exact block the
640
706
  * migration guide documents, so docs and CLI can never drift apart by shape).
641
707
  */
708
+ /**
709
+ * Printed after `init` and `migrate`: the hot runtime is off by default, so a user
710
+ * reading only the CLI output would not otherwise learn it exists or what it costs.
711
+ */
712
+ const HOT_RUNTIME_NOTE = [
713
+ "Hot runtime: off by default. `hotRuntime: 'auto'` reuses workers across test files instead of",
714
+ "starting a fresh one per file. Whether that is faster depends on the suite, so measure it on yours.",
715
+ "It has known differences from per-file isolation:",
716
+ " https://danfry1.github.io/vitest-native/guide/troubleshooting#a-test-passes-on-its-own-but-fails-when-run-with-other-files"
717
+ ];
642
718
  const PLAIN_CONFIG = `import { defineConfig } from 'vitest/config'
643
719
  import { reactNative } from 'vitest-native'
644
720
 
@@ -672,11 +748,23 @@ export default defineConfig({
672
748
  },
673
749
  })
674
750
  `;
675
- function renderInitConfig(jestCompat) {
676
- return jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
751
+ /**
752
+ * The config source. Under Vite+ the config is `vite.config.ts` with `defineConfig`
753
+ * from 'vite-plus' (viteplus.dev/guide/test): the project does not install `vitest`
754
+ * itself, so a config importing 'vitest/config' fails to load under pnpm.
755
+ */
756
+ function renderInitConfig(jestCompat, vitePlus = false) {
757
+ const source = jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
758
+ return vitePlus ? source.replace("import { defineConfig } from 'vitest/config'", "import { defineConfig } from 'vite-plus'") : source;
677
759
  }
678
- function existingConfig(root) {
760
+ function existingConfig(root, vitePlus) {
679
761
  for (const name of [
762
+ ...vitePlus ? [
763
+ "vite.config.ts",
764
+ "vite.config.mts",
765
+ "vite.config.js",
766
+ "vite.config.mjs"
767
+ ] : [],
680
768
  "vitest.config.ts",
681
769
  "vitest.config.mts",
682
770
  "vitest.config.js",
@@ -688,18 +776,36 @@ function existingConfig(root) {
688
776
  }
689
777
  function runInit(root, opts = {}) {
690
778
  const lines = [];
691
- const existing = existingConfig(root);
779
+ const vitePlus = usesVitePlus(root);
780
+ const existing = existingConfig(root, vitePlus);
781
+ if (existing && vitePlus && existing.startsWith("vite.config")) return {
782
+ lines: [
783
+ `✗ ${existing} already exists. Vite+ keeps tests in the same config, so add`,
784
+ ` vitest-native to it rather than replacing it:`,
785
+ ``,
786
+ ` import { reactNative } from 'vitest-native'`,
787
+ ``,
788
+ ` export default defineConfig({`,
789
+ ` plugins: [reactNative()],`,
790
+ ` test: { environment: 'node' },`,
791
+ ` })`,
792
+ ``,
793
+ ` Then run: vp test`
794
+ ],
795
+ ok: false
796
+ };
692
797
  if (existing && !opts.force) return {
693
798
  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.`],
694
799
  ok: false
695
800
  };
696
- const file = fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
801
+ const file = vitePlus ? "vite.config.ts" : fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
697
802
  const target = path.join(root, file);
698
- fs.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false));
803
+ fs.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false, vitePlus));
699
804
  lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
700
805
  if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
701
- lines.push("", "Next steps:", ` 1. add a script: "test": "vitest"`, ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
806
+ lines.push("", "Next steps:", vitePlus ? ` 1. add a script: "test": "vp test"` : ` 1. add a script: "test": "vitest"`, vitePlus ? ` 2. run: vp test` : ` 2. run: npx vitest`, ` 3. check the environment: npx vitest-native doctor`);
702
807
  if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
808
+ lines.push("", ...HOT_RUNTIME_NOTE);
703
809
  return {
704
810
  lines,
705
811
  ok: true,
@@ -776,8 +882,7 @@ function tryExpand(source, literalDot) {
776
882
  throw error;
777
883
  }
778
884
  }
779
- //#endregion
780
- //#region src/cli/allowlist.ts
885
+ // src/cli/allowlist.ts
781
886
  /**
782
887
  * Reading Jest's `transformIgnorePatterns` allowlist,
783
888
  * `node_modules/(?!(a|b|@scope/c)/)`. Real ones nest — React Native's own preset
@@ -874,8 +979,7 @@ function allows(entry, pkg) {
874
979
  if (entry.kind === "scope") return pkg.startsWith(`${entry.name}/`);
875
980
  return pkg.startsWith(entry.name);
876
981
  }
877
- //#endregion
878
- //#region src/cli/jest-discovery.ts
982
+ // src/cli/jest-discovery.ts
879
983
  /**
880
984
  * Which files Jest treats as tests, said to Vitest.
881
985
  *
@@ -1238,8 +1342,7 @@ function booleanFlag(value) {
1238
1342
  if (value === true || value === "true") return true;
1239
1343
  if (value === "false") return false;
1240
1344
  }
1241
- //#endregion
1242
- //#region src/cli/untranspiled.ts
1345
+ // src/cli/untranspiled.ts
1243
1346
  /**
1244
1347
  * Evidence that a package needs `transform`: a `.js` file under one of its entry
1245
1348
  * points that is not standard JavaScript (JSX or Flow), which neither Node nor Vite
@@ -1347,8 +1450,7 @@ function untranspiledFile(root, pkg) {
1347
1450
  }
1348
1451
  return null;
1349
1452
  }
1350
- //#endregion
1351
- //#region src/cli/migrate.ts
1453
+ // src/cli/migrate.ts
1352
1454
  /**
1353
1455
  * `vitest-native migrate` — analyze a project's Jest configuration and report,
1354
1456
  * key by key, what maps automatically, what the presets already cover (delete
@@ -1658,7 +1760,7 @@ function analyzeJestConfig(root) {
1658
1760
  "c"
1659
1761
  ].includes(name)) continue;
1660
1762
  if (name === "forceExit") dropped.push("scripts.test --forceExit — `vitest run` exits by itself: if something keeps the process alive after the run it waits test.teardownTimeout, warns, and exits.");
1661
- else if (name === "ci") dropped.push(`scripts.test --ci — Vitest already refuses to write new snapshots when it detects CI.`);
1763
+ else if (name === "ci") dropped.push("scripts.test --ci — Vitest writes no new snapshots when it detects CI, as Jest's --ci defaults to; set CI=true to get that elsewhere.");
1662
1764
  else if ((name === "silent" || name === "passWithNoTests") && booleanFlag(value) !== void 0) {
1663
1765
  const on = booleanFlag(value);
1664
1766
  testEntries.push(`${name}: ${on}`);
@@ -1674,7 +1776,7 @@ function analyzeJestConfig(root) {
1674
1776
  const env = take("testEnvironment");
1675
1777
  if (env && env !== "node") attention.push(`testEnvironment: '${env}' — vitest-native suites run under 'node'; review.`);
1676
1778
  else handled.add("testEnvironment");
1677
- if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — configure per-suite with vi.useFakeTimers() (the jest-compat shim covers jest.useFakeTimers()).`);
1779
+ if (take("fakeTimers") !== void 0) attention.push(`fakeTimers — not carried over: call jest.useFakeTimers(options) in a beforeEach, which the jest-compat shim translates, or set Vitest's test.fakeTimers. Not at a setup file's top level: RNTL's import drops options set there.`);
1678
1780
  const discoveryOptions = {};
1679
1781
  for (const key of [
1680
1782
  "testMatch",
@@ -1779,14 +1881,14 @@ function analyzeJestConfig(root) {
1779
1881
  const at = e.indexOf(": ");
1780
1882
  return ` { find: ${e.slice(0, at)}, replacement: ${e.slice(at + 2)} },\n`;
1781
1883
  }).join("") + regexAliases.map((e) => ` ${e},\n`).join("") + ` ]` : `{ ${["...jestCompatAliases()", ...aliasEntries].join(", ")} }`;
1884
+ const vitePlus = usesVitePlus(root);
1782
1885
  return {
1783
1886
  source,
1784
1887
  automatic,
1785
1888
  attention,
1786
1889
  presetCovered,
1787
1890
  dropped,
1788
- suggestedConfig: `import { ${excludeGlobs.length ? "configDefaults, " : ""}defineConfig } from 'vitest/config'
1789
- import { reactNative } from 'vitest-native'
1891
+ suggestedConfig: `${vitePlus ? `import { defineConfig } from 'vite-plus'\n${excludeGlobs.length ? "import { configDefaults } from 'vite-plus/test/config'\n" : ""}` : `import { ${excludeGlobs.length ? "configDefaults, " : ""}defineConfig } from 'vitest/config'\n`}import { reactNative } from 'vitest-native'
1790
1892
  import { jestCompatAliases, jestCompatSetup, jestMockTransform } from 'vitest-native/jest-compat'
1791
1893
  ${needsUrlImport ? "import { fileURLToPath } from 'node:url'\n" : ""}${extraImports.map((i) => `${i}\n`).join("")}
1792
1894
  export default defineConfig({
@@ -1805,6 +1907,7 @@ export default defineConfig({
1805
1907
  },
1806
1908
  })
1807
1909
  `,
1910
+ vitePlus,
1808
1911
  ok: source !== null
1809
1912
  };
1810
1913
  }
@@ -1846,7 +1949,16 @@ function classifyAllowlist(root, entries, active, autoInlined, out) {
1846
1949
  if (groups.detected.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.detected)} — detected by the engine (React Native ecosystem), which compiles what Node cannot run; nothing to do.`);
1847
1950
  if (groups.absent.length) out.automatic.push(`transformIgnorePatterns allows ${list(groups.absent)} — not installed; nothing to do.`);
1848
1951
  }
1849
- function renderMigrationReport(report) {
1952
+ /** The commands to run once the suggested config is saved. */
1953
+ function migrationNextStep(report) {
1954
+ return report.vitePlus ? "npx vitest-native doctor && vp test" : "npx vitest-native doctor && npx vitest";
1955
+ }
1956
+ /**
1957
+ * The report `migrate` prints. With `write: true` (`migrate --write`) the config is about to
1958
+ * be saved, so the closing line does not ask for a re-run with --write; the CLI prints the
1959
+ * next step after the file is written.
1960
+ */
1961
+ function renderMigrationReport(report, { write = false } = {}) {
1850
1962
  const lines = [];
1851
1963
  if (!report.source) {
1852
1964
  lines.push("✗ no Jest configuration found (package.json#jest or jest.config.{js,cjs,json}).", " Starting fresh? Run `vitest-native init` instead.");
@@ -1863,13 +1975,13 @@ function renderMigrationReport(report) {
1863
1975
  section("Covered by presets — delete", report.presetCovered);
1864
1976
  section("Needs your attention", report.attention);
1865
1977
  section("Dropped (no equivalent needed)", report.dropped);
1866
- lines.push("Suggested vitest.config:", "");
1978
+ lines.push(report.vitePlus ? "Suggested vite.config:" : "Suggested vitest.config:", "");
1867
1979
  lines.push(...report.suggestedConfig.split("\n").map((l) => ` ${l}`));
1868
- lines.push("Re-run with --write to save this config, then: npx vitest-native doctor && npx vitest");
1980
+ if (!write) lines.push(`Re-run with --write to save this config, then: ${migrationNextStep(report)}`, "");
1981
+ lines.push(...HOT_RUNTIME_NOTE);
1869
1982
  return lines;
1870
1983
  }
1871
- //#endregion
1872
- //#region src/cli/index.ts
1984
+ // src/cli/index.ts
1873
1985
  /**
1874
1986
  * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
1875
1987
  * environment), `migrate` (analyze a Jest config and report the mapping).
@@ -1922,8 +2034,9 @@ function main(argv, log = console.log) {
1922
2034
  }
1923
2035
  case "migrate": {
1924
2036
  const report = analyzeJestConfig(root);
1925
- for (const line of renderMigrationReport(report)) log(line);
1926
- if (report.ok && has("--write")) {
2037
+ const write = has("--write");
2038
+ for (const line of renderMigrationReport(report, { write })) log(line);
2039
+ if (report.ok && write) {
1927
2040
  const init = runInit(root, { force: has("--force") });
1928
2041
  if (!init.ok) {
1929
2042
  for (const line of init.lines) log(line);
@@ -1931,7 +2044,7 @@ function main(argv, log = console.log) {
1931
2044
  }
1932
2045
  const target = path.join(root, init.wrote);
1933
2046
  fs.writeFileSync(target, report.suggestedConfig);
1934
- log(`✓ wrote ${init.wrote} from the analysis above.`);
2047
+ log(`✓ wrote ${init.wrote} from the analysis above. Next: ${migrationNextStep(report)}`);
1935
2048
  }
1936
2049
  return report.ok ? 0 : 1;
1937
2050
  }
@@ -1943,5 +2056,4 @@ function main(argv, log = console.log) {
1943
2056
  }
1944
2057
  const entry = process.argv[1] ? path.basename(process.argv[1]) : "";
1945
2058
  if (entry === "cli.mjs" || entry === "cli.cjs" || entry === "vitest-native") process.exit(main(process.argv.slice(2)));
1946
- //#endregion
1947
2059
  export { main };
@@ -0,0 +1,45 @@
1
+ export declare const CONTEXT_ENV: "VITEST_NATIVE_CONTEXT";
2
+ export declare const CONTEXT_VERSION: number;
3
+ /** Hand-set diagnostic switches that stay environment variables. */
4
+ export declare const ESCAPE_HATCHES: readonly string[];
5
+
6
+ export interface ProjectContextFields {
7
+ platform: "ios" | "android";
8
+ diagnostics: boolean;
9
+ projectRoot: string;
10
+ reactNativeVersion?: string;
11
+ transform?: string[];
12
+ sourceExts?: string[];
13
+ assetExts?: string[];
14
+ hotPreserveGlobals?: string[];
15
+ hotEsmGeneration?: boolean;
16
+ /** Coverage is on: Node-compiled project source carries an inline source map. */
17
+ sourceMaps?: boolean;
18
+ hotReleaseGenerations?: boolean;
19
+ registry?: string;
20
+ ownership?: Record<string, unknown>;
21
+ projectDirs?: string[];
22
+ requireAliases?: [string, string][];
23
+ requireAliasesSkipped?: string[];
24
+ presetNames?: string[];
25
+ presetConfig?: Record<string, Record<string, unknown>>;
26
+ presetExports?: Record<string, string[] | null>;
27
+ presetModules?: string[];
28
+ presetDisabled?: string[];
29
+ mocks?: unknown;
30
+ knownNativeModules?: string[];
31
+ nativeModuleSpecs?: Record<string, string[]>;
32
+ nativeModules?: "permissive";
33
+ /** The supported Expo SDKs, `[minimum, maximum]` (checkLoadedExpoSdk). */
34
+ expoSdks?: [number, number];
35
+ }
36
+
37
+ export declare function writeProjectContext(
38
+ fields: ProjectContextFields,
39
+ cacheRoot: string,
40
+ ): string;
41
+ export declare function ensureProjectContext(ref: string, fields: ProjectContextFields): string;
42
+ export declare function projectContext(ref?: string): Readonly<ProjectContextFields> | null;
43
+ export declare function requireProjectContext(ref?: string): Readonly<ProjectContextFields>;
44
+ export declare function markBootContext(ref?: string): void;
45
+ export declare function assertBootContext(ref?: string): void;