vitest-native 0.14.1 → 0.15.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2497 -270
  4. package/dist/context.d.mts +15 -0
  5. package/dist/context.mjs +39 -1
  6. package/dist/errors.d.mts +20 -1
  7. package/dist/helpers.cjs +22 -1
  8. package/dist/helpers.mjs +22 -1
  9. package/dist/{host-BAAAlSkO.mjs → host-BAMNg80P.mjs} +178 -101
  10. package/dist/{index-aNBCTfA5.d.mts → index-CrCsGULN.d.mts} +76 -2
  11. package/dist/index.d.mts +2 -1
  12. package/dist/index.mjs +624 -145
  13. package/dist/jest-compat/interop.mjs +1 -1
  14. package/dist/jest-compat/jest-object.mjs +3 -4
  15. package/dist/jest-compat/node-registry.mjs +791 -67
  16. package/dist/jest-compat/setup.mjs +4 -4
  17. package/dist/matchers.d.cts +0 -1
  18. package/dist/matchers.d.mts +0 -1
  19. package/dist/native/bounded-process.mjs +63 -5
  20. package/dist/native/bridge-client.mjs +133 -0
  21. package/dist/native/bridge-server.mjs +215 -0
  22. package/dist/native/bridge-thread.mjs +79 -0
  23. package/dist/native/bridge.mjs +512 -0
  24. package/dist/native/explain.mjs +1 -2
  25. package/dist/native/export-condition-recovery.mjs +20 -99
  26. package/dist/native/hooks.mjs +252 -127
  27. package/dist/native/jest-resolvers.mjs +94 -0
  28. package/dist/native/library-jest.mjs +346 -0
  29. package/dist/native/loader.mjs +155 -67
  30. package/dist/native/match.mjs +30 -1
  31. package/dist/native/module-reset.mjs +44 -49
  32. package/dist/native/ownership-ledger.d.mts +77 -0
  33. package/dist/native/ownership-ledger.mjs +467 -0
  34. package/dist/native/ownership.d.mts +5 -0
  35. package/dist/native/ownership.mjs +30 -0
  36. package/dist/native/registry-compiler.mjs +39 -5
  37. package/dist/native/registry-process.mjs +327 -28
  38. package/dist/native/registry.mjs +750 -200
  39. package/dist/native/resolve.mjs +91 -4
  40. package/dist/native/rntl-hooks.mjs +8 -5
  41. package/dist/native/rntl-text-host.mjs +5 -15
  42. package/dist/native/setup.mjs +117 -36
  43. package/dist/native/shared-resolver.d.mts +141 -0
  44. package/dist/native/shared-resolver.mjs +719 -0
  45. package/dist/native/transform.mjs +4 -5
  46. package/dist/native/worker.mjs +9 -4
  47. package/dist/node-dispatch.mjs +291 -0
  48. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  49. package/dist/{presets-CXDyg51l.mjs → presets-CsQynQ0A.mjs} +620 -78
  50. package/dist/presets.d.mts +1 -1
  51. package/dist/presets.mjs +1 -1
  52. package/dist/rntl-matchers.d.ts +11 -15
  53. package/dist/rntl-support.mjs +27 -13
  54. package/dist/setup.mjs +4 -4
  55. package/docs/migrating-from-jest.md +9 -232
  56. package/docs/migrating-from-vitest-react-native.md +4 -4
  57. package/docs/release-readiness.md +9 -11
  58. package/docs/versioning.md +38 -9
  59. package/package.json +33 -13
