@smoothbricks/nx-plugin 0.4.26 → 0.4.28

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 (343) hide show
  1. package/README.md +994 -117
  2. package/dist/bin/smoo-nx-bound-failures.d.ts +3 -0
  3. package/dist/bin/smoo-nx-bound-failures.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-bound-failures.js +31 -0
  5. package/dist/bin/smoo-nx-cargo-hash.js +28 -3
  6. package/dist/bin/smoo-nx-exec.js +15 -73
  7. package/dist/bin/smoo-nx-failures.d.ts +3 -0
  8. package/dist/bin/smoo-nx-failures.d.ts.map +1 -0
  9. package/dist/bin/smoo-nx-failures.js +3 -0
  10. package/dist/bin/smoo-nx-nextest-extract.js +3 -2
  11. package/dist/bin/smoo-nx-test-walks.d.ts +3 -0
  12. package/dist/bin/smoo-nx-test-walks.d.ts.map +1 -0
  13. package/dist/bin/smoo-nx-test-walks.js +34 -0
  14. package/dist/bounded-test-policy.d.ts +7 -1
  15. package/dist/bounded-test-policy.d.ts.map +1 -1
  16. package/dist/bounded-test-policy.js +101 -40
  17. package/dist/build-state-output-policy.d.ts +25 -0
  18. package/dist/build-state-output-policy.d.ts.map +1 -0
  19. package/dist/build-state-output-policy.js +64 -0
  20. package/dist/cargo-closure-input.d.ts +3 -2
  21. package/dist/cargo-closure-input.d.ts.map +1 -1
  22. package/dist/cargo-closure-input.js +16 -15
  23. package/dist/cargo-dev-profile.d.ts +37 -0
  24. package/dist/cargo-dev-profile.d.ts.map +1 -0
  25. package/dist/cargo-dev-profile.js +108 -0
  26. package/dist/cargo-source-hash.d.ts +43 -6
  27. package/dist/cargo-source-hash.d.ts.map +1 -1
  28. package/dist/cargo-source-hash.js +309 -73
  29. package/dist/cargo-toolchain-policy.d.ts +4 -0
  30. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  31. package/dist/cargo-toolchain-policy.js +5 -0
  32. package/dist/cargo-workspace.d.ts +101 -5
  33. package/dist/cargo-workspace.d.ts.map +1 -1
  34. package/dist/cargo-workspace.js +291 -10
  35. package/dist/cross-check-policy.d.ts +21 -3
  36. package/dist/cross-check-policy.d.ts.map +1 -1
  37. package/dist/cross-check-policy.js +24 -6
  38. package/dist/disk-command-policy.d.ts +7 -0
  39. package/dist/disk-command-policy.d.ts.map +1 -0
  40. package/dist/disk-command-policy.js +98 -0
  41. package/dist/ensure-built-receipt.d.ts +25 -0
  42. package/dist/ensure-built-receipt.d.ts.map +1 -0
  43. package/dist/ensure-built-receipt.js +261 -0
  44. package/dist/ensure-built-witness.d.ts +57 -0
  45. package/dist/ensure-built-witness.d.ts.map +1 -0
  46. package/dist/ensure-built-witness.js +412 -0
  47. package/dist/ensure-built.d.ts +207 -12
  48. package/dist/ensure-built.d.ts.map +1 -1
  49. package/dist/ensure-built.js +576 -202
  50. package/dist/eslint-file-set.d.ts +7 -0
  51. package/dist/eslint-file-set.d.ts.map +1 -0
  52. package/dist/eslint-file-set.js +12 -0
  53. package/dist/executors/bounded-exec/cpu-pool.d.ts +63 -0
  54. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -0
  55. package/dist/executors/bounded-exec/cpu-pool.js +379 -0
  56. package/dist/executors/bounded-exec/cpu-tokens.d.ts +82 -0
  57. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +1 -0
  58. package/dist/executors/bounded-exec/cpu-tokens.js +114 -0
  59. package/dist/executors/bounded-exec/disk-lease.d.ts +61 -0
  60. package/dist/executors/bounded-exec/disk-lease.d.ts.map +1 -0
  61. package/dist/executors/bounded-exec/disk-lease.js +91 -0
  62. package/dist/executors/bounded-exec/executor.d.ts +45 -2
  63. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  64. package/dist/executors/bounded-exec/executor.js +447 -52
  65. package/dist/executors/bounded-exec/gateway-lease.d.ts +52 -0
  66. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -0
  67. package/dist/executors/bounded-exec/gateway-lease.js +143 -0
  68. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +35 -0
  69. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -0
  70. package/dist/executors/bounded-exec/hang-diagnostics.js +231 -0
  71. package/dist/executors/bounded-exec/progress.d.ts +35 -0
  72. package/dist/executors/bounded-exec/progress.d.ts.map +1 -0
  73. package/dist/executors/bounded-exec/progress.js +79 -0
  74. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +3 -0
  75. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -0
  76. package/dist/executors/bounded-exec/ram-temp-fixtures.js +12 -0
  77. package/dist/executors/bounded-exec/ram-temp-held.d.ts +91 -0
  78. package/dist/executors/bounded-exec/ram-temp-held.d.ts.map +1 -0
  79. package/dist/executors/bounded-exec/ram-temp-held.js +152 -0
  80. package/dist/executors/bounded-exec/ram-temp.d.ts +223 -0
  81. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -0
  82. package/dist/executors/bounded-exec/ram-temp.js +1528 -0
  83. package/dist/executors/bounded-exec/schema.d.ts +29 -11
  84. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  85. package/dist/executors/bounded-exec/verdict.d.ts +162 -0
  86. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/verdict.js +318 -0
  88. package/dist/executors/shard-timings/executor.d.ts +14 -0
  89. package/dist/executors/shard-timings/executor.d.ts.map +1 -0
  90. package/dist/executors/shard-timings/executor.js +25 -0
  91. package/dist/executors/shard-timings/schema.d.ts +4 -0
  92. package/dist/executors/shard-timings/schema.d.ts.map +1 -0
  93. package/dist/executors/shard-timings/schema.js +1 -0
  94. package/dist/failure-summary.d.ts +5 -0
  95. package/dist/failure-summary.d.ts.map +1 -0
  96. package/dist/failure-summary.js +118 -0
  97. package/dist/generators/create-package/generator.d.ts.map +1 -1
  98. package/dist/generators/create-package/generator.js +6 -2
  99. package/dist/index.d.ts +14 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +370 -138
  102. package/dist/managed-files/ci-workflow.d.ts +13 -0
  103. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  104. package/dist/managed-files/ci-workflow.js +44 -13
  105. package/dist/managed-files/files.d.ts +7 -1
  106. package/dist/managed-files/files.d.ts.map +1 -1
  107. package/dist/managed-files/files.js +62 -8
  108. package/dist/managed-files/json-edit.d.ts +21 -0
  109. package/dist/managed-files/json-edit.d.ts.map +1 -0
  110. package/dist/managed-files/json-edit.js +295 -0
  111. package/dist/managed-files/managed-format.d.ts +33 -1
  112. package/dist/managed-files/managed-format.d.ts.map +1 -1
  113. package/dist/managed-files/managed-format.js +82 -2
  114. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +7 -0
  115. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -1
  116. package/dist/managed-files/pr-preview-cleanup-workflow.js +68 -4
  117. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  118. package/dist/managed-files/publish-workflow.js +231 -48
  119. package/dist/managed-files/tree.d.ts +5 -0
  120. package/dist/managed-files/tree.d.ts.map +1 -1
  121. package/dist/managed-files/tree.js +5 -3
  122. package/dist/manifest-hash.d.ts.map +1 -1
  123. package/dist/manifest-hash.js +2 -5
  124. package/dist/nextest-code-bound.d.ts +62 -0
  125. package/dist/nextest-code-bound.d.ts.map +1 -0
  126. package/dist/nextest-code-bound.js +154 -0
  127. package/dist/nextest-extraction.d.ts +24 -8
  128. package/dist/nextest-extraction.d.ts.map +1 -1
  129. package/dist/nextest-extraction.js +42 -7
  130. package/dist/package-target-policy.d.ts.map +1 -1
  131. package/dist/package-target-policy.js +3 -5
  132. package/dist/release-config-policy.d.ts.map +1 -1
  133. package/dist/release-config-policy.js +3 -5
  134. package/dist/runtime-input.d.ts +14 -0
  135. package/dist/runtime-input.d.ts.map +1 -0
  136. package/dist/runtime-input.js +15 -0
  137. package/dist/rust-tokens.d.ts +11 -0
  138. package/dist/rust-tokens.d.ts.map +1 -0
  139. package/dist/rust-tokens.js +81 -0
  140. package/dist/task-results.d.ts +6 -0
  141. package/dist/task-results.d.ts.map +1 -0
  142. package/dist/task-results.js +61 -0
  143. package/dist/test-program.d.ts +54 -0
  144. package/dist/test-program.d.ts.map +1 -0
  145. package/dist/test-program.js +292 -0
  146. package/dist/test-timings.d.ts +71 -0
  147. package/dist/test-timings.d.ts.map +1 -0
  148. package/dist/test-timings.js +393 -0
  149. package/dist/test-walk-policy.d.ts +103 -0
  150. package/dist/test-walk-policy.d.ts.map +1 -0
  151. package/dist/test-walk-policy.js +657 -0
  152. package/dist/testing.d.ts +177 -0
  153. package/dist/testing.d.ts.map +1 -0
  154. package/dist/testing.js +824 -0
  155. package/dist/type-guards.d.ts +3 -0
  156. package/dist/type-guards.d.ts.map +1 -0
  157. package/dist/type-guards.js +4 -0
  158. package/dist/typecheck-test-policy.d.ts +8 -5
  159. package/dist/typecheck-test-policy.d.ts.map +1 -1
  160. package/dist/typecheck-test-policy.js +113 -100
  161. package/dist/workspace-config-policy.d.ts +8 -0
  162. package/dist/workspace-config-policy.d.ts.map +1 -1
  163. package/dist/workspace-config-policy.js +175 -63
  164. package/dist/workspace-index.d.ts +12 -0
  165. package/dist/workspace-index.d.ts.map +1 -0
  166. package/dist/workspace-index.js +17 -0
  167. package/dist/workspace-manifest.d.ts +37 -0
  168. package/dist/workspace-manifest.d.ts.map +1 -1
  169. package/executors.json +5 -0
  170. package/loader.js +13 -11
  171. package/managed/raw/envrc +33 -67
  172. package/managed/raw/git-format-staged.yml +30 -35
  173. package/managed/raw/patches/nx@23.2.1.patch +3484 -0
  174. package/managed/raw/tooling/direnv/apple-developer.sh +83 -0
  175. package/managed/raw/tooling/direnv/developer-links.ts +569 -11
  176. package/managed/raw/tooling/direnv/devenv.smoo.nix +314 -93
  177. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +20 -11
  178. package/managed/raw/tooling/direnv/linked-snapshots.ts +845 -0
  179. package/managed/raw/tooling/direnv/nx-socket-dir.sh +82 -0
  180. package/managed/raw/tooling/direnv/repo-path +14 -2
  181. package/managed/raw/tooling/direnv/setup-environment.ts +1146 -159
  182. package/managed/raw/tooling/direnv/toolchain-stamp.ts +45 -3
  183. package/managed/raw/tooling/direnv/ttsc-env.sh +39 -0
  184. package/managed/raw/tooling/git-hooks/commit-msg.sh +5 -6
  185. package/managed/raw/tooling/git-hooks/pre-commit.sh +7 -6
  186. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -15
  187. package/managed/templates/github/actions/cache-nix-devenv/action.yml +6 -6
  188. package/managed/templates/github/actions/cache-node-modules/action.yml +6 -4
  189. package/managed/templates/github/actions/cache-nx/action.yml +1 -1
  190. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +1 -1
  191. package/managed/templates/github/actions/forgejo-artifact.cjs +99 -0
  192. package/managed/templates/github/actions/forgejo-download-artifact/action.yml +49 -0
  193. package/managed/templates/github/actions/forgejo-download-artifact/index.cjs +7 -0
  194. package/managed/templates/github/actions/forgejo-upload-artifact/action.yml +65 -0
  195. package/managed/templates/github/actions/forgejo-upload-artifact/index.cjs +7 -0
  196. package/managed/templates/github/actions/setup-devenv/action.yml +21 -3
  197. package/managed/templates/github/workflows/managed-files.yml +1 -2
  198. package/nextest.toml +8 -41
  199. package/package.json +74 -12
  200. package/runtime-input.sh +81 -0
  201. package/src/__tests__/counted-cargo.ts +33 -14
  202. package/src/__tests__/fixture-nx-env.ts +111 -46
  203. package/src/__tests__/progress-clock.ts +43 -0
  204. package/src/__tests__/runtime-input.ts +23 -0
  205. package/src/bin/smoo-nx-bound-failures.test.ts +127 -0
  206. package/src/bin/smoo-nx-bound-failures.ts +33 -0
  207. package/src/bin/smoo-nx-cargo-hash.ts +28 -3
  208. package/src/bin/smoo-nx-exec.ts +16 -74
  209. package/src/bin/smoo-nx-failures.ts +4 -0
  210. package/src/bin/smoo-nx-nextest-extract.ts +3 -2
  211. package/src/bin/smoo-nx-test-walks.ts +42 -0
  212. package/src/bounded-test-policy.test.ts +268 -21
  213. package/src/bounded-test-policy.ts +114 -42
  214. package/src/build-state-output-policy.test.ts +115 -0
  215. package/src/build-state-output-policy.ts +90 -0
  216. package/src/bun-bootstrap.test.ts +57 -3
  217. package/src/bun-file-packages.test.ts +47 -0
  218. package/src/cargo-closure-input.test.ts +138 -66
  219. package/src/cargo-closure-input.ts +17 -15
  220. package/src/cargo-dev-profile.ts +137 -0
  221. package/src/cargo-resolve-cache.test.ts +70 -1
  222. package/src/cargo-source-hash.test.ts +193 -97
  223. package/src/cargo-source-hash.ts +345 -68
  224. package/src/cargo-toolchain-policy.ts +6 -0
  225. package/src/cargo-workspace.test.ts +320 -0
  226. package/src/cargo-workspace.ts +336 -10
  227. package/src/cross-check-policy.test.ts +59 -1
  228. package/src/cross-check-policy.ts +25 -6
  229. package/src/disk-command-policy.test.ts +61 -0
  230. package/src/disk-command-policy.ts +107 -0
  231. package/src/ensure-built-receipt.test.ts +184 -0
  232. package/src/ensure-built-receipt.ts +263 -0
  233. package/src/ensure-built-witness.test.ts +344 -0
  234. package/src/ensure-built-witness.ts +252 -0
  235. package/src/ensure-built.test.ts +1036 -578
  236. package/src/ensure-built.ts +820 -224
  237. package/src/eslint-file-set.ts +9 -0
  238. package/src/executors/bounded-exec/cpu-pool.test.ts +454 -0
  239. package/src/executors/bounded-exec/cpu-pool.ts +417 -0
  240. package/src/executors/bounded-exec/cpu-tokens.test.ts +269 -0
  241. package/src/executors/bounded-exec/cpu-tokens.ts +177 -0
  242. package/src/executors/bounded-exec/disk-lease.test.ts +185 -0
  243. package/src/executors/bounded-exec/disk-lease.ts +139 -0
  244. package/src/executors/bounded-exec/executor-host.test.ts +778 -0
  245. package/src/executors/bounded-exec/executor.test.ts +1116 -63
  246. package/src/executors/bounded-exec/executor.ts +565 -67
  247. package/src/executors/bounded-exec/gateway-lease.ts +176 -0
  248. package/src/executors/bounded-exec/hang-diagnostics.test.ts +285 -0
  249. package/src/executors/bounded-exec/hang-diagnostics.ts +283 -0
  250. package/src/executors/bounded-exec/progress.test.ts +79 -0
  251. package/src/executors/bounded-exec/progress.ts +118 -0
  252. package/src/executors/bounded-exec/ram-temp-fixtures.ts +12 -0
  253. package/src/executors/bounded-exec/ram-temp-held.test.ts +264 -0
  254. package/src/executors/bounded-exec/ram-temp-held.ts +242 -0
  255. package/src/executors/bounded-exec/ram-temp-host.test.ts +605 -0
  256. package/src/executors/bounded-exec/ram-temp.test.ts +674 -0
  257. package/src/executors/bounded-exec/ram-temp.ts +1918 -0
  258. package/src/executors/bounded-exec/schema.json +11 -5
  259. package/src/executors/bounded-exec/schema.ts +27 -11
  260. package/src/executors/bounded-exec/verdict.test.ts +440 -0
  261. package/src/executors/bounded-exec/verdict.ts +433 -0
  262. package/src/executors/shard-timings/executor.ts +36 -0
  263. package/src/executors/shard-timings/schema.json +21 -0
  264. package/src/executors/shard-timings/schema.ts +4 -0
  265. package/src/failure-summary.ts +119 -0
  266. package/src/generators/bounded-test-targets/generator.test.ts +4 -4
  267. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  268. package/src/generators/create-package/generator.test.ts +6 -0
  269. package/src/generators/create-package/generator.ts +6 -2
  270. package/src/host-controller-wiring.test.ts +31 -0
  271. package/src/index.test.ts +909 -295
  272. package/src/index.ts +441 -143
  273. package/src/linked-snapshots.nx.test.ts +172 -0
  274. package/src/managed-files/ci-workflow.ts +54 -13
  275. package/src/managed-files/files.ts +65 -9
  276. package/src/managed-files/forgejo-artifact.test.ts +395 -0
  277. package/src/managed-files/generator.test.ts +60 -1
  278. package/src/managed-files/json-edit.test.ts +216 -0
  279. package/src/managed-files/json-edit.ts +290 -0
  280. package/src/managed-files/managed-format-json.test.ts +308 -0
  281. package/src/managed-files/managed-format.ts +90 -2
  282. package/src/managed-files/pr-preview-cleanup-workflow.ts +69 -3
  283. package/src/managed-files/publish-workflow.ts +285 -67
  284. package/src/managed-files/repo-path.test.ts +129 -0
  285. package/src/managed-files/trace-db-artifact.test.ts +7 -0
  286. package/src/managed-files/tree.ts +11 -3
  287. package/src/manifest-hash.ts +2 -6
  288. package/src/nextest-code-bound.test.ts +155 -0
  289. package/src/nextest-code-bound.ts +195 -0
  290. package/src/nextest-extraction.test.ts +37 -5
  291. package/src/nextest-extraction.ts +51 -9
  292. package/src/nextest-partitions.test.ts +427 -82
  293. package/src/nx-cache-bound.test.ts +5 -10
  294. package/src/nx-cache-restore-mtime.test.ts +170 -0
  295. package/src/nx-daemon-claim.test.ts +277 -0
  296. package/src/nx-daemon-idle-cpu.test.ts +81 -0
  297. package/src/nx-daemon-idle-policy.test.ts +51 -0
  298. package/src/nx-daemon-ignore-files.test.ts +210 -0
  299. package/src/nx-daemon-root-normalization.test.ts +105 -0
  300. package/src/nx-daemon-validity.test.ts +925 -0
  301. package/src/nx-dot-input-policy.test.ts +353 -0
  302. package/src/nx-failure-life-cycles.test.ts +207 -0
  303. package/src/nx-files-archive-racy.test.ts +97 -0
  304. package/src/nx-foreign-workspace-env.test.ts +329 -0
  305. package/src/nx-incomplete-run-summary.test.ts +70 -0
  306. package/src/nx-plugin-load-errors.test.ts +120 -0
  307. package/src/nx-project-resolution-cache.test.ts +176 -0
  308. package/src/nx-raw-inputs.test.ts +166 -0
  309. package/src/nx-resident-graph-workers.test.ts +7 -16
  310. package/src/nx-run-information.test.ts +118 -0
  311. package/src/nx-skipped-task-exit.test.ts +180 -0
  312. package/src/nx-state-location.test.ts +63 -0
  313. package/src/nx-store-resolution.test.ts +26 -25
  314. package/src/nx-task-graph-cycles.test.ts +148 -0
  315. package/src/nx-task-output-lease.test.ts +414 -0
  316. package/src/nx-use-local.test.ts +103 -0
  317. package/src/package-target-policy.ts +3 -6
  318. package/src/release-config-policy.ts +3 -6
  319. package/src/runtime-input.test.ts +215 -0
  320. package/src/runtime-input.ts +17 -0
  321. package/src/rust-tokens.ts +78 -0
  322. package/src/serial-group-wiring.test.ts +326 -0
  323. package/src/task-history-namespace.test.ts +87 -89
  324. package/src/task-results.test.ts +226 -0
  325. package/src/task-results.ts +75 -0
  326. package/src/test-program.test.ts +303 -0
  327. package/src/test-program.ts +341 -0
  328. package/src/test-timings.test.ts +240 -0
  329. package/src/test-timings.ts +311 -0
  330. package/src/test-walk-policy.test.ts +585 -0
  331. package/src/test-walk-policy.ts +731 -0
  332. package/src/testing.test.ts +509 -0
  333. package/src/testing.ts +922 -0
  334. package/src/type-guards.ts +4 -0
  335. package/src/typecheck-test-policy.test.ts +496 -11
  336. package/src/typecheck-test-policy.ts +137 -103
  337. package/src/workspace-config-policy.test.ts +212 -13
  338. package/src/workspace-config-policy.ts +101 -73
  339. package/src/workspace-index.ts +18 -0
  340. package/src/workspace-manifest.ts +41 -0
  341. package/test-timings.json +85 -30
  342. package/managed/raw/tooling/direnv/inherited-devenv.ts +0 -665
  343. package/managed/raw/tooling/direnv/shared-caches.sh +0 -53