package/dist/cli.mjs CHANGED
@@ -1,14 +1,18 @@
1
1
  #!/usr/bin/env node
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-BAAAlSkO.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";
2
+ import { C as validatePeerDependency, b as unsupportedExpoSdkMessage, c as detectEcosystemPackages, d as detectEngine, f as SUPPORTED_NODE, g as PEER_REQUIREMENTS, h as unsupportedNodeMessage, i as ownVitestPackage, l as babelParser, m as satisfiesNodeRange, o as usesVitePlus, r as installedViteVersion, u as isPlainJavaScript, v as installedExpoVersion, x as unsupportedReactNativeMessage, y as isBelowSupportedReactNative } from "./host-BAMNg80P.mjs";
3
+ import { a as PRESET_MODULES, f as presetShadowing, i as LIBRARY_SETUP_FILES, m as testsItself, r as DEFAULT_ASSET_EXTS, s as autoDetectedPresetApplies, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
4
4
  import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-Couw0Esx.mjs";
5
5
  import { createRequire } from "node:module";
6
- import { fileURLToPath } from "node:url";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
7
  import path from "node:path";
8
8
  import fs from "node:fs";
9
+ import os from "node:os";
10
+ import { VitestNativeError } from "./errors.mjs";
9
11
  import { createNativeOwnershipPolicy, formatNativeOwnershipManifest } from "./native/ownership.mjs";
10
12
  import { resolveTransformPreset } from "./native/babel-preset.mjs";
11
13
  import { HOT_STATE_MANIFEST_ENTRIES } from "./native/state-manifest.mjs";
14
+ import { isDeepStrictEqual } from "node:util";
15
+ import { spawn, spawnSync } from "node:child_process";
12
16
  // src/cli/manifest.ts
13
17
  /**
14
18
  * Installed-package facts for the CLI, read from disk.
@@ -333,11 +337,6 @@ function classifyBabelPlugins(report, root, active) {
333
337
  };
334
338
  });
335
339
  }
336
- /** The installed major version of `vite`, or null. */
337
- function viteMajor(root) {
338
- const major = Number(installedViteVersion(root)?.replace(/^[^0-9]*/, "").split(".")[0]);
339
- return Number.isFinite(major) ? major : installedMajor(root, "vite");
340
- }
341
340
  /** Whether `name` is installed where the project resolves it. */
342
341
  function installed(root, name) {
343
342
  return installedManifest(root, name) !== null;
@@ -347,14 +346,11 @@ function pluginListSource(plugins) {
347
346
  return `[${plugins.map((p) => p.options === void 0 ? JSON.stringify(p.written) : `[${JSON.stringify(p.written)}, ${JSON.stringify(p.options)}]`).join(", ")}]`;
348
347
  }
349
348
  /**
350
- * How to run Babel plugins per Vite major. @vitejs/plugin-react 6 (Vite 8) dropped
351
- * Babel and points at @rolldown/plugin-babel; on Vite 7 and earlier its `babel`
352
- * option adds plugins.
349
+ * How to run Babel plugins: @vitejs/plugin-react 6 (Vite 8) dropped Babel and points at
350
+ * @rolldown/plugin-babel.
353
351
  */
354
- function babelRecipe(major, plugins) {
355
- const list = pluginListSource(plugins);
356
- if (major !== null && major < 8) return `install @vitejs/plugin-react and @babel/core, then add \`react({ babel: { plugins: ${list} } })\` (import react from '@vitejs/plugin-react') to plugins`;
357
- return `install @rolldown/plugin-babel and @babel/core, then add \`babel({ plugins: ${list} })\` (import babel from '@rolldown/plugin-babel') to plugins`;
352
+ function babelRecipe(plugins) {
353
+ return `install @rolldown/plugin-babel and @babel/core, then add \`babel({ plugins: ${pluginListSource(plugins)} })\` (import babel from '@rolldown/plugin-babel') to plugins`;
358
354
  }
359
355
  /** Whether a plugin's options are plain data (JSON.stringify drops functions silently). */
360
356
  function serializableOptions(entry) {
@@ -376,6 +372,13 @@ function serializableOptions(entry) {
376
372
  * engine resolution (and why), detected presets, RNTL/Node compatibility, and
377
373
  * config presence. Read-only; never mutates the project.
378
374
  */
375
+ /**
376
+ * The Vitest that runs here, as the peer check reports it: the project's own, or under
377
+ * Vite+ the copy this package loads.
378
+ */
379
+ function runningVitestVersion(from) {
380
+ return packageVersion(from, "vitest") ?? (usesVitePlus(from) ? ownVitestPackage()?.version ?? null : null);
381
+ }
379
382
  function packageVersion(root, name) {
380
383
  try {
381
384
  return createRequire(path.join(root, "package.json"))(`${name}/package.json`).version ?? null;
@@ -384,12 +387,11 @@ function packageVersion(root, name) {
384
387
  }
385
388
  }
386
389
  /**
387
- * The supported Node versions, as this package's own `engines.node` states them.
388
- * Single source: the manifest is what a package manager enforces at install time, so a
389
- * diagnostic must not carry its own copy of the range.
390
+ * The supported Node range: SUPPORTED_NODE, the constant the plugin enforces at startup,
391
+ * which a test holds equal to `engines.node` (what a package manager enforces).
390
392
  */
391
393
  function nodeRange() {
392
- const fallback = ">=22.13.0 <23 || >=24.3.0";
394
+ const fallback = SUPPORTED_NODE;
393
395
  for (let dir = path.dirname(fileURLToPath(import.meta.url));; dir = path.dirname(dir)) {
394
396
  const manifest = readManifest(path.join(dir, "package.json"));
395
397
  if (manifest?.name === "vitest-native") return manifest.engines?.node?.trim() || fallback;
@@ -404,37 +406,6 @@ function readManifest(file) {
404
406
  return null;
405
407
  }
406
408
  }
407
- const versionParts = (version) => {
408
- const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
409
- return [
410
- major,
411
- minor,
412
- patch
413
- ];
414
- };
415
- const compareVersions = (a, b) => {
416
- const [x, y] = [versionParts(a), versionParts(b)];
417
- return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
418
- };
419
- /**
420
- * Whether `version` is in `range`: `||`-separated sets of space-separated comparators
421
- * (`>=`, `>`, `<=`, `<`, `=`), the forms `engines.node` uses. A version missing parts
422
- * reads them as 0 (`<23` is `<23.0.0`).
423
- */
424
- function satisfiesNodeRange(version, range) {
425
- return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
426
- const match = /^(>=|<=|>|<|=)?\s*v?(\d[\w.-]*)$/.exec(comparator);
427
- if (!match) return false;
428
- const order = compareVersions(version, match[2]);
429
- switch (match[1] ?? "=") {
430
- case ">=": return order >= 0;
431
- case ">": return order > 0;
432
- case "<=": return order <= 0;
433
- case "<": return order < 0;
434
- default: return order === 0;
435
- }
436
- }));
437
- }
438
409
  /**
439
410
  * In Vitest's own precedence order: a `vitest.config.*` wins, and `vite.config.*`
440
411
  * is used when there is none.
@@ -464,77 +435,16 @@ function findConfigFile(root) {
464
435
  return null;
465
436
  }
466
437
  /** Source with comments removed, so a mention inside one cannot be mistaken for use. */
467
- function withoutComments(source) {
438
+ function withoutComments$1(source) {
468
439
  return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/[^\n]*/g, "$1");
469
440
  }
470
- const settingOf = (value) => value === void 0 ? null : value === "false" ? "off" : "set";
471
- /**
472
- * How a config sets Vitest's `fsModuleCache`, read as text, in each spelling: inside
473
- * `experimental: { ... }` (Vitest 4.0.11 and later) and anywhere else (the top-level
474
- * option, Vitest 5). `off` for a literal `false`, `set` for any other value, null when
475
- * that spelling is absent.
476
- */
477
- function fsModuleCacheSetting(source) {
478
- const code = withoutComments(source);
479
- const nested = /\bexperimental\s*:\s*\{[^{}]*?\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(code);
480
- const rest = nested ? code.replace(nested[0], " ") : code;
481
- const top = /\bfsModuleCache\s*:\s*([^,}\s]*)/.exec(rest);
482
- return {
483
- experimental: settingOf(nested?.[1]),
484
- topLevel: settingOf(top?.[1])
485
- };
486
- }
487
- /** Whether `version` is at or above `[major, minor, patch]`. */
488
- function versionAtLeast(version, floor) {
489
- const parts = version.replace(/^[^0-9]*/, "").split(/[.-]/).slice(0, 3).map(Number);
490
- for (let i = 0; i < 3; i++) {
491
- const part = parts[i] ?? 0;
492
- if (part !== floor[i]) return part > floor[i];
493
- }
494
- return true;
495
- }
496
- /** The first Vitest with `experimental.fsModuleCache`. */
497
- const EXPERIMENTAL_FS_MODULE_CACHE_FROM = [
498
- 4,
499
- 0,
500
- 11
501
- ];
502
- const TROUBLESHOOTING_STALE_IMPORT = "https://danfry1.github.io/vitest-native/guide/troubleshooting#cannot-find-module-keeps-failing-after-the-missing-file-exists";
503
- /**
504
- * The transform-cache note for a Vitest the plugin does not turn the cache on for.
505
- * Empty where it does (fsModuleCacheOnByDefault, which the plugin reads too), and where
506
- * the config turns the cache off on purpose.
507
- */
508
- function transformCacheAdvice(vitestVersion, configSource) {
509
- const major = Number(vitestVersion?.replace(/^[^0-9]*/, "").split(".")[0]);
510
- if (!vitestVersion || !(major >= 4) || fsModuleCacheOnByDefault(major)) return [];
511
- const setting = configSource === null ? {
512
- experimental: null,
513
- topLevel: null
514
- } : fsModuleCacheSetting(configSource);
515
- if (setting.experimental === "off") return [];
516
- const hasOption = versionAtLeast(vitestVersion, EXPERIMENTAL_FS_MODULE_CACHE_FROM);
517
- 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.`;
518
- 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}`];
519
- 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.`];
520
- if (setting.topLevel !== null) lines.push("The config sets `test.fsModuleCache`, the Vitest 5 spelling, which has no effect on Vitest 4.");
521
- 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.`);
522
- return lines;
523
- }
524
- /**
525
- * The Vitest that runs here, as the peer check reports it: the project's own, or under
526
- * Vite+ the copy this package loads.
527
- */
528
- function runningVitestVersion(from) {
529
- return packageVersion(from, "vitest") ?? (usesVitePlus(from) ? ownVitestPackage()?.version ?? null : null);
530
- }
531
441
  /**
532
442
  * Whether a config is built on one imported from elsewhere — a shared preset in a
533
443
  * workspace, typically. Such a file legitimately never mentions vitest-native, and
534
444
  * reporting it as unconfigured is a false alarm on a working project.
535
445
  */
536
446
  function extendsSharedConfig(source) {
537
- const code = withoutComments(source);
447
+ const code = withoutComments$1(source);
538
448
  const imports = [...code.matchAll(/import\s+([^;]+?)\s+from\s*["']([^"'.][^"']*)["']/g)];
539
449
  for (const [, clause, specifier] of imports) {
540
450
  if (specifier === "vitest" || specifier.startsWith("vitest/")) continue;
@@ -562,7 +472,7 @@ function extendsSharedConfig(source) {
562
472
  * working project.
563
473
  */
564
474
  function analyzeConfigUsage(source) {
565
- const code = withoutComments(source);
475
+ const code = withoutComments$1(source);
566
476
  const named = /import\s*\{([^}]*)\}\s*from\s*["']vitest-native["']/.exec(code);
567
477
  const namespaced = /import\s*\*\s*as\s*([A-Za-z_$][\w$]*)\s*from\s*["']vitest-native["']/.exec(code);
568
478
  const required = /(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*["']vitest-native["']\s*\)/.exec(code);
@@ -625,6 +535,8 @@ function resolutionRoot(start, exists = fs.existsSync) {
625
535
  dir = parent;
626
536
  }
627
537
  }
538
+ /** doctor's warning for Node 24.13.0, which troubleshooting.md explains. */
539
+ const NODE_24_13_0_CRASH = "Node 24.13.0 can crash a test run at startup with a segmentation fault (an intermittent V8 garbage-collection crash on worker threads). Use another Node 24 release, such as 24.14 or later. See https://danfry1.github.io/vitest-native/guide/troubleshooting#node-24-13-0-segmentation-fault-at-startup";
628
540
  function runDoctor(root, nodeVersion = process.versions.node) {
629
541
  const lines = [];
630
542
  let ok = true;
@@ -640,14 +552,16 @@ function runDoctor(root, nodeVersion = process.versions.node) {
640
552
  lines.push(`vitest-native doctor — ${root}`);
641
553
  lines.push("", "Runtime");
642
554
  const range = nodeRange();
643
- if (satisfiesNodeRange(nodeVersion, range)) pass(`Node ${nodeVersion} (supported: ${range})`);
644
- else fail(`Node ${nodeVersion} — vitest-native supports Node ${range}.`);
555
+ if (satisfiesNodeRange(nodeVersion, range)) {
556
+ pass(`Node ${nodeVersion} (supported: ${range})`);
557
+ if (nodeVersion === "24.13.0") warn(NODE_24_13_0_CRASH);
558
+ } else fail(unsupportedNodeMessage(nodeVersion));
645
559
  lines.push("", "Peer dependencies");
646
- for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
560
+ for (const { name, minimum, maximumMajor, optional } of PEER_REQUIREMENTS) {
647
561
  if (optional) continue;
648
562
  const from = rootFor(name);
649
563
  const running = name === "vite" ? installedViteVersion(from) : name === "vitest" ? runningVitestVersion(from) : null;
650
- const error = validatePeerDependency(name, minimum, from, maximumMajor, minimumByMajor, running);
564
+ const error = validatePeerDependency(name, minimum, from, maximumMajor, running);
651
565
  if (error) fail(error);
652
566
  else {
653
567
  pass(`${name} ${running ?? packageVersion(from, name)}`);
@@ -659,8 +573,12 @@ function runDoctor(root, nodeVersion = process.versions.node) {
659
573
  const decision = detectEngine("auto", rootFor("@react-native/babel-preset"));
660
574
  const transformPreset = resolveTransformPreset(rootFor("@react-native/babel-preset"));
661
575
  const presetLabel = transformPreset ? `${transformPreset.name} ${transformPreset.version}` : "a React Native Babel preset";
662
- if (decision.engine === "native") pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with ${presetLabel} + @babel/core present.`);
663
- else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but no React Native Babel preset (@react-native/babel-preset, or Expo's from SDK 56) and/or @babel/core resolve. Install both as devDependencies to run the real-RN native engine.`);
576
+ if (decision.engine === "native") {
577
+ pass(`engine 'auto' resolves to NATIVE — real React Native${rnVersion ? ` ${rnVersion}` : ""} with ${presetLabel} + @babel/core present.`);
578
+ const rnProblem = rnVersion && unsupportedReactNativeMessage(rnVersion);
579
+ if (rnProblem && isBelowSupportedReactNative(rnVersion)) fail(rnProblem);
580
+ else if (rnProblem) warn(rnProblem);
581
+ } else if (rnVersion) warn(`engine 'auto' resolves to MOCK: react-native ${rnVersion} is installed but no React Native Babel preset (@react-native/babel-preset, or Expo's from SDK 56) and/or @babel/core resolve. Install both as devDependencies to run the real-RN native engine.`);
664
582
  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.");
665
583
  if (decision.engine === "native") {
666
584
  const inferredRoot = configRoot;
@@ -688,9 +606,8 @@ function runDoctor(root, nodeVersion = process.versions.node) {
688
606
  else {
689
607
  const rntlMajor = Number(rntl.split(".")[0]);
690
608
  const rntlReq = PEER_REQUIREMENTS.find((r) => r.name === "@testing-library/react-native");
691
- const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor, rntlReq.minimumByMajor);
609
+ const rntlError = rntlReq && validatePeerDependency(rntlReq.name, rntlReq.minimum, root, rntlReq.maximumMajor);
692
610
  if (rntlError) warn(rntlError);
693
- else if (rntlMajor >= 14 && !satisfiesNodeRange(nodeVersion, ">=22.13.0")) fail(`@testing-library/react-native ${rntl} requires Node >= 22.13, but this is Node ${nodeVersion}. Upgrade Node or pin @testing-library/react-native@13.`);
694
611
  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`);
695
612
  else pass(`@testing-library/react-native ${rntl}${rntlMajor >= 14 ? " (14 is async: await render/fireEvent)" : ""}`);
696
613
  }
@@ -701,8 +618,10 @@ function runDoctor(root, nodeVersion = process.versions.node) {
701
618
  if (!installedManifest(root, pkg)) continue;
702
619
  installedAny = true;
703
620
  if (installedTestsItself(root, pkg)) lines.push(` · ${pkg} ${installedMajor(root, pkg)} runs its own test mode under Vitest, so no preset replaces it`);
704
- else if (!autoDetectedPresetApplies(preset, decision.engine)) lines.push(` · ${pkg} runs as itself under the native engine, on its native-module mocks; the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``);
705
- else detected.push(`${pkg} → ${preset}`);
621
+ else if (!autoDetectedPresetApplies(preset, decision.engine)) {
622
+ const setupFile = LIBRARY_SETUP_FILES[preset];
623
+ lines.push(` · ${pkg} runs as itself under the native engine, ` + (setupFile ? `with its own Jest setup (${setupFile}); ` : `on its native-module mocks; `) + `the ${preset} preset applies under the mock engine or with \`presets: { ${preset}: true }\``);
624
+ } else detected.push(`${pkg} → ${preset}`);
706
625
  }
707
626
  if (detected.length) for (const d of detected) pass(d);
708
627
  else if (!installedAny) lines.push(" (none — no preset-covered packages installed)");
@@ -720,7 +639,7 @@ function runDoctor(root, nodeVersion = process.versions.node) {
720
639
  lines.push("", "Babel");
721
640
  const classified = classifyBabelPlugins(babel, root, activePresets(root, [], decision.engine));
722
641
  const required = classified.filter((p) => p.verdict === "required");
723
- for (const p of classified) if (p.verdict === "required") warn(`${p.reason} Required: ${babelRecipe(viteMajor(rootFor("vite")), required)}.`);
642
+ for (const p of classified) if (p.verdict === "required") warn(`${p.reason} Required: ${babelRecipe(required)}.`);
724
643
  else if (p.verdict === "alias") warn(`${p.reason} \`vitest-native migrate\` writes them; otherwise add them to resolve.alias.`);
725
644
  else if (p.verdict === "unknown") warn(p.reason);
726
645
  else lines.push(` · ${p.written}: ${p.reason}`);
@@ -729,22 +648,21 @@ function runDoctor(root, nodeVersion = process.versions.node) {
729
648
  }
730
649
  lines.push("", "Config");
731
650
  const configFile = findConfigFile(configRoot);
732
- let configSource = null;
733
651
  if (!configFile) warn("no vitest.config.* found — run `vitest-native init` to create one.");
734
652
  else {
735
653
  const content = fs.readFileSync(path.join(configRoot, configFile), "utf8");
736
- configSource = content;
737
654
  const usage = analyzeConfigUsage(content);
738
- if (usage.imports && usage.invokes) pass(`${configFile} uses vitest-native.`);
739
- 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.`);
655
+ if (usage.imports && usage.invokes) {
656
+ pass(`${configFile} uses vitest-native.`);
657
+ const model = /\bownershipModel\s*:\s*["'](resolver|resolution)["']/.exec(withoutComments$1(content))?.[1];
658
+ if (model) {
659
+ lines.push(` · experimental.ownershipModel: '${model}' is on: Vite and Node's loaders resolve bare imports through one shared resolver (https://danfry1.github.io/vitest-native/guide/plugin-options#experimental).`);
660
+ if (model === "resolution") lines.push(" · 'resolution' turns on experimental.nodeMocks: a vi.mock also reaches the modules Node loads, and a mock Node cannot have synchronously fails as MOCK_NOT_SEEN_BY_NODE.");
661
+ }
662
+ } 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.`);
740
663
  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.`);
741
664
  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`.");
742
665
  }
743
- const advice = transformCacheAdvice(runningVitestVersion(rootFor("vitest")), configSource);
744
- if (advice.length) {
745
- lines.push("", "Transform cache");
746
- for (const line of advice) lines.push(` · ${line}`);
747
- }
748
666
  lines.push("", ok ? "✓ No blocking problems found." : "✗ Blocking problems found (see ✗ above).");
749
667
  return {
750
668
  lines,
@@ -809,22 +727,53 @@ function renderInitConfig(jestCompat, vitePlus = false) {
809
727
  const source = jestCompat ? JEST_COMPAT_CONFIG : PLAIN_CONFIG;
810
728
  return vitePlus ? source.replace("import { defineConfig } from 'vitest/config'", "import { defineConfig } from 'vite-plus'") : source;
811
729
  }
730
+ /**
731
+ * Vitest's config file names, in the order it looks them up (CONFIG_NAMES and
732
+ * CONFIG_EXTENSIONS in vitest/dist/chunks/constants): the first that exists is the one
733
+ * it loads, every vitest.config.* before any vite.config.*, and it does not merge the two.
734
+ */
735
+ const CONFIG_EXTENSIONS = [
736
+ ".ts",
737
+ ".mts",
738
+ ".cts",
739
+ ".js",
740
+ ".mjs",
741
+ ".cjs"
742
+ ];
743
+ const VITEST_CONFIG_FILES = CONFIG_EXTENSIONS.map((ext) => `vitest.config${ext}`);
744
+ const VITE_CONFIG_FILES = CONFIG_EXTENSIONS.map((ext) => `vite.config${ext}`);
745
+ function firstExisting(root, names) {
746
+ return names.find((name) => fs.existsSync(path.join(root, name))) ?? null;
747
+ }
748
+ /**
749
+ * The config Vitest would load from `root`, or null when there is none to replace. A
750
+ * vite.config.* counts only under Vite+, which keeps tests in it; elsewhere a new
751
+ * vitest.config.* goes beside it, and the takeover is reported.
752
+ */
812
753
  function existingConfig(root, vitePlus) {
813
- for (const name of [
814
- ...vitePlus ? [
815
- "vite.config.ts",
816
- "vite.config.mts",
817
- "vite.config.js",
818
- "vite.config.mjs"
819
- ] : [],
820
- "vitest.config.ts",
821
- "vitest.config.mts",
822
- "vitest.config.js",
823
- "vitest.config.mjs",
824
- "vitest.config.cts",
825
- "vitest.config.cjs"
826
- ]) if (fs.existsSync(path.join(root, name))) return name;
827
- return null;
754
+ return firstExisting(root, [...VITEST_CONFIG_FILES, ...vitePlus ? VITE_CONFIG_FILES : []]);
755
+ }
756
+ /**
757
+ * Printed when a new vitest.config.* takes over from a vite.config.* Vitest was reading:
758
+ * from then on, that file's plugins, `resolve` options and aliases no longer reach tests.
759
+ */
760
+ function viteConfigTakeoverNotice(viteConfig, written) {
761
+ const specifier = `./${viteConfig.replace(/\.[cm]?[jt]s$/, "")}`;
762
+ return [
763
+ `! Vitest now loads ${written} instead of ${viteConfig}: it reads a vite.config.* only when`,
764
+ ` there is no vitest.config.*, and does not merge the two. Plugins, \`resolve\` options and`,
765
+ ` aliases in ${viteConfig} no longer apply to tests. If tests need them, extend it in ${written}:`,
766
+ ``,
767
+ ` import { defineConfig, mergeConfig } from 'vitest/config'`,
768
+ ` import viteConfig from '${specifier}'`,
769
+ ``,
770
+ ` export default mergeConfig(viteConfig, defineConfig({ /* the settings this file has now */ }))`,
771
+ ``,
772
+ ` If ${viteConfig} exports a function, call it:`,
773
+ ` defineConfig((env) => mergeConfig(viteConfig(env), { /* ... */ }))`,
774
+ ``,
775
+ ` or copy over the settings tests need.`
776
+ ];
828
777
  }
829
778
  function runInit(root, opts = {}) {
830
779
  const lines = [];
@@ -846,22 +795,28 @@ function runInit(root, opts = {}) {
846
795
  ],
847
796
  ok: false
848
797
  };
798
+ if (existing && /\.c[jt]s$/.test(existing)) return {
799
+ lines: [`✗ ${existing} is a CommonJS config. vitest-native writes ES module configs and does not`, ` rewrite a CommonJS one; remove or rename ${existing}, then re-run.`],
800
+ ok: false
801
+ };
849
802
  if (existing && !opts.force) return {
850
803
  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.`],
851
804
  ok: false
852
805
  };
853
- const file = vitePlus ? "vite.config.ts" : fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs";
806
+ const file = existing ?? (vitePlus ? "vite.config.ts" : fs.existsSync(path.join(root, "tsconfig.json")) ? "vitest.config.mts" : "vitest.config.mjs");
807
+ const viteConfig = existing ? null : firstExisting(root, VITE_CONFIG_FILES);
854
808
  const target = path.join(root, file);
855
809
  fs.writeFileSync(target, renderInitConfig(opts.jestCompat ?? false, vitePlus));
856
- lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`);
857
- if (existing && opts.force) lines.push(` (replaced ${existing === file ? "it" : existing})`);
810
+ const notices = [...existing ? [` (replaced the existing ${existing}, the config Vitest loads)`] : [], ...viteConfig ? ["", ...viteConfigTakeoverNotice(viteConfig, file)] : []];
811
+ lines.push(`✓ wrote ${file}${opts.jestCompat ? " (jest-compat variant)" : ""}`, ...notices);
858
812
  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`);
859
813
  if (opts.jestCompat) lines.push(` 4. migrating a Jest suite? \`vitest-native migrate\` maps your jest.config onto this file.`);
860
814
  lines.push("", ...HOT_RUNTIME_NOTE);
861
815
  return {
862
816
  lines,
863
817
  ok: true,
864
- wrote: file
818
+ wrote: file,
819
+ notices
865
820
  };
866
821
  }
867
822
  const MAX_EXPANSIONS = 256;
@@ -984,7 +939,7 @@ function topLevelAlternatives(body) {
984
939
  const NAME = /^(@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/i;
985
940
  const SCOPE = /^@[a-z0-9~-][a-z0-9._~-]*$/i;
986
941
  const PREFIX = /^(@[a-z0-9~-][a-z0-9._~-]*(\/[a-z0-9._~-]*)?|[a-z0-9~-][a-z0-9._~-]*)$/i;
987
- function classify(expansion) {
942
+ function classify$1(expansion) {
988
943
  const trimmed = expansion.replace(new RegExp(`/$`), "/");
989
944
  if (trimmed.includes("\0")) return null;
990
945
  if (trimmed.endsWith("/")) {
@@ -1013,7 +968,7 @@ function extractAllowlistPackages(pattern) {
1013
968
  const entries = [];
1014
969
  const unparseable = [];
1015
970
  for (const alternative of topLevelAlternatives(body)) {
1016
- const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify);
971
+ const classified = tryExpand(alternative, true)?.filter((e) => !e.startsWith(".")).map(classify$1);
1017
972
  if (!classified || classified.some((c) => c === null)) {
1018
973
  unparseable.push(alternative);
1019
974
  continue;
@@ -1137,11 +1092,12 @@ function loadJestPreset(root, preset) {
1137
1092
  * against root-relative paths. So `<rootDir>/x` anchors at the root, anything else may
1138
1093
  * start mid-segment (`bskylink/.*` also ignores `notbskylink/`, hence `**\/*`), `/.*\/`
1139
1094
  * spans whole segments (`*\/**`), a trailing `/`, `/.*` or `.*` leaves the rest free,
1140
- * a pattern ending mid-segment covers a file and a directory, and `$` is left for a human.
1095
+ * a pattern ending mid-segment covers a file and a directory, and a `$`-anchored literal
1096
+ * (`\\.d\\.ts$`) becomes one file glob only when `directories` shows it prunes no directory.
1141
1097
  * Jest substitutes `<rootDir>` unescaped; it is read here as the directory it names.
1142
1098
  * A match starting above the root has no relative form and is not attempted.
1143
1099
  */
1144
- function ignorePatternToGlobs(pattern) {
1100
+ function ignorePatternToGlobs(pattern, directories) {
1145
1101
  let rest = pattern;
1146
1102
  let anchored = false;
1147
1103
  if (rest.startsWith("<rootDir>")) {
@@ -1155,13 +1111,13 @@ function ignorePatternToGlobs(pattern) {
1155
1111
  if (!expansions) return null;
1156
1112
  const globs = [];
1157
1113
  for (const expansion of expansions) {
1158
- const converted = expansionToGlobs(expansion, anchored, endAnchored);
1114
+ const converted = expansionToGlobs(expansion, anchored, endAnchored, directories);
1159
1115
  if (!converted) return null;
1160
1116
  globs.push(...converted);
1161
1117
  }
1162
1118
  return [...new Set(globs)];
1163
1119
  }
1164
- function expansionToGlobs(expansion, anchored, endAnchored) {
1120
+ function expansionToGlobs(expansion, anchored, endAnchored, directories) {
1165
1121
  let s = expansion;
1166
1122
  if (/[*?[\]{}()!\\]/.test(s.replaceAll("\0", ""))) return null;
1167
1123
  if (s.endsWith("\0")) {
@@ -1170,7 +1126,12 @@ function expansionToGlobs(expansion, anchored, endAnchored) {
1170
1126
  }
1171
1127
  if (!anchored) s = s.replace(new RegExp(`^+`), "");
1172
1128
  if (s === "" || anchored && s.startsWith(`/`)) return null;
1173
- if (endAnchored) return s.endsWith("/") ? [] : null;
1129
+ if (endAnchored) {
1130
+ if (s.endsWith("/")) return [];
1131
+ if (!directories || s.includes("\0")) return null;
1132
+ if ((typeof directories === "function" ? directories() : directories).some((dir) => anchored ? `/${dir}` === s : `/${dir}`.endsWith(s))) return null;
1133
+ return [anchored ? s.slice(1) : s.startsWith("/") ? `**/${s.slice(1)}` : `**/*${s}`];
1134
+ }
1174
1135
  const parts = s.split(`//`);
1175
1136
  if (parts.some((part) => part.includes("\0") || part === "")) return null;
1176
1137
  let glob = parts.join("/*/**/");
@@ -1208,7 +1169,7 @@ function extensionExclude(moduleFileExtensions) {
1208
1169
  * config (null when none). Merged as `setupPreset` does — the user's keys win,
1209
1170
  * `modulePathIgnorePatterns` concatenates — and defaulted as `normalize` does.
1210
1171
  */
1211
- function translateDiscovery(options, preset, major) {
1172
+ function translateDiscovery(options, preset, major, directories) {
1212
1173
  const defaults = JEST_DEFAULTS[major ?? 30];
1213
1174
  const automatic = [];
1214
1175
  const attention = [];
@@ -1277,7 +1238,7 @@ function translateDiscovery(options, preset, major) {
1277
1238
  const extra = key === "modulePathIgnorePatterns" ? " Jest also hid these paths from module resolution; Vite has no equivalent, which only matters if a test imported a module from one." : "";
1278
1239
  for (const pattern of patterns) {
1279
1240
  if (pattern === "/node_modules/") continue;
1280
- const globs = ignorePatternToGlobs(pattern);
1241
+ const globs = ignorePatternToGlobs(pattern, directories);
1281
1242
  if (globs) {
1282
1243
  exclude.push(...globs);
1283
1244
  automatic.push(`${key} '${pattern}' → test.exclude ${JSON.stringify(globs)}.${extra}`);
@@ -1297,7 +1258,7 @@ function translateDiscovery(options, preset, major) {
1297
1258
  };
1298
1259
  }
1299
1260
  /** Jest CLI flags that take a value (https://jestjs.io/docs/cli). */
1300
- const VALUED_FLAGS = /* @__PURE__ */ new Set([
1261
+ const VALUED_FLAGS$1 = /* @__PURE__ */ new Set([
1301
1262
  "testTimeout",
1302
1263
  "maxWorkers",
1303
1264
  "w",
@@ -1377,7 +1338,7 @@ function parseJestScript(script, command) {
1377
1338
  const [rawName, inline] = token.replace(/^--?/, "").split(/=(.*)/s, 2);
1378
1339
  const name = rawName.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1379
1340
  if (inline !== void 0) flags.set(name, inline);
1380
- else if (VALUED_FLAGS.has(name) && args[i + 1] !== void 0) flags.set(name, args[++i]);
1341
+ else if (VALUED_FLAGS$1.has(name) && args[i + 1] !== void 0) flags.set(name, args[++i]);
1381
1342
  else if (name === "bail" && /^\d+$/.test(args[i + 1] ?? "")) flags.set(name, args[++i]);
1382
1343
  else flags.set(name, true);
1383
1344
  }
@@ -1394,6 +1355,252 @@ function booleanFlag(value) {
1394
1355
  if (value === true || value === "true") return true;
1395
1356
  if (value === "false") return false;
1396
1357
  }
1358
+ /**
1359
+ * The project's directories, root-relative with `/`, as Vitest walks them: outside
1360
+ * node_modules and .git (configDefaults.exclude). A symlink to a directory is listed
1361
+ * (tinyglobby follows it) but not walked into.
1362
+ */
1363
+ function projectDirectories(root) {
1364
+ const dirs = [];
1365
+ const entries = (rel) => {
1366
+ try {
1367
+ return fs.readdirSync(path.join(root, rel), { withFileTypes: true });
1368
+ } catch {
1369
+ return [];
1370
+ }
1371
+ };
1372
+ const linksToDirectory = (file) => {
1373
+ try {
1374
+ return fs.statSync(file).isDirectory();
1375
+ } catch {
1376
+ return false;
1377
+ }
1378
+ };
1379
+ const walk = (rel) => {
1380
+ for (const entry of entries(rel)) {
1381
+ if (entry.name === "node_modules" || entry.name === ".git") continue;
1382
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
1383
+ if (entry.isDirectory()) {
1384
+ dirs.push(child);
1385
+ walk(child);
1386
+ } else if (entry.isSymbolicLink() && linksToDirectory(path.join(root, child))) dirs.push(child);
1387
+ }
1388
+ };
1389
+ walk("");
1390
+ return dirs;
1391
+ }
1392
+ // src/cli/jest-preset.ts
1393
+ /**
1394
+ * A Jest preset's settings, read as Jest applies them, for migrate.
1395
+ *
1396
+ * Jest applies a preset under the project's config (jest-config `setupPreset`): the
1397
+ * project's keys win, setupFiles and setupFilesAfterEnv run the preset's files first,
1398
+ * moduleNameMapper tries the project's patterns first, and transform and globals merge.
1399
+ * A project-local preset is often a known one spread and extended
1400
+ * (`module.exports = { ...require('jest-expo/jest-preset') }`); migrate recognises it
1401
+ * as that preset, so it gets the same translation, and carries over what it adds.
1402
+ */
1403
+ /** The presets migrate translates by name, in the order a local preset is matched against. */
1404
+ const KNOWN_PRESETS = [
1405
+ "jest-expo",
1406
+ "jest-expo/ios",
1407
+ "jest-expo/android",
1408
+ "jest-expo/universal",
1409
+ "jest-expo/web",
1410
+ "jest-expo/node",
1411
+ "react-native",
1412
+ "@react-native/jest-preset"
1413
+ ];
1414
+ /** Keys the discovery translation reads from the preset itself (translateDiscovery). */
1415
+ const DISCOVERY_KEYS = /* @__PURE__ */ new Set([
1416
+ "testMatch",
1417
+ "testRegex",
1418
+ "testPathIgnorePatterns",
1419
+ "modulePathIgnorePatterns",
1420
+ "moduleFileExtensions",
1421
+ "roots"
1422
+ ]);
1423
+ const isLocal = (preset) => preset.startsWith(".") || preset.startsWith("<rootDir>") || path.isAbsolute(preset);
1424
+ const isPlainObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
1425
+ /** What `local` sets beyond `base`: new keys, changed values, array items and entries `base` lacks. */
1426
+ function beyond(local, base) {
1427
+ const own = {};
1428
+ for (const [key, value] of Object.entries(local)) {
1429
+ const from = base[key];
1430
+ if (isDeepStrictEqual(value, from)) continue;
1431
+ if (Array.isArray(value) && Array.isArray(from)) own[key] = value.filter((item) => !from.some((f) => isDeepStrictEqual(f, item)));
1432
+ else if (isPlainObject(value) && isPlainObject(from)) own[key] = Object.fromEntries(Object.entries(value).filter(([k, v]) => !isDeepStrictEqual(v, from[k])));
1433
+ else own[key] = value;
1434
+ }
1435
+ return own;
1436
+ }
1437
+ /**
1438
+ * The known preset a local preset spreads: every key of the known preset is present,
1439
+ * and more of its values are kept than changed. The best match wins (jest-expo/ios
1440
+ * and jest-expo share keys).
1441
+ */
1442
+ function recognise(root, local) {
1443
+ let best;
1444
+ for (const name of KNOWN_PRESETS) {
1445
+ const loaded = loadJestPreset(root, name);
1446
+ if (!("config" in loaded)) continue;
1447
+ const keys = Object.keys(loaded.config);
1448
+ if (keys.length === 0 || !keys.every((k) => k in local)) continue;
1449
+ const kept = keys.filter((k) => isDeepStrictEqual(local[k], loaded.config[k])).length;
1450
+ if (kept * 2 <= keys.length) continue;
1451
+ if (!best || kept > best.kept) best = {
1452
+ name,
1453
+ config: loaded.config,
1454
+ kept
1455
+ };
1456
+ }
1457
+ return best;
1458
+ }
1459
+ function resolveJestPreset(root, preset) {
1460
+ const known = KNOWN_PRESETS.includes(preset);
1461
+ const loaded = loadJestPreset(root, preset);
1462
+ if (!("config" in loaded)) return {
1463
+ name: preset,
1464
+ label: `'${preset}'`,
1465
+ loaded: null,
1466
+ loadError: loaded.error,
1467
+ own: {},
1468
+ known
1469
+ };
1470
+ const config = loaded.config;
1471
+ if (known) return {
1472
+ name: preset,
1473
+ label: `'${preset}'`,
1474
+ loaded: config,
1475
+ own: {},
1476
+ known
1477
+ };
1478
+ const match = isLocal(preset) ? recognise(root, config) : void 0;
1479
+ const own = match ? beyond(config, match.config) : { ...config };
1480
+ for (const key of DISCOVERY_KEYS) delete own[key];
1481
+ delete own.preset;
1482
+ for (const [key, value] of Object.entries(own)) if (Array.isArray(value) && value.length === 0 || isPlainObject(value) && Object.keys(value).length === 0) delete own[key];
1483
+ return match ? {
1484
+ name: match.name,
1485
+ label: `'${preset}' (${match.name}'s preset, spread)`,
1486
+ loaded: config,
1487
+ own,
1488
+ known: true
1489
+ } : {
1490
+ name: preset,
1491
+ label: `'${preset}'`,
1492
+ loaded: config,
1493
+ own,
1494
+ known: false
1495
+ };
1496
+ }
1497
+ /** The project's config with the preset's settings under it, as jest-config's setupPreset merges them. */
1498
+ function withPresetSettings(config, own) {
1499
+ const merged = {
1500
+ ...own,
1501
+ ...config
1502
+ };
1503
+ for (const key of ["setupFiles", "setupFilesAfterEnv"]) if (Array.isArray(own[key]) && Array.isArray(config[key])) merged[key] = [...own[key], ...config[key]];
1504
+ for (const key of [
1505
+ "moduleNameMapper",
1506
+ "transform",
1507
+ "globals"
1508
+ ]) if (isPlainObject(own[key]) && isPlainObject(config[key])) merged[key] = {
1509
+ ...own[key],
1510
+ ...config[key]
1511
+ };
1512
+ if (isPlainObject(own.moduleNameMapper) && isPlainObject(config.moduleNameMapper)) merged.moduleNameMapper = {
1513
+ ...config.moduleNameMapper,
1514
+ ...Object.fromEntries(Object.entries(own.moduleNameMapper).filter(([k]) => !(k in config.moduleNameMapper)))
1515
+ };
1516
+ return merged;
1517
+ }
1518
+ // src/cli/superseded.ts
1519
+ /**
1520
+ * Jest settings a project wires up for a library vitest-native handles itself, which
1521
+ * migrate reports as covered (delete) instead of carrying them over. Each recogniser is
1522
+ * narrow: it matches a setting whose whole effect is known, and anything more stays
1523
+ * with the project.
1524
+ *
1525
+ * Reanimated, wherever its preset applies:
1526
+ * - Its and Worklets' Jest resolvers: the native engine applies both itself where their
1527
+ * own mocks run (native/jest-resolvers.mjs); elsewhere the preset replaces the package.
1528
+ * - A snapshot serializer that only strips `jestAnimatedProps`, `jestAnimatedStyle` and
1529
+ * `jestInlineStyle`: Reanimated's real AnimatedComponent adds those props under Jest;
1530
+ * its mock's createAnimatedComponent and the preset's module add none.
1531
+ * - A setup file that only calls `setUpTests()`: vitest-native registers
1532
+ * toHaveAnimatedStyle and toHaveAnimatedProps itself, and Reanimated's own versions read
1533
+ * props its mock does not set (presets/reanimated.ts keeps the engine's).
1534
+ */
1535
+ const RESOLVER = /(?:^|node_modules\/)(react-native-(?:reanimated|worklets))\/jest\/resolver(?:\.js)?$/;
1536
+ /** The library whose own Jest resolver `resolver` names, or null. */
1537
+ function libraryResolver(resolver) {
1538
+ return RESOLVER.exec(resolver.replace(/\\/g, "/"))?.[1] ?? null;
1539
+ }
1540
+ const REANIMATED_TEST_PROPS = /* @__PURE__ */ new Set([
1541
+ "jestAnimatedProps",
1542
+ "jestAnimatedStyle",
1543
+ "jestInlineStyle"
1544
+ ]);
1545
+ /**
1546
+ * The source without its whole-line comments, or null when a comment marker appears
1547
+ * anywhere else (a trailing comment, `src/*` inside a comment, `//` in a string): a
1548
+ * regex that strips comments across lines can swallow real code between a stray `/*`
1549
+ * and a later `*\/`, and a file that cannot be read exactly is kept.
1550
+ */
1551
+ function withoutComments(source) {
1552
+ const code = [];
1553
+ let inBlock = false;
1554
+ for (const raw of source.split("\n")) {
1555
+ const line = raw.trim();
1556
+ if (inBlock) {
1557
+ const end = line.indexOf("*/");
1558
+ if (end === -1) {
1559
+ if (line.includes("/*") || line.includes("//")) return null;
1560
+ continue;
1561
+ }
1562
+ if (end !== line.length - 2) return null;
1563
+ inBlock = false;
1564
+ } else if (line.startsWith("//")) {
1565
+ if (line.includes("/*") || line.includes("*/")) return null;
1566
+ } else if (line.startsWith("/*")) {
1567
+ const end = line.indexOf("*/", 2);
1568
+ if (line.indexOf("/*", 2) !== -1 || line.includes("//")) return null;
1569
+ if (end === -1) inBlock = true;
1570
+ else if (end !== line.length - 2) return null;
1571
+ } else if (line.includes("/*") || line.includes("*/") || line.includes("//")) return null;
1572
+ else code.push(raw);
1573
+ }
1574
+ return inBlock ? null : code.join("\n");
1575
+ }
1576
+ /**
1577
+ * Whether a serializer's source only strips Reanimated's Jest props: it names at least
1578
+ * one of them, loads nothing, and its only other string is `object` (typeof checks).
1579
+ */
1580
+ function stripsOnlyReanimatedProps(source) {
1581
+ const code = withoutComments(source);
1582
+ if (code === null || /\brequire\s*\(|^\s*import\b/m.test(code)) return false;
1583
+ const strings = [...code.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)].map((m) => m[2]);
1584
+ return strings.some((s) => REANIMATED_TEST_PROPS.has(s)) && strings.every((s) => REANIMATED_TEST_PROPS.has(s) || s === "object");
1585
+ }
1586
+ const Q = `(['"])react-native-reanimated\\1`;
1587
+ const SETUP_STATEMENTS = [
1588
+ /^(['"])use strict\1$/,
1589
+ new RegExp(`^import\\s*\\{\\s*setUpTests\\s*\\}\\s*from\\s*${Q}$`),
1590
+ new RegExp(`^(?:const|let|var)\\s*\\{\\s*setUpTests\\s*\\}\\s*=\\s*require\\(\\s*${Q}\\s*\\)$`),
1591
+ /^setUpTests\(\s*\)$/,
1592
+ new RegExp(`^require\\(\\s*${Q}\\s*\\)\\.setUpTests\\(\\s*\\)$`)
1593
+ ];
1594
+ /**
1595
+ * Whether a setup file's source only calls Reanimated's `setUpTests()`, with no
1596
+ * arguments (a frame-time argument is a setting the project chose).
1597
+ */
1598
+ function onlyCallsSetUpTests(source) {
1599
+ const code = withoutComments(source);
1600
+ if (code === null) return false;
1601
+ const statements = code.split(/[;\n]/).map((s) => s.trim()).filter(Boolean);
1602
+ return statements.filter((s) => /setUpTests\(\s*\)$/.test(s)).length === 1 && statements.every((s) => SETUP_STATEMENTS.some((re) => re.test(s)));
1603
+ }
1397
1604
  // src/cli/untranspiled.ts
1398
1605
  /**
1399
1606
  * Evidence that a package needs `transform`: a `.js` file under one of its entry
@@ -1403,13 +1610,6 @@ function booleanFlag(value) {
1403
1610
  * both. Parsed with the project's @babel/parser and no syntax plugins; without the
1404
1611
  * parser there is no evidence and nothing is claimed.
1405
1612
  */
1406
- function babelParser(root) {
1407
- const req = createRequire(path.join(root, "package.json"));
1408
- for (const from of [() => req, () => createRequire(req.resolve("@babel/core"))]) try {
1409
- return from()("@babel/parser").parse;
1410
- } catch {}
1411
- return null;
1412
- }
1413
1613
  /** Directories in a package that are not part of what it runs. */
1414
1614
  const SKIP_DIRS = /* @__PURE__ */ new Set([
1415
1615
  "node_modules",
@@ -1489,15 +1689,7 @@ function untranspiledFile(root, pkg) {
1489
1689
  continue;
1490
1690
  }
1491
1691
  if (!/\.(js|cjs|mjs)$/.test(name) || budget-- <= 0) continue;
1492
- try {
1493
- parse(fs.readFileSync(file, "utf8"), {
1494
- sourceType: "unambiguous",
1495
- allowReturnOutsideFunction: true,
1496
- allowAwaitOutsideFunction: true
1497
- });
1498
- } catch {
1499
- return path.relative(dir, file).split(path.sep).join("/");
1500
- }
1692
+ if (!isPlainJavaScript(parse, file)) return path.relative(dir, file).split(path.sep).join("/");
1501
1693
  }
1502
1694
  }
1503
1695
  return null;
@@ -1637,6 +1829,24 @@ function exactMapperKey(pattern) {
1637
1829
  const expansions = m ? tryExpand(m[1], true) : null;
1638
1830
  return expansions?.length === 1 && !expansions[0].includes("\0") ? expansions[0] : null;
1639
1831
  }
1832
+ /**
1833
+ * A `^prefix/(.*)$` → `<rootDir>/dir/$1` moduleNameMapper, which is a plain prefix
1834
+ * alias: the literal prefix (escapes read as literals, as exactMapperKey reads them)
1835
+ * and the project-relative target directory, or null.
1836
+ */
1837
+ function prefixMapper(pattern, target) {
1838
+ const m = /^\^(.+)\/\((\.\*|\.\+)\)\$?$/.exec(pattern);
1839
+ if (!m || typeof target !== "string") return null;
1840
+ const expansions = tryExpand(m[1], true);
1841
+ if (expansions?.length !== 1 || expansions[0].includes("\0")) return null;
1842
+ const t = /^(<rootDir>|\.)(\/.*)?\/\$1$/.exec(target);
1843
+ if (!t || target.indexOf("$") !== target.length - 2) return null;
1844
+ return {
1845
+ key: expansions[0],
1846
+ dir: `.${t[2] ?? ""}`,
1847
+ rest: m[2]
1848
+ };
1849
+ }
1640
1850
  /** `pkg` and `/sub` of a bare specifier (scope-aware). */
1641
1851
  function splitSpecifier(specifier) {
1642
1852
  const parts = specifier.split("/");
@@ -1684,7 +1894,7 @@ function analyzeJestConfig(root) {
1684
1894
  }
1685
1895
  } catch {}
1686
1896
  const explicitConfig = scriptFlags?.flags.get("config") ?? scriptFlags?.flags.get("c");
1687
- const { source, config, error: configError } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
1897
+ const { source, config: projectConfig, error: configError } = loadJestConfig(root, typeof explicitConfig === "string" ? explicitConfig : void 0);
1688
1898
  const automatic = [];
1689
1899
  const attention = [];
1690
1900
  if (source && configError) attention.push(`${source} could not be loaded (${configError}), so none of its settings are in the suggested config; carry them over by hand.`);
@@ -1701,9 +1911,13 @@ function analyzeJestConfig(root) {
1701
1911
  let excludeGlobs = [];
1702
1912
  let needsUrlImport = false;
1703
1913
  const pluginOptions = [];
1704
- const jestPreset = typeof config?.preset === "string" ? config.preset : void 0;
1914
+ const resolvedPreset = typeof projectConfig?.preset === "string" ? resolveJestPreset(root, projectConfig.preset) : void 0;
1915
+ const presetKeys = Object.keys(resolvedPreset?.own ?? {});
1916
+ const config = projectConfig && resolvedPreset && presetKeys.length ? withPresetSettings(projectConfig, resolvedPreset.own) : projectConfig;
1917
+ const jestPreset = resolvedPreset?.name;
1705
1918
  const navigationOff = /^jest-expo(\/(ios|android|universal))?$/.test(jestPreset ?? "") && activePresets(root).includes("navigation") && !fs.existsSync(path.join(root, "__mocks__", "@react-navigation"));
1706
1919
  const active = activePresets(root, navigationOff ? ["navigation"] : []);
1920
+ const runsWithOwnSetup = (preset) => LIBRARY_SETUP_FILES[preset] !== void 0 && !active.includes(preset);
1707
1921
  const autoInlined = new Set(detectEcosystemPackages(root, [], [], [], active));
1708
1922
  const addAlias = (key, value) => {
1709
1923
  if (aliasKeys.has(key)) return false;
@@ -1711,6 +1925,18 @@ function analyzeJestConfig(root) {
1711
1925
  aliasEntries.push(`${JSON.stringify(key)}: ${value}`);
1712
1926
  return true;
1713
1927
  };
1928
+ const projectSource = (file) => {
1929
+ if (/^(?:<rootDir>\/|\.\/)?node_modules\//.test(file)) return null;
1930
+ const rel = file.replace(/^<rootDir>\/?/, "");
1931
+ const base = path.resolve(root, rel);
1932
+ const found = [
1933
+ base,
1934
+ `${base}.js`,
1935
+ `${base}.ts`
1936
+ ].find((candidate) => fs.statSync(candidate, { throwIfNoEntry: false })?.isFile());
1937
+ return found === void 0 ? null : fs.readFileSync(found, "utf8");
1938
+ };
1939
+ const reanimatedActive = active.includes("reanimated");
1714
1940
  const absolutePath = (relative) => {
1715
1941
  needsUrlImport = true;
1716
1942
  return `fileURLToPath(new URL(${JSON.stringify(relative)}, import.meta.url))`;
@@ -1721,30 +1947,33 @@ function analyzeJestConfig(root) {
1721
1947
  handled.add(key);
1722
1948
  return config[key];
1723
1949
  };
1724
- const preset = take("preset");
1725
- if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin.`);
1950
+ take("preset");
1951
+ const preset = resolvedPreset?.name;
1952
+ const label = resolvedPreset?.label;
1953
+ if (preset === "react-native" || preset === "@react-native/jest-preset") automatic.push(`preset: ${label} → replaced by the reactNative() plugin.`);
1726
1954
  else if (preset === "jest-expo" || preset === "jest-expo/ios" || preset === "jest-expo/android") {
1727
1955
  const android = preset === "jest-expo/android";
1728
1956
  if (android) pluginOptions.push(`platform: 'android'`);
1729
- automatic.push(`preset: '${preset}' → replaced by the reactNative() plugin${android ? " with platform: 'android'" : ""}.`);
1730
- attention.push(`preset: '${preset}' — ${expoPresetCoverage()}.`);
1731
- } else if (preset === "jest-expo/universal") attention.push("preset: 'jest-expo/universal' runs one Jest project per platform. Define a Vitest project for each native platform (reactNative({ platform: 'ios' }) and reactNative({ platform: 'android' })); its web and node projects are not React Native renders and stay outside vitest-native.");
1732
- else if (preset === "jest-expo/web" || preset === "jest-expo/node") attention.push(`preset: '${preset}' targets ${preset.slice(10)}, not a React Native render; run these suites without vitest-native.`);
1733
- else if (preset) attention.push(`preset: '${preset}' — unknown preset; review what it configured.`);
1734
- let presetConfig = null;
1735
- if (preset) {
1736
- const loaded = loadJestPreset(root, preset);
1737
- if ("config" in loaded) presetConfig = loaded.config;
1738
- else attention.push(`preset: '${preset}' could not be loaded (${loaded.error}), so its testMatch/testPathIgnorePatterns could not be read; test.include falls back to Jest's defaults — compare with the preset.`);
1739
- }
1957
+ automatic.push(`preset: ${label} → replaced by the reactNative() plugin${android ? " with platform: 'android'" : ""}.`);
1958
+ attention.push(`preset: ${label} — ${expoPresetCoverage()}.`);
1959
+ } else if (preset === "jest-expo/universal") attention.push(`preset: ${label} runs one Jest project per platform. Define a Vitest project for each native platform (reactNative({ platform: 'ios' }) and reactNative({ platform: 'android' })); its web and node projects are not React Native renders and stay outside vitest-native.`);
1960
+ else if (preset === "jest-expo/web" || preset === "jest-expo/node") attention.push(`preset: ${label} targets ${preset.slice(10)}, not a React Native render; run these suites without vitest-native.`);
1961
+ else if (preset && resolvedPreset?.loaded) attention.push(`preset: ${label} — not a preset vitest-native translates by name; its settings are translated below as Jest applies them, under this config's own. Review what else it did.`);
1962
+ else if (preset) attention.push(`preset: ${label} — unknown preset; review what it configured.`);
1963
+ if (presetKeys.length) automatic.push(`preset: ${label} also sets ${list(presetKeys)} → each is handled below like this config's own keys, merged with them as Jest merges a preset's.`);
1964
+ const presetConfig = resolvedPreset?.loaded ?? null;
1965
+ if (resolvedPreset && !resolvedPreset.loaded) attention.push(`preset: ${label} could not be loaded (${resolvedPreset.loadError}), so its testMatch/testPathIgnorePatterns could not be read; test.include falls back to Jest's defaults — compare with the preset.`);
1740
1966
  for (const key of ["setupFiles", "setupFilesAfterEnv"]) {
1741
1967
  const files = take(key);
1742
1968
  if (!files?.length) continue;
1743
1969
  for (const f of files) {
1744
- const setupPackage = /^(@[^/]+\/[^/]+|[^@./][^/]*)\//.exec(f)?.[1];
1970
+ const asRequest = f.replace(/^(?:<rootDir>\/|\.\/)?node_modules\//, "");
1971
+ const setupPackage = /^(@[^/]+\/[^/]+|[^@./<][^/]*)\//.exec(asRequest)?.[1];
1745
1972
  const setupPreset = setupPackage ? presetShadowing(setupPackage) : void 0;
1746
1973
  if (/react-native\/jest\/setup/.test(f)) presetCovered.push(`${key}: '${f}' — the plugin injects its own setup; delete.`);
1747
1974
  else if (setupPreset && active.includes(setupPreset)) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup; the auto-detected ${setupPreset} preset shadows ${setupPackage}, and this file's jest.mock() calls would replace it; delete.`);
1975
+ else if (setupPreset && runsWithOwnSetup(setupPreset) && asRequest.replace(/\.js$/, "") === LIBRARY_SETUP_FILES[setupPreset]?.replace(/\.js$/, "")) presetCovered.push(`${key}: '${f}' — ${setupPackage}'s own test setup, which the native engine runs before the setup files (${LIBRARY_SETUP_FILES[setupPreset]}); delete.`);
1976
+ else if (reanimatedActive && onlyCallsSetUpTests(projectSource(f) ?? "")) presetCovered.push(`${key}: '${f}' — only calls Reanimated's setUpTests(), whose matchers cannot see the rendered style here; vitest-native registers toHaveAnimatedStyle and toHaveAnimatedProps itself; delete.`);
1748
1977
  else if (/jest-expo/.test(f)) attention.push(`${key}: '${f}' — ${expoPresetCoverage()}.`);
1749
1978
  else if (f.startsWith("<rootDir>")) {
1750
1979
  setupFiles.push(absolutePath(f.replace(/^<rootDir>\/?/, "./")));
@@ -1759,6 +1988,12 @@ function analyzeJestConfig(root) {
1759
1988
  if (mapper) for (const [pattern, target] of Object.entries(mapper)) {
1760
1989
  const assetGroup = /\\\.\(\??:?([a-z0-9|]+)\)\$?$/i.exec(pattern);
1761
1990
  const literal = exactMapperKey(pattern);
1991
+ const prefix = assetGroup ? null : prefixMapper(pattern, target);
1992
+ const plainPrefix = prefix && ![
1993
+ "@",
1994
+ "~",
1995
+ "src"
1996
+ ].includes(prefix.key) ? prefix : null;
1762
1997
  if (assetGroup) {
1763
1998
  const exts = assetGroup[1].toLowerCase().split("|");
1764
1999
  const missing = exts.filter((e) => !DEFAULT_ASSET_EXTS.includes(e));
@@ -1767,6 +2002,10 @@ function analyzeJestConfig(root) {
1767
2002
  pluginOptions.push(`assetExts: ${JSON.stringify(missing)}`);
1768
2003
  automatic.push(`moduleNameMapper '${pattern}' — ${list(missing)} ${missing.length === 1 ? "is" : "are"} not among the extensions the plugin handles by default → reactNative({ assetExts: ${JSON.stringify(missing)} }).`);
1769
2004
  }
2005
+ } else if (plainPrefix) {
2006
+ const find = `${regexLiteral(plainPrefix.key).slice(0, -2)}\\/(${plainPrefix.rest})$/`;
2007
+ regexAliases.push(`{ find: ${find}, replacement: ${absolutePath(plainPrefix.dir)} + "/$1" }`);
2008
+ automatic.push(`moduleNameMapper '${pattern}' → resolve.alias { find: ${find} } (absolute path).`);
1770
2009
  } else if (/^\^?@\/|\^~\/|\^src\//.test(pattern)) {
1771
2010
  const aliasKey = pattern.replace(/[\^$]/g, "").replace(/\((\.\*|\.\+)\)\$?$/, "").replace(/\/$/, "");
1772
2011
  const aliasTarget = String(target).replace(/^<rootDir>\/?/, "./").replace(/\/\$1$/, "").replace(/\/$/, "");
@@ -1865,7 +2104,8 @@ function analyzeJestConfig(root) {
1865
2104
  const value = take(key);
1866
2105
  if (value !== void 0) discoveryOptions[key] = value;
1867
2106
  }
1868
- const discovery = translateDiscovery(discoveryOptions, presetConfig, jestMajor(root));
2107
+ let directories;
2108
+ const discovery = translateDiscovery(discoveryOptions, presetConfig, jestMajor(root), () => directories ??= projectDirectories(root));
1869
2109
  if (discovery.include) testEntries.push(`include: [${discovery.include.map((g) => JSON.stringify(g)).join(", ")}]`);
1870
2110
  excludeGlobs = discovery.exclude;
1871
2111
  automatic.push(...discovery.automatic);
@@ -1892,7 +2132,9 @@ function analyzeJestConfig(root) {
1892
2132
  "transform",
1893
2133
  "globals",
1894
2134
  "snapshotSerializers",
1895
- "reporters"
2135
+ "reporters",
2136
+ "watchPathIgnorePatterns",
2137
+ "workerIdleMemoryLimit"
1896
2138
  ]) if (config[key] !== void 0) {
1897
2139
  handled.add(key);
1898
2140
  if (key === "transform") dropped.push(`transform — Babel/esbuild transforms are the plugin's job; dropped.`);
@@ -1900,13 +2142,29 @@ function analyzeJestConfig(root) {
1900
2142
  const vitestKey = key === "resetMocks" ? "mockReset" : key;
1901
2143
  automatic.push(key === vitestKey ? `${key} → test.${key} (same name in Vitest).` : `${key} → test.${vitestKey} (Vitest's name for it).`);
1902
2144
  testEntries.push(`${vitestKey}: ${JSON.stringify(config[key])}`);
1903
- } else if (key === "snapshotSerializers") attention.push(`snapshotSerializers — Vitest uses expect.addSnapshotSerializer; vitest-native ships one for RN trees.`);
2145
+ } else if (key === "snapshotSerializers") {
2146
+ const serializers = Array.isArray(config[key]) ? config[key] : [];
2147
+ const rest = [];
2148
+ for (const entry of serializers) {
2149
+ const code = typeof entry === "string" ? projectSource(entry) : null;
2150
+ if (reanimatedActive && code !== null && stripsOnlyReanimatedProps(code)) presetCovered.push(`snapshotSerializers '${entry}' — strips the jest* props Reanimated's real components add under Jest; the Reanimated preset's components add none; delete.`);
2151
+ else rest.push(String(entry));
2152
+ }
2153
+ if (rest.length || !serializers.length) attention.push(`snapshotSerializers${rest.length ? ` ${rest.map((r) => `'${r}'`).join(", ")}` : ""} — Vitest uses expect.addSnapshotSerializer; vitest-native ships one for RN trees.`);
2154
+ } else if (key === "watchPathIgnorePatterns") dropped.push(`${key} — affects only Jest's watch mode; Vitest's watch mode reruns by the module graph (tune it with server.watch.ignored if needed); dropped.`);
2155
+ else if (key === "workerIdleMemoryLimit") dropped.push(`${key} — Vitest recycles workers by memory only in its vm pools (test.vmMemoryLimit), which vitest-native does not use; dropped. Watch memory on the first full run.`);
1904
2156
  else dropped.push(`${key} — no vitest-native equivalent needed; dropped.`);
1905
2157
  }
1906
2158
  if (config.clearMocks === void 0) {
1907
2159
  testEntries.push(`clearMocks: false`);
1908
2160
  automatic.push("Jest keeps mock calls between tests unless clearMocks is set → test.clearMocks: false (Vitest 5 clears them before each test by default).");
1909
2161
  }
2162
+ const resolver = typeof config.resolver === "string" ? config.resolver : void 0;
2163
+ const resolverLibrary = resolver ? libraryResolver(resolver) : null;
2164
+ if (resolverLibrary && (reanimatedActive || active.includes("worklets"))) {
2165
+ handled.add("resolver");
2166
+ presetCovered.push(`resolver: '${resolver}' — ${resolverLibrary}'s own Jest resolver: the native engine applies Reanimated's and Worklets' resolvers itself where their own mocks run, and their presets replace the packages elsewhere; delete.`);
2167
+ }
1910
2168
  for (const key of Object.keys(config)) if (!handled.has(key)) attention.push(`'${key}' — unrecognized Jest key; review manually.`);
1911
2169
  }
1912
2170
  const mocksDir = path.join(root, "__mocks__");
@@ -1916,6 +2174,7 @@ function analyzeJestConfig(root) {
1916
2174
  for (const candidate of candidates) {
1917
2175
  const preset = presetShadowing(candidate);
1918
2176
  if (preset && active.includes(preset)) presetCovered.push(`__mocks__/${candidate} — the auto-detected ${preset} preset shadows ${candidate}; delete the manual mock.`);
2177
+ else if (preset && runsWithOwnSetup(preset) && installedManifest(root, candidate)) presetCovered.push(`__mocks__/${candidate} — the native engine runs ${candidate} with its own Jest setup (${LIBRARY_SETUP_FILES[preset]}), which replaces its native layer; delete the manual mock.`);
1919
2178
  else if (installedManifest(root, candidate) && installedTestsItself(root, candidate)) attention.push(`__mocks__/${candidate} — ${candidate} ${installedMajor(root, candidate)} runs its own test mode under Vitest, so no preset replaces it, and Vitest applies a root __mocks__ file only through vi.mock; the library's test mode stands in for this mock.`);
1920
2179
  }
1921
2180
  }
@@ -1927,13 +2186,12 @@ function analyzeJestConfig(root) {
1927
2186
  if (babel.source) {
1928
2187
  const classified = classifyBabelPlugins(babel, root, active);
1929
2188
  const required = classified.filter((p) => p.verdict === "required");
1930
- const vite = viteMajor(root);
1931
2189
  if (required.length) {
1932
- if (vite !== null && vite >= 8 && installed(root, "@rolldown/plugin-babel") && installed(root, "@babel/core") && required.every(serializableOptions)) {
2190
+ if (installed(root, "@rolldown/plugin-babel") && installed(root, "@babel/core") && required.every(serializableOptions)) {
1933
2191
  extraImports.push(`import babel from '@rolldown/plugin-babel'`);
1934
2192
  extraPlugins.push(`babel({ plugins: ${pluginListSource(required)} })`);
1935
2193
  for (const p of required) automatic.push(`${babel.source}: ${p.reason} → babel() from @rolldown/plugin-babel.`);
1936
- } else for (const p of required) attention.push(`${babel.source}: ${p.reason} Required: ${babelRecipe(vite, required)}.`);
2194
+ } else for (const p of required) attention.push(`${babel.source}: ${p.reason} Required: ${babelRecipe(required)}.`);
1937
2195
  }
1938
2196
  for (const p of classified.filter((c) => c.verdict === "alias")) {
1939
2197
  const options = p.options ?? {};
@@ -2058,79 +2316,2048 @@ function renderMigrationReport(report, { write = false } = {}) {
2058
2316
  lines.push(...HOT_RUNTIME_NOTE);
2059
2317
  return lines;
2060
2318
  }
2061
- // src/cli/index.ts
2319
+ // src/cli/compare.ts
2062
2320
  /**
2063
- * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
2064
- * environment), `migrate` (analyze a Jest config and report the mapping).
2065
- * Deliberately vitest-free at module load — it runs via npx outside any test
2066
- * process.
2321
+ * `vitest-native compare`: the pure half. It reads a Jest `--json` report and a Vitest
2322
+ * JSON-reporter report, matches their tests, sorts each into a bucket and renders the
2323
+ * result. Running the two runners is compare-run.ts. The design, and why the summary
2324
+ * makes the one claim it does, is in docs/compare-mode.md.
2325
+ *
2326
+ * Formats: Jest's `FormattedTestResults` (@jest/test-result 30: testResults[].name,
2327
+ * .status, .message, .assertionResults[] with ancestorTitles/title/status/
2328
+ * failureMessages) and Vitest's `JsonTestResults` (vitest 4–5, the same field names).
2329
+ * Identities come from the structured fields, never from `fullName`: both runners join
2330
+ * it with spaces, so `describe("a b")` and `describe("a", () => describe("b"))` collide.
2067
2331
  */
2068
- const USAGE = `vitest-native — test React Native with Vitest
2069
-
2070
- Usage:
2071
- vitest-native init [--jest-compat] [--force] write a ready-to-run vitest config
2072
- vitest-native doctor diagnose peers, engine, presets, RNTL/Node
2073
- vitest-native migrate [--write] [--force] analyze jest config → migration report
2074
- (--write also saves the suggested config)
2075
- Options:
2076
- --root <dir> project root (default: cwd)
2077
- --help this text
2078
-
2079
- Docs: https://danfry1.github.io/vitest-native/`;
2080
- function main(argv, log = console.log) {
2081
- const args = argv.filter((a) => a !== "--");
2082
- const command = args.find((a, i) => !a.startsWith("-") && args[i - 1] !== "--root");
2083
- const has = (flag) => args.includes(flag);
2084
- const rootIdx = args.indexOf("--root");
2085
- const root = path.resolve(rootIdx !== -1 ? args[rootIdx + 1] ?? "." : ".");
2086
- if (has("--help") || has("-h")) {
2087
- log(USAGE);
2088
- return 0;
2089
- }
2090
- if (!command) {
2091
- log(USAGE);
2092
- return 1;
2332
+ const BUCKETS = [
2333
+ "same-pass",
2334
+ "same-fail",
2335
+ "same-skip",
2336
+ "regression",
2337
+ "improvement",
2338
+ "skip-difference",
2339
+ "only-jest",
2340
+ "only-vitest"
2341
+ ];
2342
+ const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
2343
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2344
+ /**
2345
+ * Every way a message can spell `p`: as written, with either separator, JSON-escaped
2346
+ * (`C:\\x`), as a file URL. A Windows drive letter matches in either case.
2347
+ */
2348
+ function spellingPattern(paths) {
2349
+ const out = /* @__PURE__ */ new Set();
2350
+ for (const p of paths) {
2351
+ if (!p || p.length < 2) continue;
2352
+ const forward = p.replace(/\\/g, "/").replace(/\/$/, "");
2353
+ if (forward.length < 2) continue;
2354
+ out.add(forward);
2355
+ out.add(forward.replace(/\//g, "\\"));
2356
+ out.add(forward.replace(/\//g, "\\\\"));
2357
+ out.add(`file://${forward.startsWith("/") ? "" : "/"}${forward}`);
2093
2358
  }
2094
- if (!fs.existsSync(path.join(root, "package.json"))) {
2095
- log(`✗ no package.json at ${root} — run from a project root or pass --root.`);
2096
- return 1;
2359
+ if (!out.size) return null;
2360
+ const alternatives = [...out].sort((a, b) => b.length - a.length).map((s) => escapeRegex(s).replace(/^([A-Za-z]):/, (_, d) => `[${d.toLowerCase()}${d.toUpperCase()}]:`));
2361
+ return new RegExp(alternatives.join("|"), "g");
2362
+ }
2363
+ /** A Node location line (`/x/y.js:2`) heading a source line and a `^^^` marker. */
2364
+ const LOCATION = /^\s*\S+:\d+(?::\d+)?\s*$/;
2365
+ /** A marker line under a source excerpt: Node's `^^^`, TypeScript's `~~~`. */
2366
+ const MARKER = /^\s*[\^~]+\s*$/;
2367
+ /** A code-frame line: an optional `>`/`❯` marker, a line number, a vertical bar. */
2368
+ const FRAME = /^\s*[>❯]?\s*\d*\s*[|│┃┆┊]/;
2369
+ /** Box drawing (oxc/Vite 8's frames: `╭─[`, `───╯`, `╰──`). */
2370
+ const BOX = /^\s*[─-╿]/;
2371
+ /** A React component stack line: `in SecretVault (at vault.js:3)`, `in App`. */
2372
+ const COMPONENT_STACK = /^\s+in [A-Z$_][\w$.]*(?: \(at [^)]*\)| \(created by [^)]*\))?\s*$/;
2373
+ /**
2374
+ * Directories that only ever hold a machine's files — macOS's, a drive, a UNC share, and
2375
+ * the checkouts CI and containers use (GitHub Actions `/github/workspace`, `/__w`,
2376
+ * `/runner`; GitLab `/builds`; Buildkite; Netlify `/opt/build`; Docker's `/app`,
2377
+ * `/workspace`; WSL's `/mnt`): a path under one is a path, whatever it is followed by,
2378
+ * spaces included (`/Volumes/Client Work/app.js`).
2379
+ */
2380
+ const MACHINE_ROOT = String.raw`(?:\/(?:Users|Volumes|private|var\/folders|builds|github\/workspace|app|runner|__w|workspace|opt\/build|buildkite|mnt)\/|[A-Za-z]:[\\/]|\\\\(?=[\w.$-]+\\))`;
2381
+ /** A machine-rooted path, up to a file name with an extension, else to the next space. */
2382
+ const MACHINE_PATH = new RegExp(String.raw`(?<![\w.<>/~:@-])${MACHINE_ROOT}(?:[^\n'"\`<>|]*?\.[A-Za-z0-9]{1,10}(?=[\s'"\`)\]},;:]|$)|[^\s'"\`)\]},;]*)`, "g");
2383
+ /** Other absolute-looking spans; replaced only when they are paths (see isPath). */
2384
+ const POSIX_CANDIDATE = /(?<![\w.<>/~:@-])\/[\w.@+~-]+(?:\/[\w.@+~-]*)+/g;
2385
+ /** Roots shared with app routes (`/home/profile/edit`): a path needs a dotted segment there. */
2386
+ const SHARED_ROOT = /^\/(?:home\/[^/]+|tmp|var|opt|root|srv|etc|usr)\//;
2387
+ /** A home directory with at least two segments below the user: `/home/alice/clients/x`. */
2388
+ const DEEP_HOME = /^\/home\/[^/]+\/[^/]+\/[^/]+/;
2389
+ const FILE_URL = /file:\/\/\/[^\s'"`)\]},;]*/g;
2390
+ /** `/home/<user>/…`: the user segment, replaced wherever the rest of the span is kept. */
2391
+ const HOME_USER = /^\/home\/[^/]+\//;
2392
+ /**
2393
+ * Roots that never begin an app route, for assertion values: macOS's, a drive, a UNC
2394
+ * share. CI and container roots (`/app`, `/workspace`, …) begin routes too
2395
+ * (`/app/settings/privacy`, `/workspace/42/members`), so there a span needs a file name.
2396
+ */
2397
+ const STRONG_ROOT = /^(?:\/(?:Users|Volumes|private|var\/folders)\/|[A-Za-z]:[\\/]|\\\\)/;
2398
+ const STRONG_PATH = new RegExp(String.raw`(?<![\w.<>/~:@-])(?:\/(?:Users|Volumes|private|var\/folders)\/|[A-Za-z]:[\\/]|\\\\(?=[\w.$-]+\\))(?:[^\n'"\`<>|]*?\.[A-Za-z0-9]{1,10}(?=[\s'"\`)\]},;:]|$)|[^\s'"\`)\]},;]*)`, "g");
2399
+ /** Any absolute-looking span, POSIX or Windows, without spaces. */
2400
+ const ANY_CANDIDATE = /(?<![\w.<>/~:@-])(?:\/[\w.@+~-]+(?:\/[\w.@+~-]*)+|[A-Za-z]:[\\/][^\s'"`)\]},;]*)/g;
2401
+ /** An assertion's value lines: `Expected: …`, `Received: …`, and a diff's `-` / `+` lines. */
2402
+ const ASSERTION_VALUE = /^\s*(?:[-+]\s|Expected\b|Received\b)/;
2403
+ const namesFile = (span) => /\.[A-Za-z0-9]{1,10}$/.test(span.replace(/[\\/]+$/, ""));
2404
+ function exists(span) {
2405
+ try {
2406
+ return fs.existsSync(span);
2407
+ } catch {
2408
+ return false;
2097
2409
  }
2098
- switch (command) {
2099
- case "doctor": {
2100
- const result = runDoctor(root);
2101
- for (const line of result.lines) log(line);
2102
- return result.ok ? 0 : 1;
2103
- }
2104
- case "init": {
2105
- const result = runInit(root, {
2106
- jestCompat: has("--jest-compat"),
2107
- force: has("--force")
2108
- });
2109
- for (const line of result.lines) log(line);
2110
- return result.ok ? 0 : 1;
2111
- }
2112
- case "migrate": {
2113
- const report = analyzeJestConfig(root);
2114
- const write = has("--write");
2115
- for (const line of renderMigrationReport(report, { write })) log(line);
2116
- if (report.ok && write) {
2117
- const init = runInit(root, { force: has("--force") });
2118
- if (!init.ok) {
2119
- for (const line of init.lines) log(line);
2120
- return 1;
2121
- }
2122
- const target = path.join(root, init.wrote);
2123
- fs.writeFileSync(target, report.suggestedConfig);
2124
- log(`✓ wrote ${init.wrote} from the analysis above. Next: ${migrationNextStep(report)}`);
2410
+ }
2411
+ /**
2412
+ * Paths in an assertion's values, which are usually app data — navigation routes such as
2413
+ * `"/home/profile/edit/photo"` or `"/workspace/42/members"` — and must stay readable: a span
2414
+ * is replaced only when it names a file, exists on disk, or begins with a root no route
2415
+ * begins with (STRONG_ROOT).
2416
+ */
2417
+ function stripAssertionLine(line) {
2418
+ return line.replace(FILE_URL, "<path>").replace(STRONG_PATH, "<path>").replace(ANY_CANDIDATE, (span) => namesFile(span) || exists(span) || STRONG_ROOT.test(span) ? "<path>" : span);
2419
+ }
2420
+ /** Paths anywhere else in a message: every machine root, and a home directory's user. */
2421
+ function stripLine(line) {
2422
+ return line.replace(FILE_URL, "<path>").replace(MACHINE_PATH, "<path>").replace(POSIX_CANDIDATE, (span) => isPath(span) ? "<path>" : span.replace(HOME_USER, "/home/<user>/"));
2423
+ }
2424
+ /**
2425
+ * Whether an absolute-looking span is a path on a machine, not an app route: it exists
2426
+ * on disk, it goes two or more segments below a `/home/<user>/`, or it sits under a root
2427
+ * that routes share (`/home/<user>/`, `/tmp/`, …) and names a file (`.npmrc`, `app.js`).
2428
+ * `/home/profile/edit` and `/settings/privacy` stay.
2429
+ */
2430
+ function isPath(span) {
2431
+ if (fs.existsSync(span)) return true;
2432
+ if (DEEP_HOME.test(span)) return true;
2433
+ return SHARED_ROOT.test(span) && span.split("/").some((segment) => /\./.test(segment));
2434
+ }
2435
+ /**
2436
+ * A runner's failure message, kept to the error's own text. Removed: ANSI codes, the
2437
+ * stack (cut at the first ` at ` or `❯` frame), React component stacks, code frames of
2438
+ * every runner (`> 12 |`, `12| `, `12 │`, box drawing), any line a `^^^`/`~~~` marker
2439
+ * points at with its marker (Node's and esbuild's source excerpts, TypeScript
2440
+ * diagnostics), Node's `file:line` + source + `^^^` blocks (Jest's "Details:"), and
2441
+ * absolute paths: the root becomes `<root>`, the temporary directory `<tmp>`, the home
2442
+ * directory `~`, any other path on a machine `<path>` (UNC, Windows, file URLs, paths
2443
+ * with spaces). App routes such as `/home/profile/edit` are kept. What remains can still
2444
+ * include values a test put in its error, such as expected and received values.
2445
+ */
2446
+ function sanitizeMessage(raw, ctx) {
2447
+ const lines = raw.replace(ANSI, "").replace(/\r\n?/g, "\n").split("\n");
2448
+ const end = lines.findIndex((l) => /^\s+at\s/.test(l) || /^\s*❯\s/.test(l));
2449
+ const body = end === -1 ? lines : lines.slice(0, end);
2450
+ const drop = /* @__PURE__ */ new Set();
2451
+ for (let i = 0; i < body.length; i++) {
2452
+ const line = body[i];
2453
+ if (FRAME.test(line) || BOX.test(line) || COMPONENT_STACK.test(line)) drop.add(i);
2454
+ else if (MARKER.test(line)) {
2455
+ drop.add(i);
2456
+ for (let j = i - 1; j >= 0; j--) {
2457
+ if (body[j].trim() === "") continue;
2458
+ drop.add(j);
2459
+ if (j > 0 && LOCATION.test(body[j - 1])) drop.add(j - 1);
2460
+ break;
2125
2461
  }
2126
- return report.ok ? 0 : 1;
2127
2462
  }
2128
- default:
2129
- log(`✗ unknown command '${command}'.`);
2130
- log(USAGE);
2131
- return 1;
2132
2463
  }
2464
+ let text = body.filter((_, i) => !drop.has(i)).join("\n").replace(/\n{3,}/g, "\n\n").trim();
2465
+ const replace = (paths, to) => {
2466
+ const pattern = spellingPattern(paths);
2467
+ if (pattern) text = text.replace(pattern, to);
2468
+ };
2469
+ replace(ctx.roots, "<root>");
2470
+ replace(ctx.tmp ?? [], "<tmp>");
2471
+ if (ctx.home) replace([ctx.home], "~");
2472
+ text = text.split("\n").map((line) => ASSERTION_VALUE.test(line) ? stripAssertionLine(line) : stripLine(line)).join("\n");
2473
+ const capped = text.split("\n").slice(0, 30).join("\n");
2474
+ return capped.length > 4e3 ? `${capped.slice(0, 4e3)}…` : capped;
2133
2475
  }
2134
- const entry = process.argv[1] ? path.basename(process.argv[1]) : "";
2135
- if (entry === "cli.mjs" || entry === "cli.cjs" || entry === "vitest-native") process.exit(main(process.argv.slice(2)));
2136
- export { main };
2476
+ /**
2477
+ * The first non-empty line, whitespace collapsed: the key errors are grouped by. Jest's
2478
+ * `● <test name>` / `● Test suite failed to run` headers are skipped, so its file
2479
+ * failures group by the error.
2480
+ */
2481
+ function firstLine(message) {
2482
+ const lines = (message ?? "").split("\n").filter((l) => l.trim() !== "");
2483
+ const collapsed = (lines.find((l) => !l.trim().startsWith("●")) ?? lines[0] ?? "").trim().replace(/\s+/g, " ");
2484
+ return collapsed.length > 160 ? `${collapsed.slice(0, 160)}…` : collapsed || "(no message)";
2485
+ }
2486
+ function defaultRealpath(p) {
2487
+ try {
2488
+ return fs.realpathSync.native(p);
2489
+ } catch {
2490
+ return p;
2491
+ }
2492
+ }
2493
+ /** `/` separators and a lowercase drive letter: Jest writes `D:\x`, Vitest `D:/x`. */
2494
+ function slashed(p) {
2495
+ return p.replace(/\\/g, "/").replace(/^([A-Za-z]):/, (_, d) => `${d.toLowerCase()}:`);
2496
+ }
2497
+ function rootSpellings(ctx) {
2498
+ const real = ctx.realpath ?? defaultRealpath;
2499
+ return [.../* @__PURE__ */ new Set([
2500
+ ctx.root,
2501
+ real(ctx.root),
2502
+ ...ctx.aliases ?? []
2503
+ ])];
2504
+ }
2505
+ /** A reported test file as a root-relative `/` path (absolute when outside the root). */
2506
+ function relativeFile(name, ctx) {
2507
+ const real = ctx.realpath ?? defaultRealpath;
2508
+ const file = slashed(real(name));
2509
+ const roots = rootSpellings(ctx).map((r) => slashed(r).replace(/\/$/, ""));
2510
+ for (const r of roots) if (file.startsWith(`${r}/`)) return file.slice(r.length + 1);
2511
+ const base = slashed(real(ctx.root)).replace(/\/$/, "");
2512
+ if (file.startsWith("/") && base.startsWith("/")) return path.posix.relative(base, file);
2513
+ return file;
2514
+ }
2515
+ /**
2516
+ * Where a report made at another root was recorded: the prefix that, removed from its
2517
+ * absolute file names, leaves the files the other runner reported here. Null when no
2518
+ * prefix accounts for at least half of its files.
2519
+ */
2520
+ function foreignRoot(json, localFiles) {
2521
+ const names = (json?.testResults ?? []).map((r) => typeof r?.name === "string" ? slashed(r.name) : null).filter((n) => n !== null);
2522
+ const votes = /* @__PURE__ */ new Map();
2523
+ for (const name of names) {
2524
+ const match = localFiles.find((rel) => name.endsWith(`/${rel}`));
2525
+ if (match) {
2526
+ const prefix = name.slice(0, -(match.length + 1));
2527
+ votes.set(prefix, (votes.get(prefix) ?? 0) + 1);
2528
+ }
2529
+ }
2530
+ const [best] = [...votes].sort((a, b) => b[1] - a[1]);
2531
+ return best && best[1] * 2 >= names.length ? best[0] : null;
2532
+ }
2533
+ function outcome(status) {
2534
+ return status === "passed" ? "passed" : status === "failed" ? "failed" : "skipped";
2535
+ }
2536
+ /**
2537
+ * One runner's report as files of tests. Throws when the JSON is not a Jest or Vitest
2538
+ * report, so a wrong file is an error and not an empty run.
2539
+ */
2540
+ function normaliseReport(json, runner, ctx) {
2541
+ const report = json;
2542
+ if (!report || typeof report !== "object" || !Array.isArray(report.testResults)) throw new VitestNativeError("COMPARE_REPORT_INVALID", `not a ${runner} JSON report: it has no testResults array`);
2543
+ const sanitize = {
2544
+ roots: rootSpellings(ctx),
2545
+ tmp: ctx.tmp ?? tmpSpellings(),
2546
+ home: ctx.home ?? os.homedir()
2547
+ };
2548
+ const files = /* @__PURE__ */ new Map();
2549
+ for (const raw of report.testResults) {
2550
+ if (typeof raw?.name !== "string") continue;
2551
+ const file = relativeFile(raw.name, ctx);
2552
+ const tests = (Array.isArray(raw.assertionResults) ? raw.assertionResults : []).map((a) => {
2553
+ const first = (Array.isArray(a.failureMessages) ? a.failureMessages : []).find((m) => typeof m === "string" && m.trim() !== "");
2554
+ return {
2555
+ ancestors: Array.isArray(a.ancestorTitles) ? a.ancestorTitles.map(String) : [],
2556
+ title: String(a.title ?? ""),
2557
+ status: outcome(a.status),
2558
+ rawStatus: String(a.status ?? ""),
2559
+ message: first ? sanitizeMessage(first, sanitize) : null
2560
+ };
2561
+ });
2562
+ const status = outcome(raw.status);
2563
+ const message = typeof raw.message === "string" ? sanitizeMessage(raw.message, sanitize) : "";
2564
+ const broken = status === "failed" && (tests.length === 0 || !tests.some((t) => t.status === "failed") || runner === "vitest" && message !== "");
2565
+ const existing = files.get(file);
2566
+ if (existing) {
2567
+ existing.tests.push(...tests);
2568
+ if (status === "failed") existing.status = "failed";
2569
+ existing.broken ||= broken;
2570
+ existing.message ||= message;
2571
+ } else files.set(file, {
2572
+ file,
2573
+ status,
2574
+ message,
2575
+ broken,
2576
+ tests
2577
+ });
2578
+ }
2579
+ return {
2580
+ runner,
2581
+ files
2582
+ };
2583
+ }
2584
+ /** The system temporary directory, as written and with symlinks resolved. */
2585
+ function tmpSpellings() {
2586
+ const tmp = os.tmpdir();
2587
+ return [.../* @__PURE__ */ new Set([tmp, defaultRealpath(tmp)])];
2588
+ }
2589
+ /** Tests grouped by identity, in the order each identity first appears. */
2590
+ function grouped(tests) {
2591
+ const out = /* @__PURE__ */ new Map();
2592
+ for (const t of tests) {
2593
+ const key = JSON.stringify([t.ancestors, t.title]);
2594
+ const group = out.get(key) ?? {
2595
+ ancestors: t.ancestors,
2596
+ title: t.title,
2597
+ tests: []
2598
+ };
2599
+ group.tests.push(t);
2600
+ out.set(key, group);
2601
+ }
2602
+ return out;
2603
+ }
2604
+ /**
2605
+ * One result for every copy of an identity: passed only if every copy passed, failed if
2606
+ * any failed, otherwise skipped. Pairing copies by order would match a passing copy with
2607
+ * a failing one when the runners order them differently (concurrent tests, Jest's
2608
+ * randomize, projects).
2609
+ */
2610
+ function aggregate(group) {
2611
+ const { tests } = group;
2612
+ const failed = tests.find((t) => t.status === "failed");
2613
+ const side = {
2614
+ status: failed ? "failed" : tests.every((t) => t.status === "passed") ? "passed" : "skipped",
2615
+ rawStatus: tests.length === 1 ? tests[0].rawStatus : tests.map((t) => t.rawStatus).join(", "),
2616
+ message: failed?.message ?? null
2617
+ };
2618
+ if (tests.length > 1) side.copies = tests.length;
2619
+ return side;
2620
+ }
2621
+ const BROKEN_WITHOUT_MESSAGE = {
2622
+ jest: "the file failed outside any test under Jest",
2623
+ vitest: "failed outside any test (a beforeAll hook, for example); Vitest's JSON report has no message for it, so run the file with `vitest run <file>` to see the error"
2624
+ };
2625
+ function fileFailure(file, runner) {
2626
+ return file.message || BROKEN_WITHOUT_MESSAGE[runner];
2627
+ }
2628
+ function notRunSide(file, runner) {
2629
+ return {
2630
+ status: "failed",
2631
+ rawStatus: "not run",
2632
+ message: fileFailure(file, runner),
2633
+ notRun: "file-failed"
2634
+ };
2635
+ }
2636
+ /**
2637
+ * A Jest pass that Vitest confirms: Vitest passed it, at least as many times as Jest ran
2638
+ * it. Fewer copies means a Jest project (a platform, say) did not run under Vitest.
2639
+ */
2640
+ function isConfirmed(e) {
2641
+ return e.matchedBy !== "shape" && e.jest?.status === "passed" && e.vitest?.status === "passed" && (e.vitest.copies ?? 1) >= (e.jest.copies ?? 1);
2642
+ }
2643
+ function bucketOf(j, v) {
2644
+ if (j === v) return j === "passed" ? "same-pass" : j === "failed" ? "same-fail" : "same-skip";
2645
+ if (j === "skipped" || v === "skipped") return "skip-difference";
2646
+ return j === "passed" ? "regression" : "improvement";
2647
+ }
2648
+ function summary(file, runner) {
2649
+ return {
2650
+ file: file.file,
2651
+ status: file.status,
2652
+ tests: file.tests.length,
2653
+ message: file.broken ? fileFailure(file, runner) : null
2654
+ };
2655
+ }
2656
+ /**
2657
+ * The end of a printed string that starts at `start`: the index of its closing `"`, or -1.
2658
+ * Jest's pretty-format prints a string `%p` value in double quotes, escaping `"` and `\`
2659
+ * inside it. Only a quote that ends the token (followed by the end, whitespace or
2660
+ * punctuation) closes it, so a lone `"` in ordinary text does not start a value.
2661
+ */
2662
+ function printedStringEnd(title, start) {
2663
+ for (let j = start + 1; j < title.length; j++) {
2664
+ if (title[j] === "\\") {
2665
+ j++;
2666
+ continue;
2667
+ }
2668
+ if (title[j] === "\"") return /^($|[\s,;:)\]}])/.test(title.slice(j + 1)) ? j : -1;
2669
+ }
2670
+ return -1;
2671
+ }
2672
+ /**
2673
+ * A title as words, balanced `{…}` / `[…]` groups and double-quoted strings (printed
2674
+ * values), in order. A printed string is one token however many words it holds, so it
2675
+ * lines up with Vitest's literal `%p` for the same value.
2676
+ */
2677
+ function titleTokens(title) {
2678
+ const tokens = [];
2679
+ let word = "";
2680
+ const flush = () => {
2681
+ if (word) tokens.push(word);
2682
+ word = "";
2683
+ };
2684
+ for (let i = 0; i < title.length; i++) {
2685
+ const c = title[i];
2686
+ const stringEnd = c === "\"" && word === "" ? printedStringEnd(title, i) : -1;
2687
+ if (stringEnd !== -1) {
2688
+ let end = stringEnd + 1;
2689
+ while (end < title.length && !/\s/.test(title[end])) end++;
2690
+ tokens.push(title.slice(i, end));
2691
+ i = end - 1;
2692
+ continue;
2693
+ }
2694
+ if (c === "{" || c === "[") {
2695
+ flush();
2696
+ let depth = 0;
2697
+ let j = i;
2698
+ for (; j < title.length; j++) {
2699
+ if (title[j] === "{" || title[j] === "[") depth++;
2700
+ else if (title[j] === "}" || title[j] === "]") depth--;
2701
+ if (depth === 0) break;
2702
+ }
2703
+ tokens.push(title.slice(i, j + 1));
2704
+ i = j;
2705
+ } else if (/\s/.test(c)) flush();
2706
+ else word += c;
2707
+ }
2708
+ flush();
2709
+ return tokens;
2710
+ }
2711
+ const isGroup = (t) => t.startsWith("{") || t.startsWith("[");
2712
+ /** A printed value without what the two printers do differently: spaces, quotes, trailing commas. */
2713
+ const canonicalValue = (t) => t.replace(/\s+/g, "").replace(/["']/g, "").replace(/,([}\]])/g, "$1");
2714
+ /**
2715
+ * Whether Jest's printed value and Vitest's are the same value. Jest (pretty-format and
2716
+ * util.format at depth 1) prints `{"a": 1}` and `{ a: 1, b: [Array] }`; Vitest prints
2717
+ * `{ a: 1 }` and `{ a: 1, b: [ 1, 2 ] }`. Jest's `[Array]` / `[Object]` stand for any
2718
+ * array or object at that place.
2719
+ */
2720
+ function sameValue(jest, vitest) {
2721
+ const pattern = canonicalValue(jest).replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\[Array\\\]/g, "\\[.*?\\]").replace(/\\\[Object\\\]/g, "\\{.*?\\}");
2722
+ return new RegExp(`^${pattern}$`).test(canonicalValue(vitest));
2723
+ }
2724
+ /**
2725
+ * A title with its printed values normalised and nothing else. Inside each balanced
2726
+ * `{…}` / `[…]` value (titleTokens' groups), quote style is unified (`'` and `"` become
2727
+ * one; quotes are kept), whitespace runs collapse to one space, and a trailing comma goes:
2728
+ * the printers differ there. Text outside printed values is kept verbatim, so `it's on`
2729
+ * and `it"s on`, or `a , b` and `a, b`, are different titles.
2730
+ */
2731
+ function normalTitle(t) {
2732
+ let out = "";
2733
+ for (let i = 0; i < t.length; i++) {
2734
+ const c = t[i];
2735
+ if (c !== "{" && c !== "[") {
2736
+ out += c;
2737
+ continue;
2738
+ }
2739
+ let depth = 0;
2740
+ let j = i;
2741
+ for (; j < t.length; j++) {
2742
+ if (t[j] === "{" || t[j] === "[") depth++;
2743
+ else if (t[j] === "}" || t[j] === "]") depth--;
2744
+ if (depth === 0) break;
2745
+ }
2746
+ out += t.slice(i, j + 1).replace(/'/g, "\"").replace(/\s+/g, " ").replace(/,\s*([}\]])/g, "$1");
2747
+ i = j;
2748
+ }
2749
+ return out;
2750
+ }
2751
+ /**
2752
+ * Whether Vitest's token `b` is literal `%p`s standing in for Jest's printed values in `a`.
2753
+ * Punctuation stays attached to a token, so `%p,` stands for `0,`, `(%p)` for `(1)` and
2754
+ * `%p,%p` for `"",""`: the text around and between the `%p`s must appear in `a` as it is,
2755
+ * and each `%p` must stand for something.
2756
+ */
2757
+ function stoodInForBy(a, b) {
2758
+ if (!b.includes("%p")) return false;
2759
+ const literal = b.split("%p").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
2760
+ return new RegExp(`^${literal.join("(.+)")}$`, "s").test(a);
2761
+ }
2762
+ /**
2763
+ * Whether two titles have the same shape: equal except where the runners are known to
2764
+ * print a parametrised title (`it.each`) differently, each of which can hide a different
2765
+ * value: a printed object or array (quotes and Jest's `[Array]` / `[Object]` ignored),
2766
+ * Vitest's literal `%p` for one value, Jest's `$var` against Vitest's `undefined`, and
2767
+ * the `undefined` Vitest appends after `%%`.
2768
+ */
2769
+ function sameShape(jest, vitest) {
2770
+ const j = titleTokens(jest);
2771
+ const v = titleTokens(vitest);
2772
+ let i = 0;
2773
+ for (; i < j.length; i++) {
2774
+ const a = j[i];
2775
+ const b = v[i];
2776
+ if (b === void 0) return false;
2777
+ if (a === b) continue;
2778
+ if (isGroup(a) && isGroup(b) && sameValue(a, b)) continue;
2779
+ if (stoodInForBy(a, b)) continue;
2780
+ if (/^\$[A-Za-z_$][\w$]*(?:\.[\w$]+)*$/.test(a) && b === "undefined") continue;
2781
+ return false;
2782
+ }
2783
+ const rest = v.slice(i);
2784
+ return rest.length === 0 || jest.includes("%") && rest.every((t) => t === "undefined");
2785
+ }
2786
+ /**
2787
+ * Whether the titles differ only where Vitest left `%p` unformatted: the same number of
2788
+ * tokens, each equal or a `%p` (with what surrounds it) standing in for Jest's value.
2789
+ */
2790
+ function onlyPlaceholders(jest, vitest) {
2791
+ const j = titleTokens(jest);
2792
+ const v = titleTokens(vitest);
2793
+ return j.length === v.length && j.some((a, i) => a !== v[i]) && j.every((a, i) => a === v[i] || stoodInForBy(a, v[i]));
2794
+ }
2795
+ /**
2796
+ * How a Jest title matches a Vitest title, or null.
2797
+ *
2798
+ * - `same`: identical once quote style, whitespace and trailing commas are normalised
2799
+ * (normalTitle). The same test; it confirms a Jest pass.
2800
+ * - `placeholder`: equal except where Vitest printed a literal `%p` (onlyPlaceholders).
2801
+ * Vitest did not format the title at all, so it hides nothing Jest's print shows; the
2802
+ * pair confirms only when classify pairs the rows one to one, in order (see there).
2803
+ * - `shape`: equal only once a printed value is ignored (sameShape). Possibly the same
2804
+ * test printed differently, possibly a different row (`allows { user: [Object] }` is
2805
+ * Jest's print of any user). Listed for review, and never confirms a Jest pass.
2806
+ */
2807
+ function titleMatch(jest, vitest) {
2808
+ if (normalTitle(jest) === normalTitle(vitest)) return "same";
2809
+ if (onlyPlaceholders(jest, vitest)) return "placeholder";
2810
+ return sameShape(jest, vitest) ? "shape" : null;
2811
+ }
2812
+ const SNAPSHOT_MISMATCH = /Snapshot `[^`]*` mismatched/;
2813
+ function classify(jest, vitest, options = {}) {
2814
+ const entries = [];
2815
+ const onlyJest = [];
2816
+ const onlyVitest = [];
2817
+ const allFiles = [.../* @__PURE__ */ new Set([...jest.files.keys(), ...vitest.files.keys()])].sort();
2818
+ for (const file of allFiles) {
2819
+ const jf = jest.files.get(file);
2820
+ const vf = vitest.files.get(file);
2821
+ if (!jf || !vf) {
2822
+ const present = jf ?? vf;
2823
+ const runner = jf ? "jest" : "vitest";
2824
+ (jf ? onlyJest : onlyVitest).push(summary(present, runner));
2825
+ for (const g of grouped(present.tests).values()) entries.push({
2826
+ bucket: jf ? "only-jest" : "only-vitest",
2827
+ file,
2828
+ ancestors: g.ancestors,
2829
+ title: g.title,
2830
+ jest: jf ? aggregate(g) : null,
2831
+ vitest: vf ? aggregate(g) : null
2832
+ });
2833
+ continue;
2834
+ }
2835
+ const jg = grouped(jf.tests);
2836
+ const vg = grouped(vf.tests);
2837
+ const unmatched = {
2838
+ jest: /* @__PURE__ */ new Map(),
2839
+ vitest: /* @__PURE__ */ new Map()
2840
+ };
2841
+ const pairs = [];
2842
+ for (const key of /* @__PURE__ */ new Set([...jg.keys(), ...vg.keys()])) {
2843
+ const a = jg.get(key);
2844
+ const b = vg.get(key);
2845
+ if (a && !b && !vf.broken) {
2846
+ const block = JSON.stringify(a.ancestors);
2847
+ unmatched.jest.set(block, [...unmatched.jest.get(block) ?? [], a]);
2848
+ } else if (b && !a && !jf.broken) {
2849
+ const block = JSON.stringify(b.ancestors);
2850
+ const rows = b.title.includes("%p") && b.tests.length > 1 ? b.tests.map((t) => ({
2851
+ ancestors: b.ancestors,
2852
+ title: b.title,
2853
+ tests: [t]
2854
+ })) : [b];
2855
+ unmatched.vitest.set(block, [...unmatched.vitest.get(block) ?? [], ...rows]);
2856
+ } else pairs.push({
2857
+ a,
2858
+ b
2859
+ });
2860
+ }
2861
+ const at = (tests) => (g) => tests.indexOf(g.tests[0]);
2862
+ for (const [block, groups] of unmatched.jest) {
2863
+ const vs = unmatched.vitest.get(block) ?? [];
2864
+ if (!vs.some((b) => b.title.includes("%p"))) continue;
2865
+ const rows = groups.flatMap((a) => a.tests.length > 1 ? a.tests.map((t) => ({
2866
+ ...a,
2867
+ tests: [t]
2868
+ })) : [a]);
2869
+ unmatched.jest.set(block, rows.sort((x, y) => at(jf.tests)(x) - at(jf.tests)(y)));
2870
+ unmatched.vitest.set(block, [...vs].sort((x, y) => at(vf.tests)(x) - at(vf.tests)(y)));
2871
+ }
2872
+ for (const [block, js] of unmatched.jest) {
2873
+ const vs = unmatched.vitest.get(block) ?? [];
2874
+ const left = [];
2875
+ const oneToOne = options.ordered !== false && js.length === vs.length;
2876
+ js.forEach((a, i) => {
2877
+ const b = vs[i];
2878
+ let match = b ? titleMatch(a.title, b.title) : null;
2879
+ if (match === "placeholder" && !oneToOne) match = "shape";
2880
+ if (b && match) {
2881
+ pairs.push({
2882
+ a,
2883
+ b,
2884
+ vitestTitle: b.title,
2885
+ matchedBy: match
2886
+ });
2887
+ vs[i] = void 0;
2888
+ } else pairs.push({
2889
+ a,
2890
+ b: void 0,
2891
+ vitestCandidate: b?.title
2892
+ });
2893
+ });
2894
+ for (const b of vs) if (b) left.push(b);
2895
+ unmatched.vitest.set(block, left);
2896
+ }
2897
+ for (const vs of unmatched.vitest.values()) for (const b of vs) pairs.push({
2898
+ a: void 0,
2899
+ b
2900
+ });
2901
+ for (const { a, b, vitestTitle, matchedBy, vitestCandidate } of pairs) {
2902
+ const ref = a ?? b;
2903
+ let j = a ? aggregate(a) : jf.broken ? notRunSide(jf, "jest") : null;
2904
+ let v = b ? aggregate(b) : vf.broken ? notRunSide(vf, "vitest") : null;
2905
+ if (j && v && j.status === "skipped" && v.status !== "skipped" && jf.broken) j = notRunSide(jf, "jest");
2906
+ if (j && v && v.status === "skipped" && j.status !== "skipped" && vf.broken) v = notRunSide(vf, "vitest");
2907
+ const bucket = j && v ? bucketOf(j.status, v.status) : j ? "only-jest" : "only-vitest";
2908
+ const entry = {
2909
+ bucket,
2910
+ file,
2911
+ ancestors: ref.ancestors,
2912
+ title: ref.title,
2913
+ jest: j,
2914
+ vitest: v
2915
+ };
2916
+ if (vitestTitle !== void 0 && vitestTitle !== ref.title) entry.vitestTitle = vitestTitle;
2917
+ if (matchedBy === "shape") entry.matchedBy = "shape";
2918
+ else if (matchedBy === "placeholder") entry.matchedBy = "position";
2919
+ if (vitestCandidate !== void 0 && !v) entry.vitestCandidate = vitestCandidate;
2920
+ const message = v?.message ?? "";
2921
+ if (bucket === "regression" && options.snapshotHint && SNAPSHOT_MISMATCH.test(message)) {
2922
+ const hint = options.snapshotHint(file, message);
2923
+ if (hint) entry.hint = hint;
2924
+ }
2925
+ entries.push(entry);
2926
+ }
2927
+ }
2928
+ const counts = Object.fromEntries(BUCKETS.map((b) => [b, 0]));
2929
+ for (const e of entries) counts[e.bucket]++;
2930
+ const total = (r) => {
2931
+ const t = {
2932
+ files: r.files.size,
2933
+ tests: 0,
2934
+ passed: 0,
2935
+ failed: 0,
2936
+ skipped: 0
2937
+ };
2938
+ for (const f of r.files.values()) for (const test of f.tests) {
2939
+ t.tests++;
2940
+ t[test.status]++;
2941
+ }
2942
+ return t;
2943
+ };
2944
+ const jestPassed = entries.filter((e) => e.jest?.status === "passed").length;
2945
+ const confirmed = entries.filter(isConfirmed).length;
2946
+ const confirmedByPosition = entries.filter((e) => isConfirmed(e) && e.matchedBy === "position").length;
2947
+ const broken = (r) => [...r.files.values()].filter((f) => f.broken).map((f) => summary(f, r.runner));
2948
+ const brokenVitest = broken(vitest);
2949
+ const vitestFailing = entries.filter((e) => e.vitest?.status === "failed");
2950
+ const derivedExit = vitestFailing.length || brokenVitest.length ? 1 : 0;
2951
+ const run = options.vitestRun ?? {
2952
+ exitCode: derivedExit,
2953
+ errors: [],
2954
+ engine: null
2955
+ };
2956
+ const problems = [];
2957
+ if (run.exitCode !== 0) {
2958
+ if (vitestFailing.length) {
2959
+ const by = (bucket) => vitestFailing.filter((e) => e.bucket === bucket).length;
2960
+ const parts = [
2961
+ [by("regression"), "pass under Jest"],
2962
+ [by("same-fail"), "fail under Jest too"],
2963
+ [by("only-vitest"), "Jest did not run"]
2964
+ ].filter(([n]) => n > 0);
2965
+ problems.push(`${vitestFailing.length} ${vitestFailing.length === 1 ? "test fails" : "tests fail"} under Vitest` + (parts.length ? ` (${parts.map(([n, what]) => `${n} ${what}`).join(", ")})` : ""));
2966
+ }
2967
+ for (const f of brokenVitest.filter((b) => b.tests === 0 && !jest.files.get(b.file)?.broken)) problems.push(`${f.file} fails to load under Vitest: ${firstLine(f.message)}`);
2968
+ problems.push(...run.errors);
2969
+ if (!problems.length) problems.push(`Vitest exited ${run.exitCode ?? "by a signal"} although its JSON report shows no failure (a globalSetup teardown, process.exit, or an error outside any test); run \`vitest run\` to see it`);
2970
+ }
2971
+ return {
2972
+ entries,
2973
+ counts,
2974
+ files: {
2975
+ onlyJest,
2976
+ onlyVitest,
2977
+ brokenJest: broken(jest),
2978
+ brokenVitest
2979
+ },
2980
+ totals: {
2981
+ jest: total(jest),
2982
+ vitest: total(vitest)
2983
+ },
2984
+ jestPassed,
2985
+ confirmed,
2986
+ confirmedByPosition,
2987
+ vitest: {
2988
+ ...run,
2989
+ problems,
2990
+ ignoredErrors: run.exitCode === 0 ? run.errors : []
2991
+ },
2992
+ claimHolds: jestPassed > 0 && confirmed === jestPassed && run.exitCode === 0
2993
+ };
2994
+ }
2995
+ const SNAPSHOT_HINTS = {
2996
+ "no-vitest-snapshot": "no Vitest snapshot recorded. Give Vitest its own snapshot directory first (the resolveSnapshotPath recipe at https://danfry1.github.io/vitest-native/migration/from-jest#snapshots), so recording cannot rewrite Jest's .snap files; then run `vitest run` once and review the new files",
2997
+ "shared-snapshot-dir": "your Vitest config resolves snapshots to Jest's .snap files. This snapshot's key is the same in both runners, but Vitest rewrites the header of a Jest .snap file it reads, so compare does not let it read Jest's. Give Vitest its own directory (the resolveSnapshotPath recipe at https://danfry1.github.io/vitest-native/migration/from-jest#snapshots) and record there",
2998
+ "shared-snapshot-dir-nested": "your Vitest config resolves snapshots to Jest's .snap files. Vitest names this snapshot differently (`a > b 1`, where Jest writes `a b 1`), so it would not find Jest's entry, and it rewrites the header of a Jest .snap file it reads. Give Vitest its own directory (the resolveSnapshotPath recipe at https://danfry1.github.io/vitest-native/migration/from-jest#snapshots) and record there"
2999
+ };
3000
+ /** Entries grouped by the first line of the given side's message, largest group first. */
3001
+ function clusters(entries, by) {
3002
+ const groups = /* @__PURE__ */ new Map();
3003
+ for (const e of entries) {
3004
+ const key = e.hint ? SNAPSHOT_HINTS[e.hint] : firstLine(e[by]?.message ?? null);
3005
+ const group = groups.get(key) ?? {
3006
+ message: key,
3007
+ count: 0,
3008
+ tests: []
3009
+ };
3010
+ group.count++;
3011
+ group.tests.push({
3012
+ file: e.file,
3013
+ ancestors: e.ancestors,
3014
+ title: e.title
3015
+ });
3016
+ groups.set(key, group);
3017
+ }
3018
+ return [...groups.values()].sort((a, b) => b.count - a.count || a.message.localeCompare(b.message));
3019
+ }
3020
+ function testName(t) {
3021
+ return [
3022
+ t.file,
3023
+ ...t.ancestors,
3024
+ t.title
3025
+ ].join(" › ");
3026
+ }
3027
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
3028
+ function totalsLine(t) {
3029
+ return `${plural(t.files, "file")}, ${plural(t.tests, "test")} (${t.passed} passed, ${t.failed} failed, ${t.skipped} skipped)`;
3030
+ }
3031
+ /** Jest-passing tests that Vitest does not confirm (isConfirmed), by why. */
3032
+ function unconfirmed(c) {
3033
+ const out = {
3034
+ failed: [],
3035
+ skipped: [],
3036
+ fewer: [],
3037
+ shape: [],
3038
+ renamed: [],
3039
+ missing: []
3040
+ };
3041
+ for (const e of c.entries) {
3042
+ if (e.jest?.status !== "passed" || isConfirmed(e)) continue;
3043
+ if (!e.vitest) out[e.vitestCandidate !== void 0 ? "renamed" : "missing"].push(e);
3044
+ else if (e.vitest.status === "failed") out.failed.push(e);
3045
+ else if (e.vitest.status === "skipped") out.skipped.push(e);
3046
+ else if (e.matchedBy === "shape") out.shape.push(e);
3047
+ else out.fewer.push(e);
3048
+ }
3049
+ return out;
3050
+ }
3051
+ const UNCONFIRMED_LABELS = {
3052
+ failed: "fail",
3053
+ skipped: "skipped",
3054
+ fewer: "run fewer times (a Jest project missing)",
3055
+ shape: "matched only by title shape",
3056
+ renamed: "named differently",
3057
+ missing: "not collected"
3058
+ };
3059
+ function engineLabel(engine) {
3060
+ return engine ? `engine: ${engine}` : "no vitest-native engine reported";
3061
+ }
3062
+ function renderComparison(c, options) {
3063
+ const lines = [];
3064
+ const top = Math.max(1, options.top);
3065
+ const label = (r, name) => `${name} ${r.version ?? "(version unknown)"}`.padEnd(15);
3066
+ lines.push(`Jest ${label(options.jest, "jest")} ${totalsLine(c.totals.jest)} — config: ${options.jest.config}`, `Vitest ${label(options.vitest, "vitest")} ${totalsLine(c.totals.vitest)} — config: ${options.vitest.config}`, "");
3067
+ const gap = unconfirmed(c);
3068
+ const engine = engineLabel(c.vitest.engine);
3069
+ if (c.jestPassed === 0) lines.push("✗ No test passed under Jest, so there is nothing to compare against.");
3070
+ else if (c.claimHolds && options.projectChanged) lines.push(`✗ All ${plural(c.jestPassed, "test")} that pass under Jest also pass under Vitest (${engine}), but the runs changed files in the project (listed below), so the comparison does not count.`);
3071
+ else if (c.claimHolds) lines.push(`✓ All ${plural(c.jestPassed, "test")} that pass under Jest also pass under Vitest (${engine}), and \`vitest run\` exits 0.`);
3072
+ else if (c.confirmed === c.jestPassed) lines.push(`✗ \`vitest run\` exits ${c.vitest.exitCode ?? "by a signal"} (${engine}), although all ${plural(c.jestPassed, "test")} that pass under Jest also pass under Vitest:`);
3073
+ else {
3074
+ const why = Object.keys(UNCONFIRMED_LABELS).filter((k) => gap[k].length > 0).map((k) => `${gap[k].length} ${UNCONFIRMED_LABELS[k]}`);
3075
+ lines.push(`✗ ${c.jestPassed - c.confirmed} of the ${plural(c.jestPassed, "test")} that pass under Jest do not pass under Vitest (${engine}): ${why.join(", ")}.`);
3076
+ if (gap.shape.length) lines.push(`✗ ${plural(gap.shape.length, "test")} could only be matched by title shape; check them (Jest prints values differently, so a different row can look the same).`);
3077
+ }
3078
+ if (c.confirmedByPosition) lines.push(`! ${plural(c.confirmedByPosition, "test")} confirmed by row position only: Vitest printed \`%p\` instead of the value, so each was paired with the Jest row at its place in the table, not by its data. A table built differently under the two runners would pair wrong rows.`);
3079
+ if (!c.vitest.engine) lines.push("! Vitest reported no vitest-native engine: is reactNative() in this Vitest config?");
3080
+ if (c.vitest.problems.length) {
3081
+ if (c.confirmed !== c.jestPassed || c.jestPassed === 0) lines.push(`✗ \`vitest run\` exits ${c.vitest.exitCode ?? "by a signal"}:`);
3082
+ for (const p of c.vitest.problems.slice(0, top)) lines.push(` ${p}`);
3083
+ if (c.vitest.problems.length > top) lines.push(` … and ${c.vitest.problems.length - top} more (see --json)`);
3084
+ }
3085
+ if (c.vitest.ignoredErrors.length) {
3086
+ lines.push("! Vitest printed these errors but exited 0 (its config ignores unhandled errors):");
3087
+ for (const e of c.vitest.ignoredErrors.slice(0, top)) lines.push(` ${e}`);
3088
+ }
3089
+ lines.push("");
3090
+ const n = c.counts;
3091
+ const row = (mark, name, count, note) => lines.push(` ${mark} ${name.padEnd(22)} ${String(count).padStart(5)} ${note}`);
3092
+ row(" ", "same result", n["same-pass"] + n["same-fail"] + n["same-skip"], `${n["same-pass"]} pass, ${n["same-fail"]} fail, ${n["same-skip"]} skipped in both`);
3093
+ row(n.regression ? "✗" : " ", "regressions", n.regression, "pass under Jest, fail under Vitest — fix these first");
3094
+ row(" ", "improvements", n.improvement, "fail under Jest, pass under Vitest");
3095
+ row(n["skip-difference"] ? "~" : " ", "skipped differently", n["skip-difference"], "skipped by one runner, run by the other");
3096
+ row(n["only-jest"] ? "!" : " ", "only under Jest", n["only-jest"], "no Vitest result: its file or the test was not collected");
3097
+ row(n["only-vitest"] ? "!" : " ", "only under Vitest", n["only-vitest"], "no Jest result");
3098
+ lines.push("");
3099
+ const fileList = (title, files) => {
3100
+ if (!files.length) return;
3101
+ lines.push(`${title} (${files.length}):`);
3102
+ for (const f of files.slice(0, top)) {
3103
+ const why = f.message ? ` — ${firstLine(f.message)}` : "";
3104
+ lines.push(` ${f.file} (${plural(f.tests, "test")}, ${f.status})${why}`);
3105
+ }
3106
+ if (files.length > top) lines.push(` … and ${files.length - top} more (see --json)`);
3107
+ lines.push("");
3108
+ };
3109
+ fileList("! Test files only Jest collected", c.files.onlyJest);
3110
+ fileList("! Test files only Vitest collected", c.files.onlyVitest);
3111
+ fileList("✗ Test files that failed outside any test under Vitest", c.files.brokenVitest);
3112
+ const regressions = c.entries.filter((e) => e.bucket === "regression");
3113
+ if (regressions.length) {
3114
+ const groups = clusters(regressions, "vitest");
3115
+ lines.push(`Regressions by first Vitest error (top ${Math.min(top, groups.length)} of ${groups.length}):`);
3116
+ for (const g of groups.slice(0, top)) {
3117
+ lines.push(` ${g.count}× ${g.message}`);
3118
+ for (const t of g.tests.slice(0, 3)) lines.push(` ${testName(t)}`);
3119
+ if (g.tests.length > 3) lines.push(` … and ${g.tests.length - 3} more`);
3120
+ }
3121
+ lines.push("");
3122
+ }
3123
+ const testList = (title, list, describe = testName) => {
3124
+ if (!list.length) return;
3125
+ lines.push(`${title} (${list.length}):`);
3126
+ for (const e of list.slice(0, top)) lines.push(` ${describe(e)}`);
3127
+ if (list.length > top) lines.push(` … and ${list.length - top} more (see --json)`);
3128
+ lines.push("");
3129
+ };
3130
+ testList("Skipped under Vitest, passed under Jest", c.entries.filter((e) => e.bucket === "skip-difference" && e.jest?.status === "passed"));
3131
+ testList("Matched by position: the same test, its title formatted differently by each runner (Jest ⇄ Vitest)", c.entries.filter((e) => e.vitestTitle !== void 0 && e.matchedBy !== "shape"), (e) => `${testName(e)} ⇄ ${e.vitestTitle}`);
3132
+ testList("Matched by title shape — review: equal only if the values Jest and Vitest print are (unconfirmed)", c.entries.filter((e) => e.matchedBy === "shape"), (e) => `${testName(e)} ~ ${e.vitestTitle ?? e.title}`);
3133
+ testList("Named differently? Jest's test has no Vitest test of that name; at its place Vitest has another (unconfirmed)", c.entries.filter((e) => e.vitestCandidate !== void 0), (e) => `${testName(e)} ≠ ${e.vitestCandidate}`);
3134
+ const collected = new Set([...c.files.onlyJest, ...c.files.onlyVitest].map((f) => f.file));
3135
+ testList("Tests only Jest reported, in files both ran", c.entries.filter((e) => e.bucket === "only-jest" && !collected.has(e.file)));
3136
+ testList("Tests only Vitest reported, in files both ran", c.entries.filter((e) => e.bucket === "only-vitest" && !collected.has(e.file)));
3137
+ testList("Reported a different number of times (projects or repeated titles; each passes only if every copy passed)", c.entries.filter((e) => (e.jest?.copies ?? 1) !== (e.vitest?.copies ?? 1) && e.jest && e.vitest), (e) => `${testName(e)} (Jest ${e.jest?.copies ?? 1}×, Vitest ${e.vitest?.copies ?? 1}×)`);
3138
+ lines.push(options.jsonPath ? `Report: ${options.jsonPath} — test names, statuses and error messages, with stack traces, code frames and absolute paths removed. Read it before attaching it to an issue: a message can still contain whatever a test put in its error.` : "Write a report to attach to an issue with --json <file>.");
3139
+ return lines;
3140
+ }
3141
+ /** The `--json` report: identities, statuses and messages. */
3142
+ function jsonReport(c, meta) {
3143
+ const listed = c.entries.filter((e) => e.bucket !== "same-pass" && e.bucket !== "same-skip" || e.vitestTitle !== void 0);
3144
+ return {
3145
+ format: "vitest-native-compare@1",
3146
+ about: "One run of a suite under Jest and one under Vitest: test identities (file relative to the project root, describe titles, title), statuses and error messages. Stack traces, code frames and absolute paths (<root>, <tmp>, ~, <path>) are removed from messages; a message can still contain whatever a test put in its error. Tests with the same result under both runners are counted, not listed, except failures.",
3147
+ tool: {
3148
+ vitestNative: meta.vitestNative,
3149
+ node: process.version,
3150
+ platform: process.platform
3151
+ },
3152
+ runners: {
3153
+ jest: meta.jest,
3154
+ vitest: meta.vitest
3155
+ },
3156
+ verdict: {
3157
+ claim: "every test that passes under Jest also passes under Vitest, and `vitest run` exits 0",
3158
+ holds: c.claimHolds,
3159
+ jestPassed: c.jestPassed,
3160
+ confirmed: c.confirmed,
3161
+ confirmedByPosition: c.confirmedByPosition,
3162
+ vitestExitCode: c.vitest.exitCode,
3163
+ vitestProblems: c.vitest.problems,
3164
+ vitestIgnoredErrors: c.vitest.ignoredErrors,
3165
+ engine: c.vitest.engine
3166
+ },
3167
+ totals: c.totals,
3168
+ counts: c.counts,
3169
+ files: c.files,
3170
+ clusters: { regression: clusters(listed.filter((e) => e.bucket === "regression"), "vitest") },
3171
+ tests: listed.map((e) => ({
3172
+ bucket: e.bucket,
3173
+ file: e.file,
3174
+ ancestors: e.ancestors,
3175
+ title: e.title,
3176
+ ...e.vitestTitle !== void 0 ? { vitestTitle: e.vitestTitle } : {},
3177
+ ...e.matchedBy ? { matchedBy: e.matchedBy } : {},
3178
+ ...e.vitestCandidate !== void 0 ? { vitestCandidate: e.vitestCandidate } : {},
3179
+ jest: e.jest,
3180
+ vitest: e.vitest,
3181
+ ...e.hint ? { hint: e.hint } : {}
3182
+ }))
3183
+ };
3184
+ }
3185
+ // src/cli/compare-run.ts
3186
+ /**
3187
+ * `vitest-native compare`: the half that runs things. It runs the project's own Jest and
3188
+ * Vitest one after the other, each a bounded child process, and hands their JSON reports
3189
+ * to compare.ts. See docs/compare-mode.md.
3190
+ */
3191
+ /** Split an argument string into words: whitespace separates, quotes group. */
3192
+ function splitArgs(value) {
3193
+ const words = [];
3194
+ let word = null;
3195
+ for (let i = 0; i < value.length; i++) {
3196
+ const c = value[i];
3197
+ if (c === "'" || c === "\"") {
3198
+ const close = value.indexOf(c, i + 1);
3199
+ const stop = close === -1 ? value.length : close;
3200
+ word = (word ?? "") + value.slice(i + 1, stop);
3201
+ i = stop;
3202
+ } else if (/\s/.test(c)) {
3203
+ if (word !== null) words.push(word);
3204
+ word = null;
3205
+ } else word = (word ?? "") + c;
3206
+ }
3207
+ if (word !== null) words.push(word);
3208
+ return words;
3209
+ }
3210
+ /**
3211
+ * The runner arguments compare passes through. Anything else is refused: a deny-list
3212
+ * let `-ut .` (Vitest's -u inside a cluster of short flags) and Jest's `--ci false`
3213
+ * through, and both write snapshots. Positional arguments (path filters) are allowed.
3214
+ */
3215
+ const JEST_ARGS = {
3216
+ long: {
3217
+ maxWorkers: "value",
3218
+ testTimeout: "value",
3219
+ runInBand: "flag",
3220
+ selectProjects: "value",
3221
+ testNamePattern: "value",
3222
+ testPathPatterns: "value",
3223
+ testPathPattern: "value",
3224
+ testPathIgnorePatterns: "value",
3225
+ shard: "value",
3226
+ silent: "flag",
3227
+ forceExit: "flag",
3228
+ detectOpenHandles: "flag",
3229
+ logHeapUsage: "flag",
3230
+ workerIdleMemoryLimit: "value",
3231
+ passWithNoTests: "flag",
3232
+ randomize: "flag",
3233
+ seed: "value",
3234
+ maxConcurrency: "value",
3235
+ watchAll: "false-only",
3236
+ watch: "false-only",
3237
+ cache: "flag",
3238
+ clearMocks: "flag",
3239
+ config: "value",
3240
+ watchman: "flag",
3241
+ verbose: "flag",
3242
+ bail: "optional",
3243
+ coverage: "false-only"
3244
+ },
3245
+ short: {
3246
+ i: "flag",
3247
+ w: "value",
3248
+ t: "value",
3249
+ c: "value"
3250
+ }
3251
+ };
3252
+ const VITEST_ARGS = {
3253
+ long: {
3254
+ maxWorkers: "value",
3255
+ testTimeout: "value",
3256
+ hookTimeout: "value",
3257
+ teardownTimeout: "value",
3258
+ project: "value",
3259
+ testNamePattern: "value",
3260
+ shard: "value",
3261
+ pool: "value",
3262
+ silent: "flag",
3263
+ mode: "value",
3264
+ passWithNoTests: "flag",
3265
+ fileParallelism: "flag",
3266
+ isolate: "flag",
3267
+ retry: "value",
3268
+ dir: "value",
3269
+ logHeapUsage: "flag",
3270
+ watch: "false-only",
3271
+ root: "value",
3272
+ "coverage.enabled": "false-only",
3273
+ coverage: "false-only",
3274
+ bail: "value",
3275
+ allowOnly: "flag",
3276
+ "sequence.shuffle": "flag"
3277
+ },
3278
+ short: { t: "value" }
3279
+ };
3280
+ const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
3281
+ /** The first argument the spec does not allow, with why, or null. */
3282
+ function refusedArg(args, spec) {
3283
+ for (let i = 0; i < args.length; i++) {
3284
+ const arg = args[i];
3285
+ if (!arg.startsWith("-")) continue;
3286
+ if (arg.startsWith("--")) {
3287
+ const [rawName, inline] = arg.slice(2).split(/=(.*)/s, 2);
3288
+ let name = camel(rawName);
3289
+ let negated = false;
3290
+ if (!(name in spec.long) && name.startsWith("no") && /^no[A-Z]/.test(name)) {
3291
+ name = name[2].toLowerCase() + name.slice(3);
3292
+ negated = true;
3293
+ }
3294
+ const kind = spec.long[name];
3295
+ if (!kind) return arg;
3296
+ if (kind === "value") {
3297
+ if (negated) return arg;
3298
+ if (inline === void 0) {
3299
+ if (args[i + 1] === void 0) return `${arg} (no value)`;
3300
+ i++;
3301
+ }
3302
+ } else if (kind === "optional") {
3303
+ if (negated) return arg;
3304
+ } else if (kind === "false-only") {
3305
+ if (!(negated || inline === "false")) return arg;
3306
+ } else if (inline !== void 0 && inline !== "true" && inline !== "false") return arg;
3307
+ continue;
3308
+ }
3309
+ const short = arg.slice(1);
3310
+ const kind = spec.short[short];
3311
+ if (!kind) return arg;
3312
+ if (kind === "value") {
3313
+ if (args[i + 1] === void 0) return `${arg} (no value)`;
3314
+ i++;
3315
+ }
3316
+ }
3317
+ return null;
3318
+ }
3319
+ const VALUED = [
3320
+ "root",
3321
+ "jest-args",
3322
+ "vitest-args",
3323
+ "vitest-config",
3324
+ "jest-results",
3325
+ "jest-root",
3326
+ "json",
3327
+ "top",
3328
+ "timeout"
3329
+ ];
3330
+ const COMPARE_VALUED_FLAGS = VALUED.map((f) => `--${f}`);
3331
+ /** compare's switches (no value). */
3332
+ const SWITCHES = ["show-output", "strict"];
3333
+ const COMPARE_SWITCHES = SWITCHES.map((f) => `--${f}`);
3334
+ /** `compare`'s options from argv (after the command), or an error to print. */
3335
+ function parseCompareArgs(argv) {
3336
+ const values = /* @__PURE__ */ new Map();
3337
+ const flags = /* @__PURE__ */ new Set();
3338
+ for (let i = 0; i < argv.length; i++) {
3339
+ const arg = argv[i];
3340
+ if (!arg.startsWith("--")) continue;
3341
+ const [name, inline] = arg.slice(2).split(/=(.*)/s, 2);
3342
+ if (VALUED.includes(name)) {
3343
+ const value = inline ?? argv[++i];
3344
+ if (value === void 0) return { error: `--${name} needs a value.` };
3345
+ values.set(name, value);
3346
+ } else if (SWITCHES.includes(name) || name === "help") flags.add(name);
3347
+ else return { error: `unknown option --${name} for compare. Valid: ` + [
3348
+ ...COMPARE_VALUED_FLAGS,
3349
+ ...COMPARE_SWITCHES,
3350
+ "--help"
3351
+ ].join(", ") + "." };
3352
+ }
3353
+ const jestArgs = splitArgs(values.get("jest-args") ?? "");
3354
+ const vitestArgs = splitArgs(values.get("vitest-args") ?? "");
3355
+ const refusedJest = refusedArg(jestArgs, JEST_ARGS);
3356
+ if (refusedJest) return { error: `--jest-args may not contain ${refusedJest}: compare passes only arguments that cannot write snapshots or replace its reports (see https://danfry1.github.io/vitest-native/guide/cli#compare).` };
3357
+ const refusedVitest = refusedArg(vitestArgs, VITEST_ARGS);
3358
+ if (refusedVitest) return { error: `--vitest-args may not contain ${refusedVitest}: compare passes only arguments that cannot write snapshots or replace its reports or config (name a config with --vitest-config; see https://danfry1.github.io/vitest-native/guide/cli#compare).` };
3359
+ const top = Number(values.get("top") ?? 10);
3360
+ const timeout = Number(values.get("timeout") ?? 1800);
3361
+ if (!Number.isInteger(top) || top < 1) return { error: "--top needs a positive whole number." };
3362
+ if (!Number.isFinite(timeout) || timeout <= 0) return { error: "--timeout needs a number of seconds." };
3363
+ return {
3364
+ root: path.resolve(values.get("root") ?? "."),
3365
+ jestArgs,
3366
+ vitestArgs,
3367
+ vitestConfig: values.get("vitest-config"),
3368
+ jestResults: values.get("jest-results"),
3369
+ jestRoot: values.get("jest-root"),
3370
+ json: values.get("json"),
3371
+ top,
3372
+ timeoutMs: timeout * 1e3,
3373
+ showOutput: flags.has("show-output"),
3374
+ strict: flags.has("strict")
3375
+ };
3376
+ }
3377
+ /**
3378
+ * Runs between compare and each runner: `node -e WATCHDOG -- <cleanup JSON> <runner
3379
+ * args…>`. It starts the runner on compare's pipes and exits with its code. When compare
3380
+ * dies without stopping it (SIGKILL, a crash), the IPC channel disconnects: it stops the
3381
+ * runner, removes compare's temporary directories and kills its own process group,
3382
+ * which holds the runner's workers. On Windows, which has no process groups, it ends
3383
+ * the runner's tree with taskkill, and after the runner exits it stops processes the
3384
+ * runner started that outlived it (orphans keep their parent's id).
3385
+ */
3386
+ const WATCHDOG = `
3387
+ const { spawn, spawnSync } = require("node:child_process");
3388
+ const fs = require("node:fs");
3389
+ const [cleanup, ...args] = process.argv.slice(1);
3390
+ const win = process.platform === "win32";
3391
+ const started = Date.now();
3392
+ const child = spawn(process.execPath, args, { stdio: "inherit", windowsHide: true });
3393
+ let orphaned = false;
3394
+ function reapWindowsOrphans() {
3395
+ if (!win || child.pid === undefined) return;
3396
+ const since = Date.now() - started + 1000;
3397
+ const script =
3398
+ "$t=[DateTime]::Now.AddMilliseconds(-" + since + ");" +
3399
+ "function K($p){Get-CimInstance Win32_Process -Filter \\"ParentProcessId=$p\\" | " +
3400
+ "Where-Object { $_.CreationDate -ge $t } | ForEach-Object { K $_.ProcessId; " +
3401
+ "Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } }; K " + child.pid;
3402
+ spawnSync("powershell", ["-NoProfile", "-NonInteractive", "-Command", script], {
3403
+ stdio: "ignore", windowsHide: true, timeout: 20000,
3404
+ });
3405
+ }
3406
+ function shutdown(code) {
3407
+ if (orphaned) {
3408
+ for (const dir of JSON.parse(cleanup)) {
3409
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
3410
+ }
3411
+ if (!win) { try { process.kill(-process.pid, "SIGKILL"); } catch {} }
3412
+ }
3413
+ process.exit(code);
3414
+ }
3415
+ child.on("exit", (code) => { reapWindowsOrphans(); shutdown(code ?? 1); });
3416
+ child.on("error", () => shutdown(1));
3417
+ process.on("disconnect", () => {
3418
+ orphaned = true;
3419
+ if (win) spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
3420
+ else { try { child.kill("SIGTERM"); } catch {} }
3421
+ setTimeout(() => shutdown(1), 3000).unref();
3422
+ });
3423
+ `;
3424
+ /**
3425
+ * Owns compare's temporary directories for the whole run: `node -e GUARDIAN -- <dirs
3426
+ * JSON> <empty-parents JSON>`, over an IPC channel. When the channel closes — compare
3427
+ * finished, or died between or during runs (SIGKILL included) — it removes the
3428
+ * directories (a no-op after a normal run, which removed them) and exits.
3429
+ */
3430
+ const GUARDIAN = `
3431
+ const fs = require("node:fs");
3432
+ const [dirs, parents] = process.argv.slice(1).map((a) => JSON.parse(a));
3433
+ for (const s of ["SIGINT", "SIGHUP", "SIGTERM"]) process.on(s, () => {});
3434
+ process.on("disconnect", () => {
3435
+ for (const d of dirs) { try { fs.rmSync(d, { recursive: true, force: true }); } catch {} }
3436
+ for (const d of parents) { try { fs.rmdirSync(d); } catch {} }
3437
+ process.exit(0);
3438
+ });
3439
+ `;
3440
+ function startGuardian(dirs, parents) {
3441
+ try {
3442
+ const guardian = spawn(process.execPath, [
3443
+ "-e",
3444
+ GUARDIAN,
3445
+ "--",
3446
+ JSON.stringify(dirs),
3447
+ JSON.stringify(parents)
3448
+ ], {
3449
+ stdio: [
3450
+ "ignore",
3451
+ "ignore",
3452
+ "ignore",
3453
+ "ipc"
3454
+ ],
3455
+ detached: process.platform !== "win32",
3456
+ windowsHide: true
3457
+ });
3458
+ guardian.on("error", () => {});
3459
+ guardian.unref();
3460
+ guardian.channel?.unref?.();
3461
+ return guardian;
3462
+ } catch {
3463
+ return null;
3464
+ }
3465
+ }
3466
+ const SIGNALS = [
3467
+ "SIGINT",
3468
+ "SIGTERM",
3469
+ "SIGHUP"
3470
+ ];
3471
+ /** How long to wait for a runner's pipes after it exits: a test's own daemon can hold them. */
3472
+ const DRAIN_MS = 2e3;
3473
+ /**
3474
+ * Run a runner (`node <args>`) under the watchdog, with a timeout. On POSIX the watchdog
3475
+ * leads its own process group, so the whole group — the runner's workers included — can
3476
+ * be signalled: on timeout, Ctrl-C, SIGTERM or SIGHUP it gets SIGTERM, then SIGKILL after
3477
+ * 5 s, and once the runner exits whatever is left in its group is killed. A process a
3478
+ * test starts in a session of its own is out of reach, as it is under the runners.
3479
+ */
3480
+ function runBounded(args, options) {
3481
+ return new Promise((resolve) => {
3482
+ const posix = process.platform !== "win32";
3483
+ const child = spawn(process.execPath, [
3484
+ "-e",
3485
+ WATCHDOG,
3486
+ "--",
3487
+ JSON.stringify(options.cleanup),
3488
+ ...args
3489
+ ], {
3490
+ cwd: options.cwd,
3491
+ env: options.env,
3492
+ stdio: [
3493
+ "ignore",
3494
+ "pipe",
3495
+ "pipe",
3496
+ "ipc"
3497
+ ],
3498
+ detached: posix,
3499
+ windowsHide: true
3500
+ });
3501
+ const tail = [];
3502
+ let partial = "";
3503
+ const onData = (chunk) => {
3504
+ if (options.showOutput) process.stderr.write(chunk);
3505
+ const parts = (partial + chunk.toString()).split("\n");
3506
+ partial = parts.pop() ?? "";
3507
+ for (const line of parts) options.onLine?.(line);
3508
+ tail.push(...parts);
3509
+ if (tail.length > 40) tail.splice(0, tail.length - 40);
3510
+ };
3511
+ child.stdout?.on("data", onData);
3512
+ child.stderr?.on("data", onData);
3513
+ const killTree = (signal) => {
3514
+ if (child.pid === void 0) return;
3515
+ if (posix) try {
3516
+ process.kill(-child.pid, signal);
3517
+ } catch (error) {
3518
+ if (errorCode(error) !== "ESRCH") child.kill(signal);
3519
+ }
3520
+ else spawnSync("taskkill", [
3521
+ "/pid",
3522
+ String(child.pid),
3523
+ "/T",
3524
+ "/F"
3525
+ ], {
3526
+ stdio: "ignore",
3527
+ windowsHide: true
3528
+ });
3529
+ };
3530
+ let timedOut = false;
3531
+ let interrupted = false;
3532
+ let escalate;
3533
+ let drain;
3534
+ const stop = () => {
3535
+ killTree("SIGTERM");
3536
+ escalate ??= setTimeout(() => killTree("SIGKILL"), 5e3);
3537
+ };
3538
+ const timer = setTimeout(() => {
3539
+ timedOut = true;
3540
+ stop();
3541
+ }, options.timeoutMs);
3542
+ const onSignal = () => {
3543
+ interrupted = true;
3544
+ stop();
3545
+ };
3546
+ const signals = SIGNALS;
3547
+ for (const s of signals) process.on(s, onSignal);
3548
+ let settled = false;
3549
+ let exitCode = null;
3550
+ const finish = (code) => {
3551
+ if (settled) return;
3552
+ settled = true;
3553
+ clearTimeout(timer);
3554
+ clearTimeout(escalate);
3555
+ clearTimeout(drain);
3556
+ for (const s of signals) process.off(s, onSignal);
3557
+ if (partial) {
3558
+ options.onLine?.(partial);
3559
+ tail.push(partial);
3560
+ }
3561
+ if (child.connected) child.disconnect();
3562
+ resolve({
3563
+ code,
3564
+ timedOut,
3565
+ interrupted,
3566
+ tail
3567
+ });
3568
+ };
3569
+ child.on("exit", (code) => {
3570
+ exitCode = code;
3571
+ if (posix) killTree("SIGKILL");
3572
+ drain = setTimeout(() => {
3573
+ child.stdout?.destroy();
3574
+ child.stderr?.destroy();
3575
+ finish(exitCode);
3576
+ }, DRAIN_MS);
3577
+ });
3578
+ child.on("error", (error) => {
3579
+ tail.push(String(error));
3580
+ finish(null);
3581
+ });
3582
+ child.on("close", (code) => finish(code ?? exitCode));
3583
+ });
3584
+ }
3585
+ /**
3586
+ * The environment for a runner: a parent test runner's per-worker identity removed, and
3587
+ * nothing that asks either runner to write snapshots.
3588
+ */
3589
+ function runnerEnv() {
3590
+ const env = {};
3591
+ for (const [key, value] of Object.entries(process.env)) {
3592
+ if (key.startsWith("VITEST") || key === "JEST_WORKER_ID" || key === "UPDATE_SNAPSHOT") continue;
3593
+ env[key] = value;
3594
+ }
3595
+ env.CI = "true";
3596
+ return env;
3597
+ }
3598
+ /** A package's bin, found as installedManifest finds the package (walking node_modules up). */
3599
+ function locateBin(root, pkg, binName) {
3600
+ for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
3601
+ const pkgDir = path.join(dir, "node_modules", pkg);
3602
+ if (fs.existsSync(path.join(pkgDir, "package.json"))) {
3603
+ const manifest = installedManifest(dir, pkg) ?? {};
3604
+ const bin = manifest.bin;
3605
+ const relative = typeof bin === "string" ? bin : bin?.[binName];
3606
+ if (!relative) return null;
3607
+ return {
3608
+ bin: path.join(fs.realpathSync(pkgDir), relative),
3609
+ version: typeof manifest.version === "string" ? manifest.version : null
3610
+ };
3611
+ }
3612
+ if (path.dirname(dir) === dir) return null;
3613
+ }
3614
+ }
3615
+ /** The config Vitest itself would load from the root (vitest.config.* before vite.config.*). */
3616
+ function findVitestConfig(root) {
3617
+ for (const base of ["vitest.config", "vite.config"]) for (const ext of [
3618
+ ".ts",
3619
+ ".mts",
3620
+ ".cts",
3621
+ ".js",
3622
+ ".mjs",
3623
+ ".cjs"
3624
+ ]) if (fs.existsSync(path.join(root, base + ext))) return base + ext;
3625
+ return null;
3626
+ }
3627
+ /**
3628
+ * An import specifier from `fromDir` to `file`: relative with `/` separators, or the
3629
+ * absolute path with `/` separators when no relative path exists (another drive).
3630
+ */
3631
+ function importSpecifier(fromDir, file, p = path) {
3632
+ const rel = p.relative(fromDir, file);
3633
+ if (p.isAbsolute(rel)) return rel.split(p.sep).join("/");
3634
+ const forward = rel.split(p.sep).join("/");
3635
+ return forward.startsWith(".") ? forward : `./${forward}`;
3636
+ }
3637
+ /**
3638
+ * The config compare's Vitest run loads: the project's config, unchanged, except that
3639
+ * every snapshot file it resolves — through its own resolveSnapshotPath, a project's, or
3640
+ * the `__vitest_snapshots__/` recipe when it sets none — is read from a copy in an
3641
+ * isolated directory, and `update` is false. Only files with Vitest's header are copied:
3642
+ * Vitest cannot read Jest's (other keys), and with CI set Vitest 5.0.5 still rewrote the
3643
+ * header of every Jest .snap file it read. Each resolution is logged to `manifest`.
3644
+ */
3645
+ function wrapperSource(baseSpecifier, isolated, manifest, root) {
3646
+ return `import path from "node:path";
3647
+ import fs from "node:fs";
3648
+ import { mergeConfig } from "vitest/config";
3649
+ import base from ${JSON.stringify(baseSpecifier)};
3650
+
3651
+ const ROOT = ${JSON.stringify(root)};
3652
+ const ISOLATED = ${JSON.stringify(isolated)};
3653
+ const MANIFEST = ${JSON.stringify(manifest)};
3654
+ const recipe = (testPath, extension) =>
3655
+ path.join(path.dirname(testPath), "__vitest_snapshots__", path.basename(testPath) + extension);
3656
+ const seen = new Set();
3657
+
3658
+ function isolate(own) {
3659
+ return (testPath, extension, context) => {
3660
+ const original = own ? own(testPath, extension, context) : recipe(testPath, extension);
3661
+ const rel = path.relative(ROOT, original);
3662
+ const inside = rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
3663
+ const target = path.join(ISOLATED, inside ? rel : path.join("outside", Buffer.from(original).toString("hex").slice(-80)));
3664
+ if (!seen.has(target)) {
3665
+ seen.add(target);
3666
+ let header = null;
3667
+ try { header = fs.readFileSync(original, "utf8").slice(0, 40); } catch {}
3668
+ const vitests = header !== null && header.startsWith("// Vitest Snapshot");
3669
+ fs.mkdirSync(path.dirname(target), { recursive: true });
3670
+ if (vitests) fs.copyFileSync(original, target);
3671
+ fs.appendFileSync(MANIFEST, JSON.stringify({ testPath, original, copied: vitests, foreign: header !== null && !vitests }) + "\\n");
3672
+ }
3673
+ return target;
3674
+ };
3675
+ }
3676
+
3677
+ // Vitest 5.0.5 resolves every project's snapshots through the root's setting (one
3678
+ // SnapshotManager), so the root's isolation covers inline projects there; a project's own
3679
+ // is wrapped too, for a Vitest that honours it.
3680
+ function isolateProject(project, inherited) {
3681
+ if (!project || typeof project !== "object" || typeof project.then === "function") return project;
3682
+ const test = project.test ?? {};
3683
+ const own = test.resolveSnapshotPath ?? (project.extends ? inherited : undefined);
3684
+ return {
3685
+ ...project,
3686
+ test: { ...test, resolveSnapshotPath: isolate(own), taskTitleValueFormatTruncate: 0 },
3687
+ };
3688
+ }
3689
+
3690
+ function compareConfig(config) {
3691
+ const resolved = mergeConfig(config ?? {}, {});
3692
+ const test = resolved.test ?? {};
3693
+ const own = test.resolveSnapshotPath;
3694
+ resolved.test = {
3695
+ ...test,
3696
+ resolveSnapshotPath: isolate(own),
3697
+ projects: Array.isArray(test.projects) ? test.projects.map((p) => isolateProject(p, own)) : test.projects,
3698
+ update: false,
3699
+ // Full parametrised titles: Vitest cuts each formatted value at 40 characters by
3700
+ // default, so two rows can print the same title and none matches Jest's.
3701
+ taskTitleValueFormatTruncate: 0,
3702
+ };
3703
+ return resolved;
3704
+ }
3705
+
3706
+ export default typeof base === "function"
3707
+ ? async (env) => compareConfig(await base(env))
3708
+ : compareConfig(await base);
3709
+ `;
3710
+ }
3711
+ /** The `test` script's flags `migrate` maps into the Vitest config, for Jest too. */
3712
+ const FORWARDED = [
3713
+ "config",
3714
+ "c",
3715
+ "testTimeout",
3716
+ "maxWorkers",
3717
+ "w",
3718
+ "runInBand",
3719
+ "i",
3720
+ "silent",
3721
+ "passWithNoTests"
3722
+ ];
3723
+ function forwardedScriptFlags(root) {
3724
+ const forwarded = [];
3725
+ const ignored = [];
3726
+ let pkg;
3727
+ try {
3728
+ pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
3729
+ } catch (error) {
3730
+ if (errorCode(error) === "ENOENT") return {
3731
+ forwarded,
3732
+ ignored
3733
+ };
3734
+ return {
3735
+ forwarded,
3736
+ ignored,
3737
+ unreadable: error.message.split("\n")[0]
3738
+ };
3739
+ }
3740
+ {
3741
+ const script = pkg?.scripts?.test;
3742
+ const parsed = typeof script === "string" ? parseJestScript("test", script) : null;
3743
+ for (const [name, value] of parsed?.flags ?? []) if (FORWARDED.includes(name)) {
3744
+ const long = {
3745
+ c: "config",
3746
+ w: "maxWorkers",
3747
+ i: "runInBand"
3748
+ }[name] ?? name;
3749
+ forwarded.push(value === true ? `--${long}` : `--${long}=${value}`);
3750
+ } else if (![
3751
+ "ci",
3752
+ "json",
3753
+ "outputFile",
3754
+ "watch",
3755
+ "watchAll",
3756
+ "coverage"
3757
+ ].includes(name)) ignored.push(`--${name}`);
3758
+ }
3759
+ return {
3760
+ forwarded,
3761
+ ignored
3762
+ };
3763
+ }
3764
+ /** The state of a path the walk could not read, followed by its error code. */
3765
+ const UNREADABLE = "unreadable:";
3766
+ /** Paths a tree state could not read (treeState), for the summary. */
3767
+ function unreadablePaths(state) {
3768
+ return [...state].filter(([, v]) => v.startsWith(UNREADABLE)).map(([k, v]) => `${k} (${v.slice(11)})`);
3769
+ }
3770
+ /** Directories skipped by name anywhere: package installs and version control. */
3771
+ const SKIPPED_DIR_NAMES = /* @__PURE__ */ new Set(["node_modules", ".git"]);
3772
+ /**
3773
+ * Output directories tools write as a matter of course, by root-relative path only: a
3774
+ * `coverage/` inside `src/features/` is the project's own and is checked.
3775
+ */
3776
+ const OUTPUT_DIR_PATHS = [
3777
+ "coverage",
3778
+ ".expo",
3779
+ ".gradle",
3780
+ ".cache",
3781
+ ".turbo",
3782
+ ".nyc_output",
3783
+ "android/build",
3784
+ "android/app/build",
3785
+ "android/.gradle",
3786
+ "ios/build",
3787
+ "ios/Pods",
3788
+ "ios/DerivedData"
3789
+ ];
3790
+ /**
3791
+ * Size and modification time of every file under the root, except in node_modules, .git
3792
+ * and the output directories. Symlinked directories are followed only while they stay
3793
+ * inside the root (each real directory once, so a cycle ends): a link out of the
3794
+ * project leads to files the project does not own.
3795
+ */
3796
+ function treeState(root, limit = 2e5) {
3797
+ const out = /* @__PURE__ */ new Map();
3798
+ const seen = /* @__PURE__ */ new Set();
3799
+ let realRoot;
3800
+ try {
3801
+ realRoot = fs.realpathSync(root);
3802
+ } catch (error) {
3803
+ out.set(".", `${UNREADABLE}${errorCode(error) ?? "error"}`);
3804
+ return out;
3805
+ }
3806
+ const unreadable = (abs, error) => out.set(path.relative(root, abs).split(path.sep).join("/") || ".", `${UNREADABLE}${errorCode(error) ?? "error"}`);
3807
+ const inside = (real) => real === realRoot || real.startsWith(realRoot + path.sep);
3808
+ const stack = [root];
3809
+ while (stack.length) {
3810
+ const dir = stack.pop();
3811
+ let real;
3812
+ try {
3813
+ real = fs.realpathSync(dir);
3814
+ } catch (error) {
3815
+ unreadable(dir, error);
3816
+ continue;
3817
+ }
3818
+ if (seen.has(real) || !inside(real)) continue;
3819
+ seen.add(real);
3820
+ let entries;
3821
+ try {
3822
+ entries = fs.readdirSync(dir, { withFileTypes: true });
3823
+ } catch (error) {
3824
+ unreadable(dir, error);
3825
+ continue;
3826
+ }
3827
+ for (const e of entries) {
3828
+ if (SKIPPED_DIR_NAMES.has(e.name)) continue;
3829
+ const abs = path.join(dir, e.name);
3830
+ const rel = path.relative(root, abs).split(path.sep).join("/");
3831
+ if (OUTPUT_DIR_PATHS.includes(rel)) continue;
3832
+ let stat;
3833
+ try {
3834
+ stat = e.isSymbolicLink() ? fs.statSync(abs) : fs.lstatSync(abs);
3835
+ } catch (error) {
3836
+ if (errorCode(error) !== "ENOENT") unreadable(abs, error);
3837
+ continue;
3838
+ }
3839
+ if (stat.isDirectory()) stack.push(abs);
3840
+ else if (stat.isFile()) {
3841
+ if (e.isSymbolicLink()) {
3842
+ let target;
3843
+ try {
3844
+ target = fs.realpathSync(abs);
3845
+ } catch (error) {
3846
+ if (errorCode(error) !== "ENOENT") unreadable(abs, error);
3847
+ continue;
3848
+ }
3849
+ if (!inside(target)) continue;
3850
+ }
3851
+ out.set(rel, `${stat.size}:${stat.mtimeMs}`);
3852
+ if (out.size > limit) return null;
3853
+ }
3854
+ }
3855
+ }
3856
+ return out;
3857
+ }
3858
+ const SNAPSHOT = /(?:^|\/)(?:__snapshots__|__vitest_snapshots__)\/|\.snap$/;
3859
+ const SOURCE = /\.(?:[cm]?[jt]sx?|json)$/;
3860
+ /** A change compare itself could have caused: a snapshot, or a test/source file (inline snapshots). */
3861
+ function isSnapshotOrSource(change) {
3862
+ const file = change.replace(/^(?:added|changed|removed) /, "");
3863
+ return SNAPSHOT.test(file) || SOURCE.test(file);
3864
+ }
3865
+ /**
3866
+ * What the runs did to the project. A file that existed before is the project's, so any
3867
+ * change to it, whatever its kind (`.graphql`, `.yaml`, an image), is fatal; so is a new
3868
+ * snapshot file. Only new files of other kinds are reported neutrally.
3869
+ */
3870
+ function treeChanges(before, after) {
3871
+ const fatal = [];
3872
+ const other = [];
3873
+ for (const [file, state] of after) if (!before.has(file)) (SNAPSHOT.test(file) ? fatal : other).push(`added ${file}`);
3874
+ else if (before.get(file) !== state) fatal.push(`changed ${file}`);
3875
+ for (const file of before.keys()) if (!after.has(file)) fatal.push(`removed ${file}`);
3876
+ return {
3877
+ fatal: fatal.sort(),
3878
+ other: other.sort()
3879
+ };
3880
+ }
3881
+ /** Jest's `--randomize` option exists from Jest 29.2; an older Jest rejects the flag. */
3882
+ function jestRandomizeFlag(version) {
3883
+ const [major, minor] = (version ?? "").split(".").map(Number);
3884
+ return major > 29 || major === 29 && minor >= 2;
3885
+ }
3886
+ /** The `code` of a Node system error (`ENOENT`, `ESRCH`, …), or undefined. */
3887
+ function errorCode(error) {
3888
+ return error?.code;
3889
+ }
3890
+ function readReport(file) {
3891
+ try {
3892
+ return JSON.parse(fs.readFileSync(file, "utf8"));
3893
+ } catch {
3894
+ return null;
3895
+ }
3896
+ }
3897
+ function seconds(since) {
3898
+ return `${((Date.now() - since) / 1e3).toFixed(1)}s`;
3899
+ }
3900
+ /** Reads Vitest's own output for what its JSON report leaves out. */
3901
+ function vitestOutputReader(sanitize) {
3902
+ const errors = [];
3903
+ let engine = null;
3904
+ let pending = null;
3905
+ let running = false;
3906
+ const plain = (line) => line.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "");
3907
+ return {
3908
+ errors,
3909
+ engine: () => engine,
3910
+ onLine(raw) {
3911
+ const line = plain(raw);
3912
+ if (/^\s*RUN\s+v\d/.test(line)) running = true;
3913
+ const m = running ? null : /^\[vitest-native\] engine: (native|mock) — /.exec(line);
3914
+ if (m) engine ??= m[1];
3915
+ const header = /⎯+\s*(Unhandled (?:Rejection|Error)|Uncaught Exception)\s*⎯+/.exec(line);
3916
+ if (header) {
3917
+ pending = header[1];
3918
+ return;
3919
+ }
3920
+ if (pending && line.trim() !== "") {
3921
+ errors.push(`${pending}: ${sanitize(line.trim())}`);
3922
+ pending = null;
3923
+ return;
3924
+ }
3925
+ const close = /^error during close (.*)$/.exec(line);
3926
+ if (close) errors.push(`error during close: ${sanitize(close[1])}`);
3927
+ }
3928
+ };
3929
+ }
3930
+ async function runCompare(options) {
3931
+ const { root, log } = options;
3932
+ const vitest = locateBin(root, "vitest", "vitest");
3933
+ const jest = options.jestResults ? null : locateBin(root, "jest", "jest");
3934
+ if (!vitest) {
3935
+ log(`✗ Vitest is not installed at ${root}; compare runs the project's own Vitest.`);
3936
+ return 2;
3937
+ }
3938
+ if (!options.jestResults && !jest) {
3939
+ log(`✗ Jest is not installed at ${root}; compare runs the project's own Jest (or reads a Jest --json report given with --jest-results).`);
3940
+ return 2;
3941
+ }
3942
+ const analysis = analyzeJestConfig(root);
3943
+ const vitestConfigFile = options.vitestConfig ?? findVitestConfig(root);
3944
+ if (options.vitestConfig && !fs.existsSync(path.resolve(root, options.vitestConfig))) {
3945
+ log(`✗ --vitest-config ${options.vitestConfig} does not exist under ${root}.`);
3946
+ return 2;
3947
+ }
3948
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "vn-compare-"));
3949
+ const nodeModules = path.join(root, "node_modules");
3950
+ const hadNodeModules = fs.existsSync(nodeModules);
3951
+ const configParent = path.join(nodeModules, ".vitest-native");
3952
+ const hadConfigParent = fs.existsSync(configParent);
3953
+ fs.mkdirSync(configParent, { recursive: true });
3954
+ const configDir = fs.mkdtempSync(path.join(configParent, "compare-"));
3955
+ const cleanup = [work, configDir];
3956
+ const guardian = startGuardian(cleanup, [...hadConfigParent ? [] : [configParent], ...hadNodeModules ? [] : [nodeModules]]);
3957
+ let interrupted = false;
3958
+ const onSignal = () => {
3959
+ interrupted = true;
3960
+ };
3961
+ for (const s of SIGNALS) process.on(s, onSignal);
3962
+ const before = treeState(root);
3963
+ const notChecked = before ? unreadablePaths(before) : [];
3964
+ if (notChecked.length) log(` ${notChecked.length} ${notChecked.length === 1 ? "path" : "paths"} could not be read, so the check that the runs change nothing does not cover them: ${notChecked.slice(0, 5).join(", ")}` + (notChecked.length > 5 ? ", …" : ""));
3965
+ try {
3966
+ let baseFile;
3967
+ let vitestConfigLabel;
3968
+ if (vitestConfigFile) {
3969
+ baseFile = path.resolve(root, vitestConfigFile);
3970
+ const rel = path.relative(root, baseFile);
3971
+ vitestConfigLabel = rel.startsWith("..") || path.isAbsolute(rel) ? path.basename(baseFile) : rel.split(path.sep).join("/");
3972
+ } else {
3973
+ baseFile = path.join(configDir, "migrate.config.mjs");
3974
+ const rootUrl = pathToFileURL(root + path.sep).href;
3975
+ fs.writeFileSync(baseFile, analysis.suggestedConfig.replaceAll("import.meta.url", JSON.stringify(rootUrl)));
3976
+ vitestConfigLabel = "the one `vitest-native migrate` suggests (not saved)";
3977
+ }
3978
+ const manifest = path.join(work, "snapshots.jsonl");
3979
+ const wrapper = path.join(configDir, "vitest.compare.config.mjs");
3980
+ fs.writeFileSync(wrapper, wrapperSource(importSpecifier(configDir, baseFile), path.join(configDir, "snapshots"), manifest, root));
3981
+ const jestInfo = {
3982
+ version: jest?.version ?? null,
3983
+ config: options.jestResults ? `report ${path.basename(options.jestResults)}` : analysis.source ?? "Jest's defaults (no Jest config found)"
3984
+ };
3985
+ const vitestInfo = {
3986
+ version: vitest.version,
3987
+ config: vitestConfigLabel
3988
+ };
3989
+ let jestReport;
3990
+ if (options.jestResults) {
3991
+ jestReport = readReport(path.resolve(options.jestResults));
3992
+ if (jestReport === null) {
3993
+ log(`✗ could not read a JSON report from ${options.jestResults}.`);
3994
+ return 2;
3995
+ }
3996
+ } else {
3997
+ const out = path.join(work, "jest.json");
3998
+ const script = forwardedScriptFlags(root);
3999
+ if (script.unreadable) log(` package.json could not be read (${script.unreadable}); no script flags forwarded.`);
4000
+ if (script.ignored.length) log(` scripts.test also passes ${script.ignored.join(" ")} to Jest; not forwarded (add them with --jest-args if they matter).`);
4001
+ const started = Date.now();
4002
+ log(`Running Jest ${jest?.version ?? ""}…`);
4003
+ const run = await runBounded([
4004
+ jest.bin,
4005
+ "--json",
4006
+ `--outputFile=${out}`,
4007
+ "--coverage=false",
4008
+ "--reporters=default",
4009
+ ...jestRandomizeFlag(jest?.version ?? null) ? ["--randomize=false"] : [],
4010
+ ...script.forwarded,
4011
+ ...options.jestArgs,
4012
+ "--ci"
4013
+ ], {
4014
+ cwd: root,
4015
+ env: runnerEnv(),
4016
+ timeoutMs: options.timeoutMs,
4017
+ showOutput: options.showOutput,
4018
+ cleanup
4019
+ });
4020
+ const failure = runFailure("Jest", run, options.timeoutMs);
4021
+ if (failure) return reportFailure(log, failure, run);
4022
+ jestReport = readReport(out);
4023
+ if (jestReport === null) return reportFailure(log, `Jest exited (${run.code}) without writing its JSON report.`, run);
4024
+ log(` done in ${seconds(started)}`);
4025
+ }
4026
+ const vitestOut = path.join(work, "vitest.json");
4027
+ const sanitizeCtx = {
4028
+ roots: [root, fs.realpathSync(root)],
4029
+ tmp: tmpSpellings(),
4030
+ home: os.homedir()
4031
+ };
4032
+ const reader = vitestOutputReader((s) => sanitizeMessage(s, sanitizeCtx));
4033
+ const started = Date.now();
4034
+ log(`Running Vitest ${vitest.version ?? ""}…`);
4035
+ const run = await runBounded([
4036
+ vitest.bin,
4037
+ "run",
4038
+ "--config",
4039
+ wrapper,
4040
+ "--reporter=json",
4041
+ `--outputFile.json=${vitestOut}`,
4042
+ "--reporter=default",
4043
+ "--coverage.enabled=false",
4044
+ ...options.vitestArgs
4045
+ ], {
4046
+ cwd: root,
4047
+ env: runnerEnv(),
4048
+ timeoutMs: options.timeoutMs,
4049
+ showOutput: options.showOutput,
4050
+ cleanup,
4051
+ onLine: reader.onLine
4052
+ });
4053
+ const failure = runFailure("Vitest", run, options.timeoutMs);
4054
+ if (failure) return reportFailure(log, failure, run);
4055
+ const vitestReport = readReport(vitestOut);
4056
+ if (vitestReport === null) return reportFailure(log, `Vitest exited (${run.code}) without writing its JSON report.`, run);
4057
+ log(` done in ${seconds(started)}`);
4058
+ log("");
4059
+ if (options.rawReportsDir) {
4060
+ fs.mkdirSync(options.rawReportsDir, { recursive: true });
4061
+ const save = (name, report) => fs.writeFileSync(path.join(options.rawReportsDir, name), JSON.stringify(report));
4062
+ save("jest.json", jestReport);
4063
+ save("vitest.json", vitestReport);
4064
+ }
4065
+ let jestResults;
4066
+ let vitestResults;
4067
+ try {
4068
+ vitestResults = normaliseReport(vitestReport, "vitest", { root });
4069
+ let aliases = options.jestRoot ? [options.jestRoot] : [];
4070
+ if (!aliases.length && options.jestResults) {
4071
+ const local = [...vitestResults.files.keys()];
4072
+ const prefix = [...normaliseReport(jestReport, "jest", { root }).files.keys()].some((f) => /^(\/|\.\.\/|[a-z]:)/.test(f)) ? foreignRoot(jestReport, local) : null;
4073
+ if (prefix) {
4074
+ aliases = [prefix];
4075
+ log(` Jest's report was made at ${prefix}; its paths are read relative to that directory.`);
4076
+ }
4077
+ }
4078
+ jestResults = normaliseReport(jestReport, "jest", {
4079
+ root,
4080
+ aliases
4081
+ });
4082
+ } catch (error) {
4083
+ log(`✗ ${error.message}`);
4084
+ return 2;
4085
+ }
4086
+ const resolutions = /* @__PURE__ */ new Map();
4087
+ if (fs.existsSync(manifest)) for (const line of fs.readFileSync(manifest, "utf8").split("\n")) {
4088
+ if (!line.trim()) continue;
4089
+ const entry = JSON.parse(line);
4090
+ const rel = path.relative(root, entry.testPath).split(path.sep).join("/");
4091
+ resolutions.set(rel, entry);
4092
+ }
4093
+ const comparison = classify(jestResults, vitestResults, {
4094
+ snapshotHint: (file, message) => snapshotHint(root, resolutions.get(file), file, message),
4095
+ vitestRun: {
4096
+ exitCode: run.code,
4097
+ errors: reader.errors,
4098
+ engine: reader.engine()
4099
+ },
4100
+ ordered: !options.strict && !options.jestResults && !options.jestArgs.some((a) => /^--randomize(=true)?$/.test(a)) && !options.vitestArgs.some((a) => /^--sequence\.shuffle(=true)?$/.test(a))
4101
+ });
4102
+ vitestInfo.config += "; snapshots read from an isolated copy";
4103
+ const after = treeState(root);
4104
+ const changes = before && after ? treeChanges(before, after) : {
4105
+ fatal: [],
4106
+ other: []
4107
+ };
4108
+ if (!before || !after) log(" The project has too many files to check that the runs changed none.");
4109
+ for (const line of renderComparison(comparison, {
4110
+ jest: jestInfo,
4111
+ vitest: vitestInfo,
4112
+ top: options.top,
4113
+ jsonPath: options.json ?? null,
4114
+ projectChanged: changes.fatal.length > 0
4115
+ })) log(line);
4116
+ if (!vitestConfigFile && analysis.attention.length) log(`Note: \`vitest-native migrate\` lists ${analysis.attention.length} item(s) that need attention; they can explain differences.`);
4117
+ if (changes.other.length) {
4118
+ log(` The runs wrote ${changes.other.length} other file(s) in the project:`);
4119
+ for (const c of changes.other.slice(0, options.top)) log(` ${c}`);
4120
+ if (changes.other.length > options.top) log(` … and ${changes.other.length - options.top} more`);
4121
+ }
4122
+ if (options.json) {
4123
+ const report = jsonReport(comparison, {
4124
+ vitestNative: installedManifest(root, "vitest-native")?.version ?? null,
4125
+ jest: jestInfo,
4126
+ vitest: vitestInfo
4127
+ });
4128
+ report.projectChanges = changes.fatal;
4129
+ report.projectWrites = changes.other;
4130
+ fs.writeFileSync(path.resolve(options.json), `${JSON.stringify(report, null, 2)}\n`);
4131
+ }
4132
+ if (changes.fatal.length) {
4133
+ const own = changes.fatal.filter(isSnapshotOrSource);
4134
+ const suites = changes.fatal.filter((c) => !isSnapshotOrSource(c));
4135
+ const list = (items) => {
4136
+ for (const c of items.slice(0, options.top)) log(` ${c}`);
4137
+ if (items.length > options.top) log(` … and ${items.length - options.top} more`);
4138
+ };
4139
+ if (own.length) {
4140
+ log("");
4141
+ log(`✗ The runs changed ${own.length} snapshot or source file(s) in the project, which compare must never do:`);
4142
+ list(own);
4143
+ log(" Restore them from version control, and report this with the command you ran.");
4144
+ }
4145
+ if (suites.length) {
4146
+ log("");
4147
+ log("✗ The test run changed these existing files (compare's comparison does not count while the suite rewrites tracked files):");
4148
+ list(suites);
4149
+ }
4150
+ return 2;
4151
+ }
4152
+ if (interrupted) {
4153
+ log("✗ compare was interrupted.");
4154
+ return 130;
4155
+ }
4156
+ if (comparison.jestPassed === 0) return 2;
4157
+ return comparison.claimHolds ? 0 : 1;
4158
+ } finally {
4159
+ for (const s of SIGNALS) process.off(s, onSignal);
4160
+ fs.rmSync(work, {
4161
+ recursive: true,
4162
+ force: true
4163
+ });
4164
+ fs.rmSync(configDir, {
4165
+ recursive: true,
4166
+ force: true
4167
+ });
4168
+ for (const [dir, existed] of [[configParent, hadConfigParent], [nodeModules, hadNodeModules]]) {
4169
+ if (existed) continue;
4170
+ try {
4171
+ fs.rmdirSync(dir);
4172
+ } catch (error) {
4173
+ const code = errorCode(error);
4174
+ if (code !== "ENOTEMPTY" && code !== "EEXIST" && code !== "ENOENT") log(` Could not remove ${dir}, which compare created: ${error.message}`);
4175
+ }
4176
+ }
4177
+ if (guardian?.connected) guardian.disconnect();
4178
+ }
4179
+ }
4180
+ /**
4181
+ * Which snapshot hint a Vitest snapshot mismatch gets. Inline and file snapshots fail with
4182
+ * the same message as a `.snap` one, and recording those is not what the hints say, so
4183
+ * a test gets one only when it is a `.snap` case: its key, in Jest's spelling (Vitest's
4184
+ * `a > b 1` is Jest's `a b 1`), is in Jest's `.snap` file, which it must be for the test
4185
+ * to have passed under Jest. Then: Vitest's config resolves to Jest's own file
4186
+ * (`shared-snapshot-dir`), or Vitest's own file lacks the key (`no-vitest-snapshot`).
4187
+ */
4188
+ function snapshotHint(root, resolution, file, message) {
4189
+ const key = /Snapshot `([^`]*)` mismatched/.exec(message)?.[1];
4190
+ if (!key || !resolution) return void 0;
4191
+ const read = (p) => {
4192
+ try {
4193
+ return fs.readFileSync(p, "utf8");
4194
+ } catch {
4195
+ return "";
4196
+ }
4197
+ };
4198
+ const abs = path.resolve(root, file);
4199
+ const jestFile = resolution.foreign ? resolution.original : path.join(path.dirname(abs), "__snapshots__", `${path.basename(abs)}.snap`);
4200
+ const jestKey = key.split(" > ").join(" ");
4201
+ if (!read(jestFile).includes(`exports[\`${jestKey}\`]`)) return void 0;
4202
+ if (resolution.foreign) return key.includes(" > ") ? "shared-snapshot-dir-nested" : "shared-snapshot-dir";
4203
+ if (!resolution.copied) return "no-vitest-snapshot";
4204
+ return read(resolution.original).includes(`exports[\`${key}\`]`) ? void 0 : "no-vitest-snapshot";
4205
+ }
4206
+ function runFailure(name, run, timeoutMs) {
4207
+ if (run.interrupted) return `${name} was interrupted.`;
4208
+ if (run.timedOut) return `${name} did not finish within ${timeoutMs / 1e3}s and was stopped; raise --timeout if the suite needs longer.`;
4209
+ return null;
4210
+ }
4211
+ function reportFailure(log, message, run) {
4212
+ log(`✗ ${message}`);
4213
+ const tail = run.tail.filter((l) => l.trim() !== "").slice(-20);
4214
+ if (tail.length) {
4215
+ log(" Last output:");
4216
+ for (const line of tail) log(` ${line}`);
4217
+ }
4218
+ return run.interrupted ? 130 : 2;
4219
+ }
4220
+ // src/cli/index.ts
4221
+ /**
4222
+ * vitest-native CLI: `init` (write a ready config), `doctor` (diagnose the
4223
+ * environment), `migrate` (analyze a Jest config and report the mapping),
4224
+ * `compare` (run the suite under Jest and under Vitest and list the differences).
4225
+ * Deliberately vitest-free at module load — it runs via npx outside any test
4226
+ * process.
4227
+ */
4228
+ /** Each command's flags, besides --root <dir> and --help, which every command takes. */
4229
+ const COMMAND_FLAGS = {
4230
+ init: ["--jest-compat", "--force"],
4231
+ doctor: [],
4232
+ migrate: ["--write", "--force"],
4233
+ compare: [...COMPARE_VALUED_FLAGS, ...COMPARE_SWITCHES]
4234
+ };
4235
+ /** Flags whose value is the next argument (unless written as --flag=value). */
4236
+ const VALUED_FLAGS = /* @__PURE__ */ new Set(["--root", ...COMPARE_VALUED_FLAGS]);
4237
+ /**
4238
+ * The first flag `command` does not take, or null. An ignored typo (`--wirte`, `--stirct`)
4239
+ * would run something other than what was asked, so it is refused instead. The argument
4240
+ * after a valued flag is its value, even when it starts with "--" (`--jest-args "--ci"`).
4241
+ */
4242
+ function unknownFlag(command, args) {
4243
+ const allowed = /* @__PURE__ */ new Set([
4244
+ "--root",
4245
+ "--help",
4246
+ "-h",
4247
+ ...COMMAND_FLAGS[command] ?? []
4248
+ ]);
4249
+ for (let i = 0; i < args.length; i++) {
4250
+ const arg = args[i];
4251
+ if (!arg.startsWith("-")) continue;
4252
+ const name = arg.split("=")[0];
4253
+ if (!allowed.has(name)) return name;
4254
+ if (VALUED_FLAGS.has(name) && !arg.includes("=")) i++;
4255
+ }
4256
+ return null;
4257
+ }
4258
+ const USAGE = `vitest-native — test React Native with Vitest
4259
+
4260
+ Usage:
4261
+ vitest-native init [--jest-compat] [--force] write a ready-to-run vitest config
4262
+ vitest-native doctor diagnose peers, engine, presets, RNTL/Node
4263
+ vitest-native migrate [--write] [--force] analyze jest config → migration report
4264
+ (--write also saves the suggested config)
4265
+ vitest-native compare run the suite under Jest and under Vitest,
4266
+ list every test whose result differs
4267
+ --jest-args "<args>" extra Jest arguments --vitest-args "<args>" extra Vitest arguments
4268
+ --vitest-config <file> Vitest config to use --jest-results <file> read Jest's --json report
4269
+ --jest-root <dir> where that report was made (detected when omitted)
4270
+ --json <file> write a report to attach to an issue (no source code)
4271
+ --top <n> groups and files to list (10)
4272
+ --timeout <seconds> per runner (1800) --show-output stream both runners' output
4273
+ --strict confirm a parametrised (%p) row only by its title, never by its place
4274
+ exits 0 when every Jest-passing test passes under Vitest and \`vitest run\` exits 0,
4275
+ 1 when not, 2 when a runner could not run or the project changed, 130 when interrupted
4276
+ Options:
4277
+ --root <dir> project root (default: cwd)
4278
+ --help this text
4279
+
4280
+ Docs: https://danfry1.github.io/vitest-native/`;
4281
+ function main(argv, log = console.log) {
4282
+ const args = argv.filter((a) => a !== "--");
4283
+ const command = args.find((a, i) => !a.startsWith("-") && !COMPARE_VALUED_FLAGS.includes(args[i - 1]));
4284
+ const has = (flag) => args.includes(flag);
4285
+ const rootIdx = args.indexOf("--root");
4286
+ const root = path.resolve(rootIdx !== -1 ? args[rootIdx + 1] ?? "." : ".");
4287
+ if (has("--help") || has("-h")) {
4288
+ log(USAGE);
4289
+ return 0;
4290
+ }
4291
+ if (!command) {
4292
+ log(USAGE);
4293
+ return 1;
4294
+ }
4295
+ const unknown = command in COMMAND_FLAGS ? unknownFlag(command, args) : null;
4296
+ if (unknown) {
4297
+ log(`✗ unknown option ${unknown} for ${command}. Valid: ${[
4298
+ "--root",
4299
+ "--help",
4300
+ ...COMMAND_FLAGS[command]
4301
+ ].join(", ")}.`);
4302
+ return 1;
4303
+ }
4304
+ if (!fs.existsSync(path.join(root, "package.json"))) {
4305
+ log(`✗ no package.json at ${root} — run from a project root or pass --root.`);
4306
+ return 1;
4307
+ }
4308
+ switch (command) {
4309
+ case "doctor": {
4310
+ const result = runDoctor(root);
4311
+ for (const line of result.lines) log(line);
4312
+ return result.ok ? 0 : 1;
4313
+ }
4314
+ case "init": {
4315
+ const result = runInit(root, {
4316
+ jestCompat: has("--jest-compat"),
4317
+ force: has("--force")
4318
+ });
4319
+ for (const line of result.lines) log(line);
4320
+ return result.ok ? 0 : 1;
4321
+ }
4322
+ case "migrate": {
4323
+ const report = analyzeJestConfig(root);
4324
+ const write = has("--write");
4325
+ for (const line of renderMigrationReport(report, { write })) log(line);
4326
+ if (report.ok && write) {
4327
+ const init = runInit(root, { force: has("--force") });
4328
+ if (!init.ok) {
4329
+ for (const line of init.lines) log(line);
4330
+ return 1;
4331
+ }
4332
+ const target = path.join(root, init.wrote);
4333
+ fs.writeFileSync(target, report.suggestedConfig);
4334
+ log(`✓ wrote ${init.wrote} from the analysis above. Next: ${migrationNextStep(report)}`);
4335
+ for (const line of init.notices ?? []) log(line);
4336
+ }
4337
+ return report.ok ? 0 : 1;
4338
+ }
4339
+ case "compare": {
4340
+ const parsed = parseCompareArgs(args.filter((_, i) => i !== args.indexOf(command)));
4341
+ if ("error" in parsed) {
4342
+ log(`✗ ${parsed.error}`);
4343
+ return 1;
4344
+ }
4345
+ return runCompare({
4346
+ ...parsed,
4347
+ root,
4348
+ log
4349
+ });
4350
+ }
4351
+ default:
4352
+ log(`✗ unknown command '${command}'.`);
4353
+ log(USAGE);
4354
+ return 1;
4355
+ }
4356
+ }
4357
+ const entry = process.argv[1] ? path.basename(process.argv[1]) : "";
4358
+ if (entry === "cli.mjs" || entry === "vitest-native") {
4359
+ const code = main(process.argv.slice(2));
4360
+ if (typeof code === "number") process.exit(code);
4361
+ else code.then((c) => process.exit(c));
4362
+ }
4363
+ export { COMMAND_FLAGS, main, unknownFlag };