@@ -0,0 +1,731 @@
1
+ // One walk per test path. Within one test file, a case that walks another case's path again, differs from it only in
2
+ // literals, or replays its scenario with one injected step changed, tests one path twice: the cases belong in one walk
3
+ // that pays the setup once and asserts after each step, or in one table or property over what differs.
4
+ //
5
+ // Each top-level statement of a case body is normalized three ways: `exact` renames the names the case declares to
6
+ // their declaration index and keeps literals, so equal statements do the same thing; `shape` also abstracts every
7
+ // literal, so equal shapes differ only in values; `skeleton` also collapses every declared name, so a statement
8
+ // matches across cases that declare a different number of names before it. Field, method, key and path names are
9
+ // never renamed. Callers choose the files and, for a diff-scoped check, the changed line ranges: a pair is judged when
10
+ // either of its cases overlaps a change.
11
+ import { spawnSync } from 'node:child_process';
12
+ import { existsSync, readFileSync } from 'node:fs';
13
+ import { extname, join } from 'node:path';
14
+ import ts from 'typescript';
15
+ import { type RustToken, rustTokens } from './rust-tokens.js';
16
+
17
+ export const TEST_ONE_WALK = {
18
+ id: 'TEST-ONE-WALK',
19
+ help:
20
+ 'Fold the cases into one walk that pays the setup once and asserts after each step, or into one ' +
21
+ 'table/property over the values or injected step that differ. Keep a separate case only for a distinct ' +
22
+ 'boundary or edge.',
23
+ /** Leading statements two cases must share exactly before one that only asserts beyond them repeats the other. */
24
+ samePath: 2,
25
+ /** Statements a case needs before a literal-only twin counts. */
26
+ literalTwin: 2,
27
+ /** A replayed scenario shares at least this many leading statements in skeleton (the setup)… */
28
+ scenarioHead: 1,
29
+ /** …and this many trailing ones (the action and its outcome), after the longer case's extra trailing assertions… */
30
+ scenarioTail: 3,
31
+ };
32
+
33
+ /** One top-level statement of a case body, normalized. */
34
+ export interface Step {
35
+ readonly exact: string;
36
+ readonly shape: string;
37
+ readonly skeleton: string;
38
+ /** `exact` with every declared name collapsed: equal flows do the same thing with the same values. */
39
+ readonly flow: string;
40
+ /** A pure assertion: it only reads what earlier steps built, so it walks no path of its own. */
41
+ readonly assertion: boolean;
42
+ }
43
+
44
+ /** One test case: `test`/`it` in TypeScript, a `#[test]`-family fn in Rust. */
45
+ export interface TestCase {
46
+ readonly name: string;
47
+ readonly start: number;
48
+ /** The 1-based column of the case's first token on its `start` line. */
49
+ readonly column: number;
50
+ readonly end: number;
51
+ /**
52
+ * What decides the case's outcome besides its body: an expected-failure or ignore modifier, and in TypeScript the
53
+ * `before*`/`after*` hooks of its enclosing `describe` chain. Only cases with equal identities are compared.
54
+ */
55
+ readonly identity: string;
56
+ readonly steps: readonly Step[];
57
+ }
58
+
59
+ /**
60
+ * `same-path`: the cases share their leading statements exactly, and one of them only asserts beyond them, so it
61
+ * walks a prefix of the other's path. `literal-twin`: the bodies have the same shape and differ only in literals.
62
+ * `same-scenario`: one case is the other's setup (in skeleton) and its action and outcome (exactly, up to declared
63
+ * names) around one injected statement of its own. It is advisory: measured at about 80% precision, it is reported to
64
+ * the writer and reviewer and never refuses.
65
+ */
66
+ export type Duplication = 'same-path' | 'literal-twin' | 'same-scenario';
67
+
68
+ /** Whether a kind refuses (a lint error) or only advises (a warning for the writer and reviewer). */
69
+ export const REFUSES: Record<Duplication, boolean> = {
70
+ 'same-path': true,
71
+ 'literal-twin': true,
72
+ 'same-scenario': false,
73
+ };
74
+
75
+ export interface DuplicateScenario {
76
+ readonly file: string;
77
+ readonly first: TestCase;
78
+ readonly second: TestCase;
79
+ readonly kind: Duplication;
80
+ /** Statements the two cases share: exactly, in shape, or in skeleton, by kind. */
81
+ readonly shared: number;
82
+ }
83
+
84
+ /** A changed line range on the new side of a diff, inclusive. */
85
+ export interface ChangeRange {
86
+ readonly start: number;
87
+ readonly end: number;
88
+ }
89
+
90
+ interface Token {
91
+ readonly text: string;
92
+ readonly literal: boolean;
93
+ /** A name the case declares, renamed to `$<declaration index>`. */
94
+ readonly local: boolean;
95
+ }
96
+
97
+ function step(tokens: readonly Token[], assertion: boolean): Step {
98
+ return {
99
+ exact: tokens.map((token) => token.text).join(' '),
100
+ shape: tokens.map((token) => (token.literal ? '$L' : token.text)).join(' '),
101
+ skeleton: tokens.map((token) => (token.literal ? '$L' : token.local ? '$' : token.text)).join(' '),
102
+ flow: tokens.map((token) => (token.local ? '$' : token.text)).join(' '),
103
+ assertion,
104
+ };
105
+ }
106
+
107
+ const JS_EXTENSION = /^\.(?:[cm]?[jt]sx?)$/u;
108
+ /** A file under a test directory, or named as a test. Rust test fns are read from any `.rs` file. */
109
+ export const TEST_PATH =
110
+ /(?:^|\/)(?:__tests__|tests?|nx-it)(?:\/|$)|(?:^|\/)(?:test[-_]|[^/]+\.(?:test|spec)\.)|[-_]test\.(?:sh|py|[cm]?tsx?)$/u;
111
+
112
+ // --- TypeScript -------------------------------------------------------------------------------------------------
113
+
114
+ const CASE_CALLEE = /^(?:test|it)(?:\.(?:only|concurrent|serial|failing))?$/u;
115
+ const ASSERT_CALLEE = /^(?:expect|expectTypeOf|assert\w*)$/u;
116
+ /** Matchers that run the subject: a throw, a rejection or a resolution is a path of its own. */
117
+ const ACTING_MATCHER = /^(?:rejects|resolves|toThrow\w*)$/u;
118
+
119
+ function declaredNames(body: ts.Node): Map<string, number> {
120
+ const names = new Map<string, number>();
121
+ const bind = (name: ts.BindingName): void => {
122
+ if (ts.isIdentifier(name)) {
123
+ if (!names.has(name.text)) names.set(name.text, names.size);
124
+ return;
125
+ }
126
+ // A shorthand `{ name }` binds the property it reads: renaming it would equate `{ trace }` with `{ flush }`.
127
+ for (const element of name.elements)
128
+ if (!ts.isOmittedExpression(element) && (ts.isArrayBindingPattern(name) || element.propertyName !== undefined))
129
+ bind(element.name);
130
+ };
131
+ const visit = (node: ts.Node): void => {
132
+ if (ts.isVariableDeclaration(node) || ts.isParameter(node)) bind(node.name);
133
+ if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && node.name !== undefined) bind(node.name);
134
+ ts.forEachChild(node, visit);
135
+ };
136
+ visit(body);
137
+ return names;
138
+ }
139
+
140
+ /**
141
+ * `expect(…)…` or `assert…(…)` that calls only methods (no free function, local closure or constructor) and runs no
142
+ * function, rejection or throw; or `if (…) throw …` with no else.
143
+ */
144
+ function tsAssertion(statement: ts.Node): boolean {
145
+ if (ts.isIfStatement(statement)) {
146
+ const then = statement.thenStatement;
147
+ const thrown = ts.isThrowStatement(then) || (ts.isBlock(then) && then.statements.every(ts.isThrowStatement));
148
+ return statement.elseStatement === undefined && thrown;
149
+ }
150
+ if (!ts.isExpressionStatement(statement)) return false;
151
+ let asserts = false;
152
+ let acts = false;
153
+ const visit = (node: ts.Node): void => {
154
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isNewExpression(node)) acts = true;
155
+ else if (ts.isPropertyAccessExpression(node) && ACTING_MATCHER.test(node.name.text)) acts = true;
156
+ else if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
157
+ if (ASSERT_CALLEE.test(node.expression.text)) asserts = true;
158
+ else acts = true;
159
+ }
160
+ ts.forEachChild(node, visit);
161
+ };
162
+ visit(statement.expression);
163
+ return asserts && !acts;
164
+ }
165
+
166
+ function tsTokens(node: ts.Node, source: ts.SourceFile, locals: ReadonlyMap<string, number>): Token[] {
167
+ const tokens: Token[] = [];
168
+ const visit = (child: ts.Node): void => {
169
+ if (ts.isIdentifier(child)) {
170
+ // A property name (`.name`, `name:`, `{ name }`) is a key, never the local it may share a spelling with.
171
+ const parent = child.parent;
172
+ const key =
173
+ ((ts.isPropertyAccessExpression(parent) || ts.isPropertyAssignment(parent)) && parent.name === child) ||
174
+ ts.isShorthandPropertyAssignment(parent);
175
+ const local = key ? undefined : locals.get(child.text);
176
+ tokens.push(
177
+ local === undefined
178
+ ? { text: child.text, literal: false, local: false }
179
+ : { text: `$${local}`, literal: false, local: true },
180
+ );
181
+ return;
182
+ }
183
+ switch (child.kind) {
184
+ case ts.SyntaxKind.StringLiteral:
185
+ case ts.SyntaxKind.NumericLiteral:
186
+ case ts.SyntaxKind.BigIntLiteral:
187
+ case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
188
+ case ts.SyntaxKind.RegularExpressionLiteral:
189
+ case ts.SyntaxKind.TemplateHead:
190
+ case ts.SyntaxKind.TemplateMiddle:
191
+ case ts.SyntaxKind.TemplateTail:
192
+ case ts.SyntaxKind.TrueKeyword:
193
+ case ts.SyntaxKind.FalseKeyword:
194
+ tokens.push({ text: child.getText(source), literal: true, local: false });
195
+ return;
196
+ }
197
+ const children = child.getChildren(source);
198
+ if (children.length === 0) tokens.push({ text: child.getText(source), literal: false, local: false });
199
+ else for (const grandchild of children) visit(grandchild);
200
+ };
201
+ visit(node);
202
+ return tokens;
203
+ }
204
+
205
+ const HOOK_CALLEE = /^(?:before|after)(?:Each|All)$/u;
206
+
207
+ /**
208
+ * What the enclosing `describe` chain fixes for a case, outermost first, as source text: its `before*`/`after*` hook
209
+ * calls and its own declarations (`const make = () => new MemoryStore()` makes a different subject than a DiskStore).
210
+ */
211
+ function describeChain(node: ts.Node, source: ts.SourceFile): string[] {
212
+ const context: string[] = [];
213
+ for (let scope = node.parent; scope !== undefined; scope = scope.parent) {
214
+ if (!(ts.isArrowFunction(scope) || ts.isFunctionExpression(scope)) || !ts.isBlock(scope.body)) continue;
215
+ const call = scope.parent;
216
+ if (!ts.isCallExpression(call) || !/^describe(?:[.(]|$)/u.test(call.expression.getText(source))) continue;
217
+ const own = scope.body.statements
218
+ .filter(
219
+ (statement) =>
220
+ ts.isVariableStatement(statement) ||
221
+ ts.isFunctionDeclaration(statement) ||
222
+ (ts.isExpressionStatement(statement) &&
223
+ ts.isCallExpression(statement.expression) &&
224
+ ts.isIdentifier(statement.expression.expression) &&
225
+ HOOK_CALLEE.test(statement.expression.expression.text)),
226
+ )
227
+ .map((statement) => statement.getText(source).replace(/\s+/gu, ' '));
228
+ context.unshift(...own);
229
+ }
230
+ return context;
231
+ }
232
+
233
+ /**
234
+ * The steps a case walks. A body that is one call whose last argument is a function, such as
235
+ * `await withHarness(memoryBackend, async (h) => { … })`, walks the call itself as its first step, with the function
236
+ * replaced by `$body` so the wrapper's other arguments still tell cases apart, and then that function's statements.
237
+ */
238
+ function caseSteps(body: ts.ConciseBody, source: ts.SourceFile, locals: ReadonlyMap<string, number>): Step[] {
239
+ const steps: Step[] = [];
240
+ let statements: readonly ts.Node[] = ts.isBlock(body) ? body.statements : [body];
241
+ for (;;) {
242
+ const only = statements.length === 1 ? statements[0] : undefined;
243
+ let expression = only !== undefined && ts.isExpressionStatement(only) ? only.expression : only;
244
+ while (expression !== undefined && ts.isAwaitExpression(expression)) expression = expression.expression;
245
+ const call = expression !== undefined && ts.isCallExpression(expression) ? expression : undefined;
246
+ const inner = call?.arguments.at(-1);
247
+ if (
248
+ call === undefined ||
249
+ inner === undefined ||
250
+ !(ts.isArrowFunction(inner) || ts.isFunctionExpression(inner)) ||
251
+ !ts.isBlock(inner.body)
252
+ )
253
+ break;
254
+ const punct = (text: string): Token => ({ text, literal: false, local: false });
255
+ const wrapper = [
256
+ ...tsTokens(call.expression, source, locals),
257
+ punct('('),
258
+ ...call.arguments.slice(0, -1).flatMap((argument) => [...tsTokens(argument, source, locals), punct(',')]),
259
+ punct('$body'),
260
+ punct(')'),
261
+ ];
262
+ steps.push(step(wrapper, false));
263
+ statements = inner.body.statements;
264
+ }
265
+ for (const statement of statements) steps.push(step(tsTokens(statement, source, locals), tsAssertion(statement)));
266
+ return steps;
267
+ }
268
+
269
+ export function typeScriptCases(file: string, text: string): TestCase[] {
270
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
271
+ const cases: TestCase[] = [];
272
+ const line = (offset: number): number => source.getLineAndCharacterOfPosition(offset).line + 1;
273
+ const visit = (node: ts.Node): void => {
274
+ const callee = ts.isCallExpression(node) ? node.expression.getText(source) : '';
275
+ if (ts.isCallExpression(node) && CASE_CALLEE.test(callee)) {
276
+ const body = node.arguments.find(
277
+ (argument): argument is ts.ArrowFunction | ts.FunctionExpression =>
278
+ ts.isArrowFunction(argument) || ts.isFunctionExpression(argument),
279
+ );
280
+ const title = node.arguments[0];
281
+ if (body !== undefined && title !== undefined) {
282
+ cases.push({
283
+ name: ts.isStringLiteralLike(title) ? title.text : title.getText(source),
284
+ start: line(node.getStart(source)),
285
+ column: source.getLineAndCharacterOfPosition(node.getStart(source)).character + 1,
286
+ end: line(node.end),
287
+ identity: [callee.endsWith('.failing') ? 'failing' : '', ...describeChain(node, source)].join('\n'),
288
+ steps: caseSteps(body.body, source, declaredNames(body)),
289
+ });
290
+ return;
291
+ }
292
+ }
293
+ ts.forEachChild(node, visit);
294
+ };
295
+ visit(source);
296
+ return cases;
297
+ }
298
+
299
+ // --- Rust -------------------------------------------------------------------------------------------------------
300
+
301
+ const RUST_ASSERT = /^(?:debug_)?(?:prop_)?assert(?:_eq|_ne|_matches)?$/u;
302
+
303
+ /**
304
+ * `assert*!(…)` that borrows nothing mutably, calls no method on a `let mut` local (`mutable`, by renamed name), and
305
+ * otherwise calls only methods, macros and `Type::` items.
306
+ */
307
+ function rustAssertion(tokens: readonly Token[], mutable: ReadonlySet<string>): boolean {
308
+ if (!RUST_ASSERT.test(tokens[0]?.text ?? '') || tokens[1]?.text !== '!') return false;
309
+ return tokens.every((token, index) => {
310
+ const before = tokens[index - 1]?.text;
311
+ if (token.text === 'mut') return before !== '&';
312
+ if (mutable.has(token.text) && tokens[index + 1]?.text === '.' && tokens[index + 3]?.text === '(') return false;
313
+ if (tokens[index + 1]?.text !== '(' || !/^[a-z_$]/u.test(token.text) || before === '.') return true;
314
+ return before === '::' && /^[A-Z]/u.test(tokens[index - 2]?.text ?? '');
315
+ });
316
+ }
317
+
318
+ const OPEN: Record<string, true> = { '(': true, '[': true, '{': true };
319
+ const CLOSE: Record<string, true> = { ')': true, ']': true, '}': true };
320
+ /** Statements that end at their closing brace with no `;`. */
321
+ const BLOCK_STATEMENT: Record<string, true> = {
322
+ if: true,
323
+ for: true,
324
+ while: true,
325
+ loop: true,
326
+ match: true,
327
+ unsafe: true,
328
+ '{': true,
329
+ };
330
+ /** Pattern keywords that bind nothing. */
331
+ const PATTERN_WORDS: Record<string, true> = { mut: true, ref: true, _: true };
332
+
333
+ /** The index of the token closing the group opened at `open`. */
334
+ function closing(tokens: readonly RustToken[], open: number): number {
335
+ let depth = 0;
336
+ for (let index = open; index < tokens.length; index += 1) {
337
+ const token = tokens[index];
338
+ if (token?.kind !== 'punct') continue;
339
+ if (OPEN[token.text]) depth += 1;
340
+ else if (CLOSE[token.text]) {
341
+ depth -= 1;
342
+ if (depth === 0) return index;
343
+ }
344
+ }
345
+ return tokens.length - 1;
346
+ }
347
+
348
+ function rustSteps(body: readonly RustToken[]): Step[] {
349
+ const locals = new Map<string, number>();
350
+ const mutable = new Set<string>();
351
+ for (let index = 0; index < body.length; index += 1) {
352
+ if (body[index]?.text !== 'let') continue;
353
+ for (let cursor = index + 1; cursor < body.length; cursor += 1) {
354
+ const token = body[cursor];
355
+ if (token === undefined || token.text === '=' || token.text === ':' || token.text === ';') break;
356
+ if (token.kind !== 'ident' || !/^[a-z_]/u.test(token.text) || PATTERN_WORDS[token.text]) continue;
357
+ if (!locals.has(token.text)) locals.set(token.text, locals.size);
358
+ if (body[cursor - 1]?.text === 'mut') mutable.add(`$${locals.get(token.text)}`);
359
+ }
360
+ }
361
+ const steps: Step[] = [];
362
+ let current: Token[] = [];
363
+ let depth = 0;
364
+ const flush = (): void => {
365
+ if (current.length === 0) return;
366
+ steps.push(step(current, rustAssertion(current, mutable)));
367
+ current = [];
368
+ };
369
+ for (let index = 0; index < body.length; index += 1) {
370
+ const token = body[index];
371
+ if (token === undefined) break;
372
+ // A name after `.` or `::` is a field, method or path item, and a name before a lone `:` that opens or follows a
373
+ // `,` in a group is a struct-literal key: neither is the local it may share a spelling with.
374
+ const before = body[index - 1]?.text;
375
+ const member = before === '.' || before === '::';
376
+ const key = body[index + 1]?.text === ':' && (before === '{' || before === ',');
377
+ const local = token.kind === 'ident' && !member && !key ? locals.get(token.text) : undefined;
378
+ current.push(local === undefined ? token : { text: `$${local}`, literal: false, local: true });
379
+ if (token.kind !== 'punct') continue;
380
+ if (OPEN[token.text]) depth += 1;
381
+ else if (CLOSE[token.text]) depth -= 1;
382
+ if (depth !== 0) continue;
383
+ if (token.text === ';') flush();
384
+ else if (token.text === '}' && BLOCK_STATEMENT[current[0]?.text ?? '']) {
385
+ const next = body[index + 1]?.text;
386
+ if (next !== 'else' && next !== '.' && next !== '?') flush();
387
+ }
388
+ }
389
+ flush();
390
+ return steps;
391
+ }
392
+
393
+ /**
394
+ * An `async { … }` block that is the whole of a one-statement body, as in `runtime().block_on(async { … })`: the tokens
395
+ * before it (the wrapper, kept as the case's first step so a different runtime still tells cases apart) and the
396
+ * block's statements. Undefined for any other body.
397
+ */
398
+ function asyncBody(
399
+ body: readonly RustToken[],
400
+ ): { readonly wrapper: readonly RustToken[]; readonly inner: readonly RustToken[] } | undefined {
401
+ const at = body.findIndex((token) => token.text === 'async');
402
+ if (at === -1) return undefined;
403
+ const open = body[at + 1]?.text === 'move' ? at + 2 : at + 1;
404
+ if (body[open]?.text !== '{') return undefined;
405
+ const close = closing(body, open);
406
+ // Only the call's closing parentheses, a `;` and an unwrap or `?` may follow the block.
407
+ return body.length - close <= 8 ? { wrapper: body.slice(0, at), inner: body.slice(open + 1, close) } : undefined;
408
+ }
409
+
410
+ /** Attributes that change what a test's outcome means or where it runs: an expected panic, not running it, a cfg gate. */
411
+ const OUTCOME_ATTRIBUTE: Record<string, true> = { should_panic: true, ignore: true, cfg: true, cfg_attr: true };
412
+
413
+ export function rustCases(text: string): TestCase[] {
414
+ const tokens = rustTokens(text);
415
+ const newlines: number[] = [];
416
+ for (let offset = text.indexOf('\n'); offset !== -1; offset = text.indexOf('\n', offset + 1)) newlines.push(offset);
417
+ const line = (offset: number): number => {
418
+ let [low, high] = [0, newlines.length];
419
+ while (low < high) {
420
+ const middle = (low + high) >> 1;
421
+ if ((newlines[middle] ?? 0) < offset) low = middle + 1;
422
+ else high = middle;
423
+ }
424
+ return low + 1;
425
+ };
426
+ const cases: TestCase[] = [];
427
+ // Outcome attributes may sit before or after `#[test]`; those before it are held until a non-attribute token.
428
+ let held: string[] = [];
429
+ let heldUntil = -1;
430
+ for (let index = 0; index < tokens.length; index += 1) {
431
+ if (tokens[index]?.text !== '#' || tokens[index + 1]?.text !== '[') {
432
+ if (index !== heldUntil) held = [];
433
+ continue;
434
+ }
435
+ const close = closing(tokens, index + 1);
436
+ const attribute = tokens.slice(index + 2, close).map((token) => token.text);
437
+ const pathEnd = attribute.findIndex((text) => text === '(' || text === '=');
438
+ const path = (pathEnd === -1 ? attribute : attribute.slice(0, pathEnd)).at(-1) ?? '';
439
+ if (path !== 'test') {
440
+ if (index !== heldUntil) held = [];
441
+ if (OUTCOME_ATTRIBUTE[path]) held.push(attribute.join(' '));
442
+ heldUntil = close + 1;
443
+ index = close;
444
+ continue;
445
+ }
446
+ const modifiers = [...held];
447
+ held = [];
448
+ let cursor = close + 1;
449
+ while (cursor < tokens.length && tokens[cursor]?.text !== 'fn') {
450
+ if (tokens[cursor]?.text === '#' && tokens[cursor + 1]?.text === '[') {
451
+ const end = closing(tokens, cursor + 1);
452
+ const attribute = tokens.slice(cursor + 2, end).map((token) => token.text);
453
+ if (OUTCOME_ATTRIBUTE[attribute[0] ?? '']) modifiers.push(attribute.join(' '));
454
+ cursor = end;
455
+ }
456
+ cursor += 1;
457
+ }
458
+ const name = tokens[cursor + 1]?.text;
459
+ while (cursor < tokens.length && tokens[cursor]?.text !== '{') {
460
+ if (tokens[cursor]?.text === '(') cursor = closing(tokens, cursor);
461
+ cursor += 1;
462
+ }
463
+ if (name === undefined || cursor >= tokens.length) break;
464
+ const end = closing(tokens, cursor);
465
+ const start = tokens[index]?.offset ?? 0;
466
+ const body = tokens.slice(cursor + 1, end);
467
+ const steps = rustSteps(body);
468
+ const wrapped = steps.length === 1 ? asyncBody(body) : undefined;
469
+ cases.push({
470
+ name,
471
+ start: line(start),
472
+ column: start - (newlines[line(start) - 2] ?? -1),
473
+ end: line(tokens[end]?.offset ?? start),
474
+ identity: modifiers.sort().join('\n'),
475
+ steps: wrapped === undefined ? steps : [step(wrapped.wrapper, false), ...rustSteps(wrapped.inner)],
476
+ });
477
+ index = end;
478
+ }
479
+ return cases;
480
+ }
481
+
482
+ // --- Comparison -------------------------------------------------------------------------------------------------
483
+
484
+ /**
485
+ * The duplication between two cases of one identity, if either walks the other's path again, differs from it only in
486
+ * literals, or replays its scenario with one injected step changed.
487
+ */
488
+ export function duplication(
489
+ first: TestCase,
490
+ second: TestCase,
491
+ ): { readonly kind: Duplication; readonly shared: number } | undefined {
492
+ if (first.identity !== second.identity) return undefined;
493
+ const [a, b] = [first.steps, second.steps];
494
+ if (a.length === b.length && a.length >= TEST_ONE_WALK.literalTwin && a.every((s, i) => s.shape === b[i]?.shape))
495
+ return { kind: 'literal-twin', shared: a.length };
496
+ const shared = exactPrefix(a, b);
497
+ if (shared >= TEST_ONE_WALK.samePath && (onlyAssertsAfter(a, shared) || onlyAssertsAfter(b, shared)))
498
+ return { kind: 'same-path', shared };
499
+ return sameScenario(a, b);
500
+ }
501
+
502
+ function exactPrefix(a: readonly Step[], b: readonly Step[]): number {
503
+ let shared = 0;
504
+ while (shared < a.length && shared < b.length && a[shared]?.exact === b[shared]?.exact) shared += 1;
505
+ return shared;
506
+ }
507
+
508
+ function onlyAssertsAfter(steps: readonly Step[], shared: number): boolean {
509
+ return steps.slice(shared).every((s) => s.assertion);
510
+ }
511
+
512
+ /**
513
+ * One case is the other's setup (equal in skeleton) and action and outcome (equal in flow: the same calls with the
514
+ * same values, up to declared names) around exactly one statement of its own: the same scenario with a different
515
+ * injected step. The other case may inject more steps, and either case may end with extra pure assertions; they are
516
+ * more checks on the same outcome. The shared tail must hold an action, so two cases that only assert alike after
517
+ * different actions are not one scenario.
518
+ */
519
+ function sameScenario(
520
+ a: readonly Step[],
521
+ b: readonly Step[],
522
+ ): { readonly kind: Duplication; readonly shared: number } | undefined {
523
+ const shared = Math.max(framed(a, b), framed(b, a));
524
+ return shared > 0 ? { kind: 'same-scenario', shared } : undefined;
525
+ }
526
+
527
+ /** How many trailing statements of `steps` are pure assertions. */
528
+ function trailingAssertions(steps: readonly Step[]): number {
529
+ let count = 0;
530
+ while (count < steps.length && steps[steps.length - 1 - count]?.assertion === true) count += 1;
531
+ return count;
532
+ }
533
+
534
+ /** The head and tail `own` shares with `other` when exactly one statement of `own` lies between them, else 0. */
535
+ function framed(own: readonly Step[], other: readonly Step[]): number {
536
+ let head = 0;
537
+ while (head < own.length && own[head]?.skeleton === other[head]?.skeleton) head += 1;
538
+ if (head < TEST_ONE_WALK.scenarioHead) return 0;
539
+ let best = 0;
540
+ for (let ownExtra = 0; ownExtra <= trailingAssertions(own); ownExtra += 1) {
541
+ const ownEnd = own.length - ownExtra;
542
+ for (let otherExtra = 0; otherExtra <= trailingAssertions(other); otherExtra += 1) {
543
+ const otherEnd = other.length - otherExtra;
544
+ let tail = 0;
545
+ while (
546
+ tail < ownEnd - head &&
547
+ tail < otherEnd - head &&
548
+ own[ownEnd - 1 - tail]?.flow === other[otherEnd - 1 - tail]?.flow
549
+ )
550
+ tail += 1;
551
+ const acts = own.slice(ownEnd - tail, ownEnd).some((s) => !s.assertion);
552
+ if (acts && tail >= TEST_ONE_WALK.scenarioTail && ownEnd - head - tail === 1) best = Math.max(best, head + tail);
553
+ }
554
+ }
555
+ return best;
556
+ }
557
+
558
+ /**
559
+ * For each case, the earlier case it most nearly repeats among the pairs `judged` admits (a diff-scoped caller admits
560
+ * a pair when either case changed; partners are chosen only among those). The nearest refusing partner and the nearest
561
+ * advisory partner are reported separately, so an advisory pair can never hide a refusing one.
562
+ */
563
+ export function duplicateScenarios(
564
+ file: string,
565
+ cases: readonly TestCase[],
566
+ judged: (first: TestCase, second: TestCase) => boolean = () => true,
567
+ ): DuplicateScenario[] {
568
+ const found: DuplicateScenario[] = [];
569
+ cases.forEach((second, later) => {
570
+ const best: Partial<Record<'refusing' | 'advisory', DuplicateScenario>> = {};
571
+ for (const first of cases.slice(0, later)) {
572
+ if (!judged(first, second)) continue;
573
+ const match = duplication(first, second);
574
+ if (match === undefined) continue;
575
+ const slot = REFUSES[match.kind] ? 'refusing' : 'advisory';
576
+ const held = best[slot];
577
+ if (held === undefined || match.shared > held.shared) best[slot] = { file, first, second, ...match };
578
+ }
579
+ if (best.refusing !== undefined) found.push(best.refusing);
580
+ if (best.advisory !== undefined) found.push(best.advisory);
581
+ });
582
+ return found;
583
+ }
584
+
585
+ export function testCases(file: string, text: string): TestCase[] | undefined {
586
+ if (JS_EXTENSION.test(extname(file))) return TEST_PATH.test(file) ? typeScriptCases(file, text) : undefined;
587
+ return extname(file) === '.rs' ? rustCases(text) : undefined;
588
+ }
589
+
590
+ export function findDuplicateScenarios(
591
+ root: string,
592
+ files: readonly string[],
593
+ changes?: ReadonlyMap<string, readonly ChangeRange[]>,
594
+ ): DuplicateScenario[] {
595
+ const found: DuplicateScenario[] = [];
596
+ for (const file of files) {
597
+ const path = join(root, file);
598
+ if (!existsSync(path)) continue;
599
+ const cases = testCases(file, readFileSync(path, 'utf8'));
600
+ if (cases === undefined) continue;
601
+ const ranges = changes?.get(file);
602
+ const touched = (test: TestCase): boolean =>
603
+ ranges === undefined || ranges.some((range) => range.start <= test.end && range.end >= test.start);
604
+ found.push(...duplicateScenarios(file, cases, (first, second) => touched(first) || touched(second)));
605
+ }
606
+ return found;
607
+ }
608
+
609
+ export function formatDuplicateScenario(duplicate: DuplicateScenario): string {
610
+ const { first, second, shared } = duplicate;
611
+ const [a, b] = [`\`${first.name}\``, `\`${second.name}\``];
612
+ const verbatim =
613
+ first.steps.length === second.steps.length && first.steps.every((s, i) => s.exact === second.steps[i]?.exact);
614
+ const asserter = onlyAssertsAfter(first.steps, shared) ? [a, b] : [b, a];
615
+ const what =
616
+ duplicate.kind === 'literal-twin'
617
+ ? verbatim
618
+ ? `${b} repeats ${a} verbatim (${shared} statements)`
619
+ : `${b} differs from ${a} only in literals (${shared} statements of one shape)`
620
+ : duplicate.kind === 'same-path'
621
+ ? `${asserter[0]} only asserts after the ${shared} statements it shares with ${asserter[1]}: its assertions ` +
622
+ `belong in ${asserter[1]} after statement ${shared}`
623
+ : `${b} replays the scenario of ${a} with one step changed (${shared} shared statements of setup, action ` +
624
+ 'and outcome)';
625
+ return (
626
+ `${REFUSES[duplicate.kind] ? 'error' : 'warning'}[${TEST_ONE_WALK.id}]: ${what}\n` +
627
+ ` --> ${duplicate.file}:${second.start}:${second.column}\n` +
628
+ ` --> ${duplicate.file}:${first.start}:${first.column}\n` +
629
+ ` = help: ${TEST_ONE_WALK.help}`
630
+ );
631
+ }
632
+
633
+ /** A git answer, or why git could not give one. */
634
+ export type GitAnswer<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly reason: string };
635
+
636
+ /** Runs git without global or system configuration, so a sandboxed caller gets the same answer as its host. */
637
+ function git(
638
+ root: string,
639
+ args: readonly string[],
640
+ ): { readonly status: number; readonly stdout: string; readonly stderr: string } {
641
+ const result = spawnSync('git', args, {
642
+ cwd: root,
643
+ encoding: 'utf8',
644
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
645
+ maxBuffer: 1 << 28,
646
+ });
647
+ return { status: result.status ?? -1, stdout: result.stdout, stderr: result.stderr.trim() };
648
+ }
649
+
650
+ function failed(args: readonly string[], result: { readonly status: number; readonly stderr: string }): string {
651
+ return `git ${args.join(' ')}: ${result.stderr || `exit ${result.status}`}`;
652
+ }
653
+
654
+ /**
655
+ * The merge base of HEAD and the upstream main. A set `NX_BASE` (exported by nx-set-shas in CI) is the upstream and
656
+ * must name a commit. Otherwise the upstream is the first that exists of `refs/remotes/main/main`, the local main's
657
+ * upstream branch and `refs/remotes/origin/main`, and local `main` when none does.
658
+ */
659
+ export function upstreamBase(root: string): GitAnswer<string> {
660
+ const nxBase = process.env.NX_BASE;
661
+ const exists = (ref: string): GitAnswer<boolean> => {
662
+ const args = ['rev-parse', '--verify', '--quiet', ref];
663
+ const result = git(root, args);
664
+ // `--verify --quiet` answers an absent ref with status 1; any other failure is git failing, not an answer.
665
+ if (result.status === 0 || result.status === 1) return { ok: true, value: result.status === 0 };
666
+ return { ok: false, reason: failed(args, result) };
667
+ };
668
+ let upstream = 'main';
669
+ if (nxBase !== undefined && nxBase !== '') {
670
+ const named = exists(`${nxBase}^{commit}`);
671
+ if (!named.ok) return named;
672
+ if (!named.value) return { ok: false, reason: `NX_BASE=${nxBase} names no commit` };
673
+ upstream = nxBase;
674
+ } else {
675
+ // The local main's upstream, when it has one: `for-each-ref` answers empty, never fails, when either is missing.
676
+ const tracked = git(root, ['for-each-ref', '--format=%(upstream)', 'refs/heads/main']).stdout.trim();
677
+ for (const ref of ['refs/remotes/main/main', tracked, 'refs/remotes/origin/main'].filter(Boolean)) {
678
+ const found = exists(ref);
679
+ if (!found.ok) return found;
680
+ if (found.value) {
681
+ upstream = ref;
682
+ break;
683
+ }
684
+ }
685
+ }
686
+ const args = ['merge-base', 'HEAD', upstream];
687
+ const result = git(root, args);
688
+ if (result.status !== 0)
689
+ return {
690
+ ok: false,
691
+ reason: `${failed(args, result)} (fetch main, set refs/remotes/main/main, or export NX_BASE)`,
692
+ };
693
+ return { ok: true, value: result.stdout.trim() };
694
+ }
695
+
696
+ /**
697
+ * The files changed since `base`, tracked or untracked, and the new-side line ranges of each change; an untracked
698
+ * file is changed throughout.
699
+ */
700
+ export function diffScope(
701
+ root: string,
702
+ base: string,
703
+ ): GitAnswer<{ readonly files: readonly string[]; readonly changes: ReadonlyMap<string, readonly ChangeRange[]> }> {
704
+ const read = (args: readonly string[]): GitAnswer<string> => {
705
+ const result = git(root, args);
706
+ return result.status === 0 ? { ok: true, value: result.stdout } : { ok: false, reason: failed(args, result) };
707
+ };
708
+ const changed = read(['diff', '--name-only', '-z', base, '--']);
709
+ if (!changed.ok) return changed;
710
+ const listed = read(['ls-files', '--others', '--exclude-standard', '-z']);
711
+ if (!listed.ok) return listed;
712
+ const untracked = new Set(listed.value.split('\0'));
713
+ const files = [...new Set([...changed.value.split('\0'), ...untracked].filter(Boolean))].sort();
714
+ const changes = new Map<string, readonly ChangeRange[]>();
715
+ for (const file of files) {
716
+ if (untracked.has(file)) {
717
+ changes.set(file, [{ start: 1, end: Number.POSITIVE_INFINITY }]);
718
+ continue;
719
+ }
720
+ const diff = read(['diff', '--unified=0', '--no-ext-diff', '--no-color', base, '--', file]);
721
+ if (!diff.ok) return diff;
722
+ changes.set(
723
+ file,
724
+ Array.from(diff.value.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gmu), (match) => {
725
+ const start = Number(match[1]);
726
+ return { start, end: start + Math.max(Number(match[2] ?? 1), 1) - 1 };
727
+ }),
728
+ );
729
+ }
730
+ return { ok: true, value: { files, changes } };
731
+ }