@smoothbricks/nx-plugin 0.5.6 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (440) hide show
  1. package/README.md +1095 -360
  2. package/dist/.build-inputs.json +138 -0
  3. package/dist/bin/smoo-nx-cargo-toolchain.d.ts +3 -0
  4. package/dist/bin/smoo-nx-cargo-toolchain.d.ts.map +1 -0
  5. package/dist/bin/smoo-nx-cargo-toolchain.js +8 -0
  6. package/dist/bin/smoo-nx-forbidden-spellings.d.ts +3 -0
  7. package/dist/bin/smoo-nx-forbidden-spellings.d.ts.map +1 -0
  8. package/dist/bin/smoo-nx-forbidden-spellings.js +32 -0
  9. package/dist/bin/smoo-nx-nextest-timings.d.ts +3 -0
  10. package/dist/bin/smoo-nx-nextest-timings.d.ts.map +1 -0
  11. package/dist/bin/smoo-nx-nextest-timings.js +28 -0
  12. package/dist/bounded-test-policy.d.ts +1 -1
  13. package/dist/bounded-test-policy.d.ts.map +1 -1
  14. package/dist/bounded-test-policy.js +14 -15
  15. package/dist/build-state-output-policy.d.ts +95 -1
  16. package/dist/build-state-output-policy.d.ts.map +1 -1
  17. package/dist/build-state-output-policy.js +368 -30
  18. package/dist/bun-lock-scope.d.ts +44 -0
  19. package/dist/bun-lock-scope.d.ts.map +1 -0
  20. package/dist/bun-lock-scope.js +97 -0
  21. package/dist/cargo-build-script-env.d.ts +49 -0
  22. package/dist/cargo-build-script-env.d.ts.map +1 -0
  23. package/dist/cargo-build-script-env.js +324 -0
  24. package/dist/cargo-closure-input.d.ts +31 -4
  25. package/dist/cargo-closure-input.d.ts.map +1 -1
  26. package/dist/cargo-closure-input.js +66 -6
  27. package/dist/cargo-retention-hook.d.ts +17 -0
  28. package/dist/cargo-retention-hook.d.ts.map +1 -0
  29. package/dist/cargo-retention-hook.js +85 -0
  30. package/dist/cargo-source-hash.d.ts +25 -7
  31. package/dist/cargo-source-hash.d.ts.map +1 -1
  32. package/dist/cargo-source-hash.js +108 -43
  33. package/dist/cargo-toolchain-paths.d.ts +40 -0
  34. package/dist/cargo-toolchain-paths.d.ts.map +1 -0
  35. package/dist/cargo-toolchain-paths.js +84 -0
  36. package/dist/cargo-toolchain-policy.d.ts +25 -8
  37. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  38. package/dist/cargo-toolchain-policy.js +39 -5
  39. package/dist/cargo-workspace.d.ts +10 -4
  40. package/dist/cargo-workspace.d.ts.map +1 -1
  41. package/dist/cargo-workspace.js +65 -95
  42. package/dist/cross-check-policy.d.ts +9 -9
  43. package/dist/cross-check-policy.d.ts.map +1 -1
  44. package/dist/cross-check-policy.js +11 -11
  45. package/dist/disk-command-policy.d.ts.map +1 -1
  46. package/dist/disk-command-policy.js +1 -0
  47. package/dist/ensure-built-receipt.d.ts +13 -5
  48. package/dist/ensure-built-receipt.d.ts.map +1 -1
  49. package/dist/ensure-built-receipt.js +126 -47
  50. package/dist/ensure-built-witness.d.ts +27 -8
  51. package/dist/ensure-built-witness.d.ts.map +1 -1
  52. package/dist/ensure-built-witness.js +45 -15
  53. package/dist/ensure-built.d.ts.map +1 -1
  54. package/dist/ensure-built.js +9 -1
  55. package/dist/eslint-config-closure.d.ts +7 -0
  56. package/dist/eslint-config-closure.d.ts.map +1 -0
  57. package/dist/eslint-config-closure.js +346 -0
  58. package/dist/executors/all-verdicts/executor.d.ts +35 -0
  59. package/dist/executors/all-verdicts/executor.d.ts.map +1 -0
  60. package/dist/executors/all-verdicts/executor.js +133 -0
  61. package/dist/executors/all-verdicts/schema.d.ts +10 -0
  62. package/dist/executors/all-verdicts/schema.d.ts.map +1 -0
  63. package/dist/executors/all-verdicts/schema.js +2 -0
  64. package/dist/executors/bounded-exec/bounds.d.ts +56 -0
  65. package/dist/executors/bounded-exec/bounds.d.ts.map +1 -0
  66. package/dist/executors/bounded-exec/bounds.js +43 -0
  67. package/dist/executors/bounded-exec/cpu-pool.d.ts +33 -36
  68. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
  69. package/dist/executors/bounded-exec/cpu-pool.js +54 -119
  70. package/dist/executors/bounded-exec/executor.d.ts +19 -12
  71. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  72. package/dist/executors/bounded-exec/executor.js +371 -239
  73. package/dist/executors/bounded-exec/gateway-lease.d.ts +22 -19
  74. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -1
  75. package/dist/executors/bounded-exec/gateway-lease.js +81 -28
  76. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +18 -1
  77. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -1
  78. package/dist/executors/bounded-exec/hang-diagnostics.js +148 -30
  79. package/dist/executors/bounded-exec/lease-wait.d.ts +43 -0
  80. package/dist/executors/bounded-exec/lease-wait.d.ts.map +1 -0
  81. package/dist/executors/bounded-exec/lease-wait.js +68 -0
  82. package/dist/executors/bounded-exec/lock-wait.d.ts +51 -0
  83. package/dist/executors/bounded-exec/lock-wait.d.ts.map +1 -0
  84. package/dist/executors/bounded-exec/lock-wait.js +108 -0
  85. package/dist/executors/bounded-exec/owned-subtree.d.ts +84 -0
  86. package/dist/executors/bounded-exec/owned-subtree.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/owned-subtree.js +178 -0
  88. package/dist/executors/bounded-exec/progress.d.ts +4 -1
  89. package/dist/executors/bounded-exec/progress.d.ts.map +1 -1
  90. package/dist/executors/bounded-exec/progress.js +5 -2
  91. package/dist/executors/bounded-exec/ram-attach.d.ts +19 -0
  92. package/dist/executors/bounded-exec/ram-attach.d.ts.map +1 -0
  93. package/dist/executors/bounded-exec/ram-attach.js +207 -0
  94. package/dist/executors/bounded-exec/ram-detach.d.ts +25 -0
  95. package/dist/executors/bounded-exec/ram-detach.d.ts.map +1 -0
  96. package/dist/executors/bounded-exec/ram-detach.js +207 -0
  97. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +76 -0
  98. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -1
  99. package/dist/executors/bounded-exec/ram-temp-fixtures.js +296 -0
  100. package/dist/executors/bounded-exec/ram-temp.d.ts +388 -88
  101. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
  102. package/dist/executors/bounded-exec/ram-temp.js +1213 -399
  103. package/dist/executors/bounded-exec/run-cpu-pool.d.ts +4 -4
  104. package/dist/executors/bounded-exec/run-cpu-pool.d.ts.map +1 -1
  105. package/dist/executors/bounded-exec/run-cpu-pool.js +20 -30
  106. package/dist/executors/bounded-exec/runner-hook.js +14 -5
  107. package/dist/executors/bounded-exec/runner-lifecycle.d.ts +14 -1
  108. package/dist/executors/bounded-exec/runner-lifecycle.d.ts.map +1 -1
  109. package/dist/executors/bounded-exec/runner-lifecycle.js +27 -6
  110. package/dist/executors/bounded-exec/{cpu-tokens.d.ts → runner-sizing.d.ts} +14 -42
  111. package/dist/executors/bounded-exec/runner-sizing.d.ts.map +1 -0
  112. package/dist/executors/bounded-exec/{cpu-tokens.js → runner-sizing.js} +5 -35
  113. package/dist/executors/bounded-exec/runtime-pin.d.ts +73 -0
  114. package/dist/executors/bounded-exec/runtime-pin.d.ts.map +1 -0
  115. package/dist/executors/bounded-exec/runtime-pin.js +167 -0
  116. package/dist/executors/bounded-exec/schema.d.ts +18 -1
  117. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  118. package/dist/executors/bounded-exec/verdict.d.ts +40 -11
  119. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
  120. package/dist/executors/bounded-exec/verdict.js +88 -19
  121. package/dist/executors/cargo-zigbuild/executor.d.ts +21 -0
  122. package/dist/executors/cargo-zigbuild/executor.d.ts.map +1 -1
  123. package/dist/executors/cargo-zigbuild/executor.js +67 -12
  124. package/dist/executors/clean-outputs/executor.js +1 -0
  125. package/dist/executors/scriptc-native/executor.d.ts +79 -0
  126. package/dist/executors/scriptc-native/executor.d.ts.map +1 -0
  127. package/dist/executors/scriptc-native/executor.js +367 -0
  128. package/dist/executors/scriptc-native/ffi-paths.d.ts +9 -0
  129. package/dist/executors/scriptc-native/ffi-paths.d.ts.map +1 -0
  130. package/dist/executors/scriptc-native/ffi-paths.js +25 -0
  131. package/dist/executors/scriptc-native/schema.d.ts +34 -0
  132. package/dist/executors/scriptc-native/schema.d.ts.map +1 -0
  133. package/dist/executors/scriptc-native/schema.js +1 -0
  134. package/dist/executors/typescript-emit/executor.d.ts +3 -1
  135. package/dist/executors/typescript-emit/executor.d.ts.map +1 -1
  136. package/dist/executors/typescript-emit/executor.js +164 -33
  137. package/dist/forbidden-spelling-policy.d.ts +56 -0
  138. package/dist/forbidden-spelling-policy.d.ts.map +1 -0
  139. package/dist/forbidden-spelling-policy.js +176 -0
  140. package/dist/generators/create-package/generator.d.ts.map +1 -1
  141. package/dist/generators/create-package/generator.js +3 -4
  142. package/dist/graph-input-contract.d.ts +14 -0
  143. package/dist/graph-input-contract.d.ts.map +1 -1
  144. package/dist/graph-input-contract.js +67 -2
  145. package/dist/index.d.ts +23 -6
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +676 -215
  148. package/dist/managed-assets.d.ts +2 -0
  149. package/dist/managed-assets.d.ts.map +1 -1
  150. package/dist/managed-files/files.d.ts +3 -3
  151. package/dist/managed-files/files.d.ts.map +1 -1
  152. package/dist/managed-files/files.js +28 -3
  153. package/dist/managed-files/managed-format.d.ts.map +1 -1
  154. package/dist/managed-files/managed-format.js +1 -0
  155. package/dist/nextest-code-bound.js +1 -0
  156. package/dist/nextest-timings.d.ts +35 -0
  157. package/dist/nextest-timings.d.ts.map +1 -0
  158. package/dist/nextest-timings.js +168 -0
  159. package/dist/owned-installation.d.ts +6 -5
  160. package/dist/owned-installation.d.ts.map +1 -1
  161. package/dist/owned-installation.js +150 -26
  162. package/dist/package-target-policy.d.ts.map +1 -1
  163. package/dist/package-target-policy.js +2 -3
  164. package/dist/process-children.d.ts +7 -0
  165. package/dist/process-children.d.ts.map +1 -0
  166. package/dist/process-children.darwin.d.ts +7 -0
  167. package/dist/process-children.darwin.d.ts.map +1 -0
  168. package/dist/process-children.darwin.js +13 -0
  169. package/dist/process-children.js +14 -0
  170. package/dist/process-children.linux.d.ts +8 -0
  171. package/dist/process-children.linux.d.ts.map +1 -0
  172. package/dist/process-children.linux.js +25 -0
  173. package/dist/process-group.d.ts +108 -0
  174. package/dist/process-group.d.ts.map +1 -0
  175. package/dist/process-group.js +171 -0
  176. package/dist/process-listing.d.ts +7 -0
  177. package/dist/process-listing.d.ts.map +1 -0
  178. package/dist/process-listing.js +51 -0
  179. package/dist/producer-receipts.d.ts +8 -2
  180. package/dist/producer-receipts.d.ts.map +1 -1
  181. package/dist/producer-receipts.js +75 -48
  182. package/dist/task-graph-policy.d.ts +21 -0
  183. package/dist/task-graph-policy.d.ts.map +1 -0
  184. package/dist/task-graph-policy.js +91 -0
  185. package/dist/test-timings.js +4 -4
  186. package/dist/test-walk-policy.d.ts +14 -5
  187. package/dist/test-walk-policy.d.ts.map +1 -1
  188. package/dist/test-walk-policy.js +8 -2
  189. package/dist/testing.d.ts +73 -28
  190. package/dist/testing.d.ts.map +1 -1
  191. package/dist/testing.js +217 -223
  192. package/dist/tool-bins.d.ts +33 -0
  193. package/dist/tool-bins.d.ts.map +1 -0
  194. package/dist/tool-bins.js +72 -0
  195. package/dist/typecheck-test-policy.d.ts.map +1 -1
  196. package/dist/typecheck-test-policy.js +3 -4
  197. package/dist/wait-why-policy.d.ts +28 -0
  198. package/dist/wait-why-policy.d.ts.map +1 -0
  199. package/dist/wait-why-policy.js +223 -0
  200. package/dist/workspace-config-policy.d.ts +14 -8
  201. package/dist/workspace-config-policy.d.ts.map +1 -1
  202. package/dist/workspace-config-policy.js +60 -16
  203. package/dist/workspace-manifest.d.ts +41 -6
  204. package/dist/workspace-manifest.d.ts.map +1 -1
  205. package/dist/workspace-manifest.js +57 -0
  206. package/executors.json +21 -1
  207. package/loader.js +2 -0
  208. package/managed/raw/envrc +11 -0
  209. package/managed/raw/patches/nx@23.2.1.patch +2840 -199
  210. package/managed/raw/patches/ttsc@0.34.1.patch +119 -0
  211. package/managed/raw/tooling/direnv/cargo-fetch-bound.ts +245 -0
  212. package/managed/raw/tooling/direnv/cargo-fetch-run.ts +299 -0
  213. package/managed/raw/tooling/direnv/compiler-variables.sh +42 -0
  214. package/managed/raw/tooling/direnv/developer-links.ts +464 -25
  215. package/managed/raw/tooling/direnv/devenv.smoo.nix +78 -38
  216. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -12
  217. package/managed/raw/tooling/direnv/installed-bun-links.ts +308 -0
  218. package/managed/raw/tooling/direnv/linked-snapshots.ts +62 -3
  219. package/managed/raw/tooling/direnv/nx-socket-dir.sh +56 -17
  220. package/managed/raw/tooling/direnv/repo-path +68 -6
  221. package/managed/raw/tooling/direnv/secret-references.ts +13 -4
  222. package/managed/raw/tooling/direnv/setup-environment.ts +128 -537
  223. package/managed/raw/tooling/direnv/toolchain-stamp.ts +4 -2
  224. package/managed/raw/tooling/direnv/ttsc-env.sh +9 -0
  225. package/managed/raw/tooling/direnv/uv-relocation.ts +227 -0
  226. package/managed/raw/tooling/git-hooks/commit-msg.sh +2 -1
  227. package/managed/raw/tooling/git-hooks/pre-commit.sh +2 -1
  228. package/managed/raw/tooling/git-hooks/pre-push.sh +2 -1
  229. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +85 -7
  230. package/managed/templates/github/actions/save-nix-devenv/action.yml +12 -2
  231. package/managed/templates/github/actions/setup-devenv/action.yml +2 -0
  232. package/package.json +77 -13
  233. package/src/bin/smoo-nx-cargo-toolchain.ts +11 -0
  234. package/src/bin/smoo-nx-forbidden-spellings.ts +33 -0
  235. package/src/bin/smoo-nx-nextest-timings.ts +31 -0
  236. package/src/bounded-test-policy.ts +12 -14
  237. package/src/build-state-output-policy.ts +458 -34
  238. package/src/bun-lock-scope.ts +108 -0
  239. package/src/cargo-build-script-env.ts +265 -0
  240. package/src/cargo-closure-input.ts +74 -7
  241. package/src/cargo-retention-hook.ts +94 -0
  242. package/src/cargo-source-hash.ts +138 -41
  243. package/src/cargo-toolchain-paths.ts +95 -0
  244. package/src/cargo-toolchain-policy.ts +49 -5
  245. package/src/cargo-workspace.ts +72 -123
  246. package/src/cross-check-policy.ts +12 -10
  247. package/src/disk-command-policy.ts +1 -0
  248. package/src/ensure-built-receipt.ts +132 -39
  249. package/src/ensure-built-witness.ts +62 -10
  250. package/src/ensure-built.ts +11 -1
  251. package/src/eslint-config-closure.ts +357 -0
  252. package/src/executors/all-verdicts/executor.ts +164 -0
  253. package/src/executors/all-verdicts/schema.json +22 -0
  254. package/src/executors/all-verdicts/schema.ts +10 -0
  255. package/src/executors/bounded-exec/bounds.ts +76 -0
  256. package/src/executors/bounded-exec/cpu-pool.ts +51 -117
  257. package/src/executors/bounded-exec/executor.ts +423 -259
  258. package/src/executors/bounded-exec/gateway-lease.ts +82 -33
  259. package/src/executors/bounded-exec/hang-diagnostics.ts +173 -31
  260. package/src/executors/bounded-exec/lease-wait.ts +89 -0
  261. package/src/executors/bounded-exec/lock-wait.ts +141 -0
  262. package/src/executors/bounded-exec/owned-subtree.ts +235 -0
  263. package/src/executors/bounded-exec/progress.ts +9 -3
  264. package/src/executors/bounded-exec/ram-attach.ts +238 -0
  265. package/src/executors/bounded-exec/ram-detach.ts +226 -0
  266. package/src/executors/bounded-exec/ram-temp-fixtures.ts +358 -0
  267. package/src/executors/bounded-exec/ram-temp-registry.txt +440 -0
  268. package/src/executors/bounded-exec/ram-temp.ts +1497 -460
  269. package/src/executors/bounded-exec/run-cpu-pool.ts +22 -30
  270. package/src/executors/bounded-exec/runner-hook.ts +14 -6
  271. package/src/executors/bounded-exec/runner-lifecycle.ts +31 -8
  272. package/src/executors/bounded-exec/{cpu-tokens.ts → runner-sizing.ts} +13 -59
  273. package/src/executors/bounded-exec/runtime-pin.ts +232 -0
  274. package/src/executors/bounded-exec/schema.json +11 -2
  275. package/src/executors/bounded-exec/schema.ts +19 -1
  276. package/src/executors/bounded-exec/verdict.ts +137 -34
  277. package/src/executors/cargo-zigbuild/executor.ts +82 -8
  278. package/src/executors/clean-outputs/executor.ts +1 -0
  279. package/src/executors/scriptc-native/executor.ts +394 -0
  280. package/src/executors/scriptc-native/ffi-paths.ts +29 -0
  281. package/src/executors/scriptc-native/schema.json +60 -0
  282. package/src/executors/scriptc-native/schema.ts +34 -0
  283. package/src/executors/typescript-emit/executor.ts +205 -38
  284. package/src/forbidden-spelling-policy.ts +226 -0
  285. package/src/generators/create-package/generator.ts +7 -7
  286. package/src/graph-input-contract.ts +61 -2
  287. package/src/index.ts +792 -225
  288. package/src/managed-assets.ts +3 -0
  289. package/src/managed-files/files.ts +28 -3
  290. package/src/managed-files/managed-format.ts +1 -0
  291. package/src/nextest-code-bound.ts +1 -0
  292. package/src/nextest-timings.ts +106 -0
  293. package/src/owned-installation.ts +150 -23
  294. package/src/package-target-policy.ts +2 -3
  295. package/src/process-children.darwin.ts +14 -0
  296. package/src/process-children.linux.ts +33 -0
  297. package/src/process-children.ts +22 -0
  298. package/src/process-group.ts +209 -0
  299. package/src/process-listing.ts +54 -0
  300. package/src/producer-receipts.ts +68 -45
  301. package/src/task-graph-policy.ts +98 -0
  302. package/src/test-walk-policy.ts +23 -8
  303. package/src/testing.ts +240 -232
  304. package/src/tool-bins.ts +108 -0
  305. package/src/typecheck-test-policy.ts +2 -3
  306. package/src/wait-why-policy.ts +226 -0
  307. package/src/workspace-config-policy.ts +63 -15
  308. package/src/workspace-manifest.ts +89 -6
  309. package/test-timings.json +123 -98
  310. package/dist/bin/smoo-nx-failures.d.ts +0 -3
  311. package/dist/bin/smoo-nx-failures.d.ts.map +0 -1
  312. package/dist/bin/smoo-nx-failures.js +0 -3
  313. package/dist/bin/smoo-nx-nextest-extract.d.ts +0 -3
  314. package/dist/bin/smoo-nx-nextest-extract.d.ts.map +0 -1
  315. package/dist/bin/smoo-nx-nextest-extract.js +0 -42
  316. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +0 -1
  317. package/dist/failure-summary.d.ts +0 -5
  318. package/dist/failure-summary.d.ts.map +0 -1
  319. package/dist/failure-summary.js +0 -118
  320. package/dist/nextest-extraction.d.ts +0 -117
  321. package/dist/nextest-extraction.d.ts.map +0 -1
  322. package/dist/nextest-extraction.js +0 -303
  323. package/managed/raw/patches/ttsc@0.30.4.patch +0 -2255
  324. package/src/__tests__/cargo-closure-filesets.ts +0 -94
  325. package/src/__tests__/cargo-closure-fixture.ts +0 -113
  326. package/src/__tests__/counted-cargo-process.ts +0 -286
  327. package/src/__tests__/counted-cargo.ts +0 -713
  328. package/src/__tests__/directory-change.ts +0 -27
  329. package/src/__tests__/fixture-cargo-home.ts +0 -36
  330. package/src/__tests__/fixture-nx-env.ts +0 -193
  331. package/src/__tests__/owned-installation.ts +0 -13
  332. package/src/__tests__/past-tick.ts +0 -12
  333. package/src/__tests__/progress-clock.ts +0 -43
  334. package/src/__tests__/runtime-input.ts +0 -23
  335. package/src/bin/smoo-nx-bound-failures.test.ts +0 -127
  336. package/src/bin/smoo-nx-failures.ts +0 -4
  337. package/src/bin/smoo-nx-nextest-extract.ts +0 -44
  338. package/src/bounded-test-policy.test.ts +0 -1029
  339. package/src/build-state-output-policy.test.ts +0 -115
  340. package/src/bun-bootstrap.test.ts +0 -102
  341. package/src/bun-file-packages.test.ts +0 -47
  342. package/src/cargo-closure-filesets.test.ts +0 -63
  343. package/src/cargo-closure-input.property.test.ts +0 -50
  344. package/src/cargo-closure-input.test.ts +0 -506
  345. package/src/cargo-closure-key.test.ts +0 -240
  346. package/src/cargo-resolve-cache.test.ts +0 -1181
  347. package/src/cargo-source-hash.test.ts +0 -707
  348. package/src/cargo-workspace.test.ts +0 -615
  349. package/src/cross-check-policy.test.ts +0 -316
  350. package/src/disk-command-policy.test.ts +0 -61
  351. package/src/ensure-built-receipt.test.ts +0 -279
  352. package/src/ensure-built-witness.test.ts +0 -688
  353. package/src/ensure-built.test.ts +0 -1462
  354. package/src/executors/bounded-exec/cargo-progress-host.test.ts +0 -332
  355. package/src/executors/bounded-exec/cpu-pool.test.ts +0 -684
  356. package/src/executors/bounded-exec/cpu-tokens.test.ts +0 -519
  357. package/src/executors/bounded-exec/disk-lease.test.ts +0 -219
  358. package/src/executors/bounded-exec/executor-host.test.ts +0 -800
  359. package/src/executors/bounded-exec/executor.test.ts +0 -1819
  360. package/src/executors/bounded-exec/go-progress-host.test.ts +0 -171
  361. package/src/executors/bounded-exec/hang-diagnostics.test.ts +0 -291
  362. package/src/executors/bounded-exec/progress.test.ts +0 -139
  363. package/src/executors/bounded-exec/ram-temp-held.test.ts +0 -264
  364. package/src/executors/bounded-exec/ram-temp-host.test.ts +0 -635
  365. package/src/executors/bounded-exec/ram-temp.test.ts +0 -750
  366. package/src/executors/bounded-exec/run-cpu-pool.test.ts +0 -79
  367. package/src/executors/bounded-exec/runner-hook.test.ts +0 -193
  368. package/src/executors/bounded-exec/runner-lifecycle.test.ts +0 -82
  369. package/src/executors/bounded-exec/verdict.test.ts +0 -545
  370. package/src/executors/cargo-zigbuild/executor.test.ts +0 -129
  371. package/src/executors/clean-outputs/executor.test.ts +0 -20
  372. package/src/executors/typescript-emit/executor.test.ts +0 -83
  373. package/src/failure-summary.ts +0 -119
  374. package/src/generators/bounded-test-targets/generator.test.ts +0 -138
  375. package/src/generators/bun-test-tracing/generator.test.ts +0 -250
  376. package/src/generators/create-package/generator.test.ts +0 -190
  377. package/src/generators/make-public/generator.test.ts +0 -137
  378. package/src/graph-input-contract.test.ts +0 -379
  379. package/src/host-controller-wiring.test.ts +0 -31
  380. package/src/index.test.ts +0 -3319
  381. package/src/linked-snapshots.nx.test.ts +0 -254
  382. package/src/managed-files/forgejo-artifact.test.ts +0 -395
  383. package/src/managed-files/generator.test.ts +0 -243
  384. package/src/managed-files/github-host-cache-isolation.test.ts +0 -86
  385. package/src/managed-files/json-edit.test.ts +0 -216
  386. package/src/managed-files/managed-content.test.ts +0 -166
  387. package/src/managed-files/managed-format-json.test.ts +0 -308
  388. package/src/managed-files/repo-path.test.ts +0 -172
  389. package/src/managed-files/setup-devenv-free-disk.test.ts +0 -95
  390. package/src/managed-files/trace-db-artifact.test.ts +0 -7
  391. package/src/managed-files/tree-permissions.test.ts +0 -109
  392. package/src/managed-files/tree.test.ts +0 -123
  393. package/src/manifest-hash.test.ts +0 -219
  394. package/src/nextest-code-bound.test.ts +0 -161
  395. package/src/nextest-extraction.test.ts +0 -216
  396. package/src/nextest-extraction.ts +0 -371
  397. package/src/nextest-partitions.test.ts +0 -501
  398. package/src/nx-cache-bound.test.ts +0 -109
  399. package/src/nx-cache-restore-mtime.test.ts +0 -170
  400. package/src/nx-daemon-claim.test.ts +0 -279
  401. package/src/nx-daemon-idle-cpu.test.ts +0 -80
  402. package/src/nx-daemon-idle-policy.test.ts +0 -111
  403. package/src/nx-daemon-ignore-files.test.ts +0 -210
  404. package/src/nx-daemon-root-normalization.test.ts +0 -105
  405. package/src/nx-daemon-start-never.test.ts +0 -292
  406. package/src/nx-daemon-validity.test.ts +0 -1055
  407. package/src/nx-dot-input-policy.test.ts +0 -353
  408. package/src/nx-failure-life-cycles.test.ts +0 -207
  409. package/src/nx-files-archive-racy.test.ts +0 -97
  410. package/src/nx-foreign-workspace-env.test.ts +0 -329
  411. package/src/nx-incomplete-run-summary.test.ts +0 -70
  412. package/src/nx-plugin-load-errors.test.ts +0 -120
  413. package/src/nx-project-graph-errors.test.ts +0 -70
  414. package/src/nx-project-resolution-cache.test.ts +0 -176
  415. package/src/nx-raw-inputs.test.ts +0 -166
  416. package/src/nx-resident-graph-workers.test.ts +0 -112
  417. package/src/nx-run-information.test.ts +0 -118
  418. package/src/nx-skipped-task-exit.test.ts +0 -180
  419. package/src/nx-state-location.test.ts +0 -63
  420. package/src/nx-store-resolution.test.ts +0 -81
  421. package/src/nx-task-graph-cycles.test.ts +0 -148
  422. package/src/nx-task-output-lease.test.ts +0 -550
  423. package/src/nx-use-local.test.ts +0 -105
  424. package/src/owned-installation.test.ts +0 -105
  425. package/src/package-target-policy.test.ts +0 -1014
  426. package/src/producer-receipts.test.ts +0 -285
  427. package/src/release-config-policy.test.ts +0 -311
  428. package/src/runtime-input.test.ts +0 -393
  429. package/src/serial-group-wiring.test.ts +0 -326
  430. package/src/task-history-namespace.test.ts +0 -181
  431. package/src/task-results.test.ts +0 -228
  432. package/src/test-clock-policy.test.ts +0 -338
  433. package/src/test-program.test.ts +0 -303
  434. package/src/test-timings.test.ts +0 -240
  435. package/src/test-walk-policy.test.ts +0 -620
  436. package/src/testing.test.ts +0 -509
  437. package/src/typecheck-test-policy.test.ts +0 -1468
  438. package/src/typescript-resolution.test.ts +0 -76
  439. package/src/version-actions.test.ts +0 -80
  440. package/src/workspace-config-policy.test.ts +0 -737
package/src/index.test.ts DELETED
@@ -1,3319 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { chmod, mkdir, mkdtemp, readdir, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import { dirname, join } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
- import { isEslintFileSet } from '@smoothbricks/nx-plugin/eslint-file-set';
7
- import type {
8
- CreateNodesContextV2,
9
- CreateNodesV2,
10
- ProjectGraph,
11
- ProjectGraphProjectNode,
12
- TargetConfiguration,
13
- } from 'nx/src/devkit-exports.js';
14
- import { WorkspaceContext } from 'nx/src/native/index.js';
15
- import { AggregateCreateNodesError } from 'nx/src/project-graph/error-types.js';
16
- import { createTargetDefaultsResults } from 'nx/src/project-graph/utils/project-configuration/target-defaults.js';
17
- import { mergeTargetConfigurations } from 'nx/src/project-graph/utils/project-configuration-utils.js';
18
- import { createTaskGraph } from 'nx/src/tasks-runner/create-task-graph.js';
19
- import { getOutputsForTargetAndConfiguration } from 'nx/src/tasks-runner/utils.js';
20
- import { resetWorkspaceContext } from 'nx/src/utils/workspace-context.js';
21
- import { useFixtureCargoHome } from './__tests__/fixture-cargo-home.js';
22
- import { runtimeInputValue } from './__tests__/runtime-input.js';
23
- import { BOUNDED_TEST_IDLE_TIMEOUT_MS, BOUNDED_TEST_KILL_AFTER_MS } from './bounded-test-policy.js';
24
- import { CARGO_CLOSURE_INPUT } from './cargo-closure-input.js';
25
- import { exceptionalTestFilter, packageNameFromCargoTestTarget } from './cargo-workspace.js';
26
- import { CARGO_CROSS_LINT_COMMAND, CARGO_CROSS_LINT_TARGET, CARGO_LINT_CLIPPY_COMMAND } from './cross-check-policy.js';
27
- import { cargoCommandNpmPackages, createNodesV2, createNodesV2ForPlatform } from './index.js';
28
- import { NEXTEST_EXTRACTION_DIRECTORY } from './nextest-extraction.js';
29
- import { applyWorkspaceConfig, RELEASE_CONFIGURATION } from './workspace-config-policy.js';
30
-
31
- useFixtureCargoHome();
32
-
33
- const [, rawInferTargets] = createNodesV2;
34
- const inferTargets: typeof rawInferTargets = async (files, options, context) => {
35
- await prepareCargoFixture(context.workspaceRoot);
36
- return rawInferTargets(files, options, context);
37
- };
38
-
39
- describe('@smoothbricks/nx-plugin inferred targets', () => {
40
- it('never lets a cache hit on the build aggregate restore its children’s dist', async () => {
41
- const workspace = await createWorkspace();
42
- // The emitter keys on one input outside its project, as a transform or toolchain does. The
43
- // aggregate hashes only the project, so a toolchain change moves the emitter's key and not the
44
- // aggregate's: the aggregate replays from cache right after the emitter reran.
45
- const emit: TargetConfiguration = {
46
- executor: 'nx:run-commands',
47
- cache: true,
48
- inputs: ['{projectRoot}/source.txt', '{workspaceRoot}/toolchain.txt'],
49
- outputs: ['{projectRoot}/dist'],
50
- options: { command: 'mkdir -p dist && cat source.txt ../../toolchain.txt > dist/app.js', cwd: '{projectRoot}' },
51
- };
52
- const declared = { 'emit-js': emit };
53
- try {
54
- await workspace.write(
55
- 'packages/app/package.json',
56
- JSON.stringify({ name: 'app', private: true, nx: { targets: declared } }),
57
- );
58
- const targets = await inferProjectTargets(workspace, 'packages/app/package.json');
59
- const build = resolveDeclaredOverInferred(targets, declared, 'build');
60
- expect(build?.dependsOn).toContain('emit-js');
61
- expect(build?.cache).toBe(true);
62
- if (build === undefined) throw new Error('app infers no build aggregate over emit-js');
63
-
64
- // A replay restores exactly what Nx resolves as the task's outputs. Left without `outputs`, a
65
- // `build` target gets Nx's legacy defaults, `{projectRoot}/dist` among them, and the replay
66
- // puts back the dist the emitter wrote on the run that last produced the aggregate's key.
67
- const app: ProjectGraphProjectNode = {
68
- name: 'app',
69
- type: 'lib',
70
- data: { root: 'packages/app', targets: { build, 'emit-js': emit } },
71
- };
72
- expect(getOutputsForTargetAndConfiguration({ project: 'app', target: 'build' }, {}, app)).toEqual([]);
73
- expect(getOutputsForTargetAndConfiguration({ project: 'app', target: 'emit-js' }, {}, app)).toEqual([
74
- 'packages/app/dist',
75
- ]);
76
- } finally {
77
- await workspace.cleanup();
78
- }
79
- });
80
-
81
- it('names standalone package projects from package metadata', async () => {
82
- const workspace = await createWorkspace();
83
- try {
84
- await workspace.write(
85
- 'specs/prototype/package.json',
86
- '{"name":"standalone-package","nx":{"name":"standalone-project"}}\n',
87
- );
88
- await workspace.write('specs/package-fallback/package.json', '{"name":"package-fallback"}\n');
89
-
90
- const explicit = await inferProject(workspace, 'specs/prototype/package.json');
91
- const fallback = await inferProject(workspace, 'specs/package-fallback/package.json');
92
-
93
- expect(explicit?.name).toBe('standalone-project');
94
- expect(explicit?.targets).toEqual({});
95
- expect(fallback?.name).toBe('package-fallback');
96
- expect(fallback?.targets).toEqual({});
97
- } finally {
98
- await workspace.cleanup();
99
- }
100
- });
101
-
102
- it('skips smoo managed raw package.json sources as projects', async () => {
103
- const workspace = await createWorkspace();
104
- try {
105
- await workspace.write(
106
- 'packages/nx-plugin/managed/raw/tooling/typescript-api/package.json',
107
- '{"name":"@smoothbricks/typescript-api","private":true}\n',
108
- );
109
- await workspace.write(
110
- 'tooling/typescript-api/package.json',
111
- '{"name":"@smoothbricks/typescript-api","private":true}\n',
112
- );
113
-
114
- const managed = await inferTargets(
115
- ['packages/nx-plugin/managed/raw/tooling/typescript-api/package.json'],
116
- undefined,
117
- workspace.context,
118
- );
119
- expect(managed[0]?.[1]).toEqual({});
120
-
121
- const live = await inferProject(workspace, 'tooling/typescript-api/package.json');
122
- expect(live?.name).toBe('@smoothbricks/typescript-api');
123
- } finally {
124
- await workspace.cleanup();
125
- }
126
- });
127
-
128
- it('never infers a project from a package.json a build wrote', async () => {
129
- const workspace = await createWorkspace();
130
- try {
131
- await workspace.write('packages/cowshed/package.json', '{"name":"cowshed","private":true}\n');
132
- // napi's platform build, a dist tree, cargo's target dir, a package cache: every
133
- // one of these is written by a task, and a graph recomputed while it is being
134
- // written must not see a second `cowshed` and drop the real one.
135
- const outputs = [
136
- 'packages/cowshed/.cache/native-debug/package.json',
137
- 'packages/cowshed/dist/npm/linux-x64-gnu/package.json',
138
- 'packages/cowshed/target/debug/build/x/out/package.json',
139
- 'packages/cowshed/node_modules/dep/package.json',
140
- ];
141
- for (const path of outputs) {
142
- await workspace.write(path, '{"name":"cowshed","private":true}\n');
143
- }
144
-
145
- const inferred = await inferTargets(outputs, undefined, workspace.context);
146
- for (const [, result] of inferred) {
147
- expect(result).toEqual({});
148
- }
149
- const live = await inferProject(workspace, 'packages/cowshed/package.json');
150
- expect(live?.name).toBe('cowshed');
151
- } finally {
152
- await workspace.cleanup();
153
- }
154
- });
155
-
156
- it('keys installed patch data and pins without keying patch documentation', async () => {
157
- const workspace = await createWorkspace();
158
- try {
159
- await workspace.write('packages/example/package.json', '{"name":"example","scripts":{"test":"bun test"}}\n');
160
- await workspace.write('packages/example/tsconfig.lib.json', '{}\n');
161
- await workspace.write('packages/example/tsconfig.test.json', '{}\n');
162
- await workspace.write('patches/nx.patch', 'patch-one\n');
163
- await workspace.write('patches/compiler/PIN', 'revision-one\n');
164
- await workspace.write('patches/compiler/VERSION', 'version-one\n');
165
- await workspace.write('patches/README.md', 'documentation-one\n');
166
- await workspace.write('patches/compiler/notes.md', 'nested documentation-one\n');
167
- await workspace.write('packages/unrelated/source.ts', 'export const value = 1;\n');
168
- const targets = await inferProjectTargets(workspace, 'packages/example/package.json');
169
- const context = new WorkspaceContext(
170
- workspace.context.workspaceRoot,
171
- join(workspace.context.workspaceRoot, '.nx/patch-input-context'),
172
- );
173
- for (const name of ['tsc-js', 'typecheck', 'typecheck-tests', 'lint']) {
174
- const inputs = targets[name]?.inputs ?? [];
175
- const patchInputs = inputs.filter(
176
- (input): input is string => typeof input === 'string' && input.includes('{workspaceRoot}/patches/'),
177
- );
178
- expect(patchInputs.length).toBeGreaterThan(0);
179
- const positive = patchInputs
180
- .filter((input) => !input.startsWith('!'))
181
- .map((input) => input.slice('{workspaceRoot}/'.length));
182
- const negative = patchInputs
183
- .filter((input) => input.startsWith('!'))
184
- .map((input) => input.slice('!{workspaceRoot}/'.length));
185
- expect(context.glob(positive, negative).sort()).toEqual([
186
- 'patches/compiler/PIN',
187
- 'patches/compiler/VERSION',
188
- 'patches/nx.patch',
189
- ]);
190
- const before = context.hashFilesMatchingGlob(positive, negative);
191
- await workspace.write('patches/README.md', name + ' docs\n');
192
- await workspace.write('patches/compiler/notes.md', name + ' nested docs\n');
193
- await workspace.write('packages/unrelated/source.ts', 'export const value = ' + name.length + ';\n');
194
- context.incrementalUpdate(
195
- ['patches/README.md', 'patches/compiler/notes.md', 'packages/unrelated/source.ts'],
196
- [],
197
- );
198
- expect(context.hashFilesMatchingGlob(positive, negative)).toBe(before);
199
- let previous = before;
200
- for (const file of ['patches/nx.patch', 'patches/compiler/PIN', 'patches/compiler/VERSION']) {
201
- await workspace.write(file, name + ' changed ' + file + '\n');
202
- context.incrementalUpdate([file], []);
203
- const changed = context.hashFilesMatchingGlob(positive, negative);
204
- expect(changed).not.toBe(previous);
205
- previous = changed;
206
- }
207
- }
208
- } finally {
209
- await workspace.cleanup();
210
- }
211
- });
212
-
213
- it('uses the transformer-aware compiler for emit and validation', async () => {
214
- const workspace = await createWorkspace();
215
- try {
216
- await workspace.write(
217
- 'packages/example/package.json',
218
- '{"name":"example","bin":{"example":"./dist/bin/example.js"},"scripts":{"test":"bun test --pass-with-no-tests"}}\n',
219
- );
220
- await workspace.write('packages/example/tsconfig.lib.json', '{}\n');
221
- await workspace.write('packages/example/tsconfig.test.json', '{}\n');
222
-
223
- const targets = await inferProjectTargets(workspace, 'packages/example/package.json');
224
-
225
- expect(targets['tsc-js']?.executor).toBe('@smoothbricks/nx-plugin:typescript-emit');
226
- expect(targets['tsc-js']?.options).toEqual({
227
- executableOutputs: ['./dist/bin/example.js'],
228
- tsConfig: 'tsconfig.lib.json',
229
- cwd: 'packages/example',
230
- });
231
- const toolchainInputs = [
232
- '{workspaceRoot}/package.json',
233
- '{workspaceRoot}/bun.lock',
234
- '{workspaceRoot}/patches/**/*',
235
- '!{workspaceRoot}/patches/**/*.md',
236
- '{workspaceRoot}/tsconfig.base.json',
237
- ];
238
- // An emit is a shipped artifact: it hashes the raw manifests, so a
239
- // version bump reruns it rather than restoring a stale one.
240
- expect(targets['tsc-js']?.inputs).toEqual([
241
- 'production',
242
- '^production',
243
- ...toolchainInputs,
244
- '{projectRoot}/tsconfig.lib.json',
245
- ]);
246
- expect(targets['tsc-js']?.outputs).toEqual(['{projectRoot}/dist/**/*.{js,cjs,mjs,jsx,d.ts,d.cts,d.mts}{,.map}']);
247
- // Typecheck runs the compiler devenv.smoo.nix pins (SMOO_TYPECHECK_TSC) itself, not through
248
- // ttsc, whose auto-loaded transform plugins would check with their own compiler; and it refuses
249
- // to fall back to another when the shell does not provide it.
250
- const typecheckCompiler =
251
- '"${SMOO_TYPECHECK_TSC:?is unset, enter the devenv shell (devenv.smoo.nix builds the typecheck compiler)}"';
252
- expect(targets.typecheck?.options).toMatchObject({
253
- command: `${typecheckCompiler} -p tsconfig.lib.json --noEmit`,
254
- cwd: 'packages/example',
255
- });
256
- const checkToolchainInputs = [
257
- '{workspaceRoot}/patches/**/*',
258
- '!{workspaceRoot}/patches/**/*.md',
259
- '{workspaceRoot}/tsconfig.base.json',
260
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
261
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
262
- ];
263
- // The compiler's store path names its pinned revision, so a compiler bump misses the cache.
264
- expect(targets.typecheck?.inputs).toEqual([
265
- 'versionlessProduction',
266
- '^production',
267
- ...checkToolchainInputs,
268
- { env: 'SMOO_TYPECHECK_TSC' },
269
- '{projectRoot}/tsconfig.lib.json',
270
- ]);
271
- expect(targets.build?.executor).toBe('nx:noop');
272
- expect(targets.build?.cache).toBe(true);
273
- expect(targets.build?.dependsOn).toEqual(['^build', 'tsc-js']);
274
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
275
- expect(targets.clean?.cache).toBe(false);
276
-
277
- expect(targets['typecheck-tests']?.executor).toBe('nx:run-commands');
278
- expect(targets['typecheck-tests']?.cache).toBe(true);
279
- expect(targets['typecheck-tests']?.dependsOn).toEqual(['tsc-js', 'typecheck']);
280
- expect(targets['typecheck-tests']?.options).toMatchObject({
281
- command: `${typecheckCompiler} -p tsconfig.test.json --noEmit`,
282
- cwd: 'packages/example',
283
- });
284
- expect(targets['typecheck-tests']?.inputs).toEqual([
285
- 'versionlessDefault',
286
- '^production',
287
- ...checkToolchainInputs,
288
- { env: 'SMOO_TYPECHECK_TSC' },
289
- '{projectRoot}/tsconfig.test.json',
290
- ]);
291
-
292
- expect(targets['typecheck-tests:watch']?.executor).toBe('nx:run-commands');
293
- expect(targets['typecheck-tests:watch']?.continuous).toBe(true);
294
- expect(targets['typecheck-tests:watch']?.options).toMatchObject({
295
- command: `${typecheckCompiler} -p tsconfig.test.json --noEmit --watch`,
296
- cwd: 'packages/example',
297
- });
298
-
299
- expect(targets['test-watch']?.executor).toBe('nx:run-commands');
300
- expect(targets['test-watch']?.continuous).toBe(true);
301
- expect(targets['test-watch']?.dependsOn).toEqual(['typecheck-tests']);
302
- expect(targets['test-watch']?.options).toMatchObject({
303
- command: 'bun test --watch --pass-with-no-tests',
304
- cwd: 'packages/example',
305
- });
306
-
307
- expect(targets.lint?.cache).toBe(true);
308
- expect(targets.lint?.dependsOn).toEqual(['typecheck-tests']);
309
- expect(targets.lint?.inputs).toContain('^production');
310
- } finally {
311
- await workspace.cleanup();
312
- }
313
- });
314
-
315
- it('hashes the manifests without their versions for checks, raw for artifacts', async () => {
316
- const workspace = await createWorkspace();
317
- try {
318
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
319
- await workspace.write('packages/example/tsconfig.lib.json', '{}\n');
320
- await workspace.write('packages/example/tsconfig.test.json', '{}\n');
321
-
322
- const project = await inferProjectWithNxJson(workspace, 'packages/example/package.json', {
323
- namedInputs: { versionlessProduction: ['production'] },
324
- });
325
- const targets = project?.targets ?? {};
326
- const checkToolchain = [
327
- '{workspaceRoot}/patches/**/*',
328
- '!{workspaceRoot}/patches/**/*.md',
329
- '{workspaceRoot}/tsconfig.base.json',
330
- // Hashed by Nx itself: a `json` input costs no process, and neither
331
- // does the crate digest that replaces the manifests below.
332
- // The root manifest's scripts, smoo and nx sections are read by no check: an
333
- // edit to a script or a developer link must not re-key every lint and typecheck.
334
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
335
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
336
- ];
337
-
338
- // No crate manifest in this project, so no crate digest is declared at
339
- // all — nothing is hashed that nothing reads.
340
- expect(project?.namedInputs).toEqual({
341
- versionlessProduction: [
342
- 'production',
343
- '!{projectRoot}/package.json',
344
- { json: '{projectRoot}/package.json', excludeFields: ['version'] },
345
- ],
346
- versionlessDefault: [
347
- 'default',
348
- '!{projectRoot}/package.json',
349
- { json: '{projectRoot}/package.json', excludeFields: ['version'] },
350
- ],
351
- });
352
- expect(targets.typecheck?.inputs).toEqual([
353
- 'versionlessProduction',
354
- { input: 'versionlessProduction', dependencies: true },
355
- ...checkToolchain,
356
- { env: 'SMOO_TYPECHECK_TSC' },
357
- '{projectRoot}/tsconfig.lib.json',
358
- ]);
359
- expect(targets['typecheck-tests']?.inputs).toEqual([
360
- 'versionlessDefault',
361
- { input: 'versionlessProduction', dependencies: true },
362
- ...checkToolchain,
363
- { env: 'SMOO_TYPECHECK_TSC' },
364
- '{projectRoot}/tsconfig.test.json',
365
- ]);
366
- expect(targets.lint?.inputs).toEqual([
367
- 'versionlessDefault',
368
- { input: 'versionlessProduction', dependencies: true },
369
- ...checkToolchain,
370
- ...[
371
- 'biome.json',
372
- 'biome.jsonc',
373
- 'eslint.config.js',
374
- 'eslint.config.mjs',
375
- 'eslint.config.cjs',
376
- 'eslint.config.ts',
377
- 'eslint.config.mts',
378
- 'eslint.config.cts',
379
- ].flatMap((name) => [`{workspaceRoot}/${name}`, `{projectRoot}/${name}`]),
380
- '{workspaceRoot}/tooling/checks/**/*',
381
- ]);
382
-
383
- // The guard this whole treatment lives or dies on. A declaration emit is
384
- // a shipped artifact, and a crate compiled beside it embeds its version
385
- // through `env!("CARGO_PKG_VERSION")`, so an artifact target that stopped
386
- // hashing the raw manifests could hit a pre-bump entry and publish a
387
- // binary reporting the previous version.
388
- expect(targets['tsc-js']?.inputs).toEqual([
389
- 'production',
390
- '^production',
391
- '{workspaceRoot}/package.json',
392
- '{workspaceRoot}/bun.lock',
393
- '{workspaceRoot}/patches/**/*',
394
- '!{workspaceRoot}/patches/**/*.md',
395
- '{workspaceRoot}/tsconfig.base.json',
396
- '{projectRoot}/tsconfig.lib.json',
397
- ]);
398
- } finally {
399
- await workspace.cleanup();
400
- }
401
- });
402
-
403
- it('hashes crate manifests into a digest, only where crates exist', async () => {
404
- const workspace = await createWorkspace();
405
- try {
406
- const manifest = (version: string) =>
407
- `[package]\nname = "rust-example"\nversion = "${version}"\n\n[dependencies]\nserde = { version = "1.0.200" }\n`;
408
- await workspace.write('packages/rust/package.json', '{"name":"rust-example"}\n');
409
- await workspace.write('packages/rust/tsconfig.lib.json', '{}\n');
410
- await workspace.write('packages/rust/Cargo.toml', manifest('0.1.0'));
411
- const production = async () =>
412
- (await inferProjectWithNxJson(workspace, 'packages/rust/package.json', {}))?.namedInputs?.versionlessProduction;
413
-
414
- const baseline = await production();
415
-
416
- // TOML has no `json` input, so this is the one manifest kind the plugin
417
- // hashes itself. There is no command behind it: the value IS the input,
418
- // and Nx hashes it through the project configuration.
419
- expect(baseline).toEqual([
420
- 'production',
421
- '!{projectRoot}/package.json',
422
- { json: '{projectRoot}/package.json', excludeFields: ['version'] },
423
- '!{projectRoot}/**/Cargo.toml',
424
- expect.stringMatching(/^\{projectRoot\}\/\.versionless-crate-manifests\/[0-9a-f]{64}$/),
425
- ]);
426
-
427
- // What the digest exists for: the release moves the crate's own version
428
- // and nothing else, so the input a check hashes must not move with it.
429
- await workspace.write('packages/rust/Cargo.toml', manifest('9.9.9'));
430
- expect(await production()).toEqual(baseline);
431
-
432
- // And a dependency really changing must still reach the hash, or the
433
- // exclusion above would be hiding it.
434
- await workspace.write('packages/rust/Cargo.toml', manifest('0.1.0').replace('1.0.200', '1.0.201'));
435
- expect(await production()).not.toEqual(baseline);
436
- } finally {
437
- await workspace.cleanup();
438
- }
439
- });
440
-
441
- it('keeps the dependency half raw until the workspace defines the named input', async () => {
442
- const workspace = await createWorkspace();
443
- try {
444
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
445
- await workspace.write('packages/example/tsconfig.lib.json', '{}\n');
446
-
447
- // `{ input, dependencies: true }` resolves the name in each dependency's
448
- // own context and Nx throws when one has no definition for it. A
449
- // project.json project this plugin never inferred has none, so the
450
- // transitive half waits for the workspace-wide definition that covers it.
451
- const targets = (await inferProjectWithNxJson(workspace, 'packages/example/package.json', {}))?.targets ?? {};
452
-
453
- expect(targets.typecheck?.inputs).toEqual([
454
- 'versionlessProduction',
455
- '^production',
456
- '{workspaceRoot}/patches/**/*',
457
- '!{workspaceRoot}/patches/**/*.md',
458
- '{workspaceRoot}/tsconfig.base.json',
459
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
460
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
461
- { env: 'SMOO_TYPECHECK_TSC' },
462
- '{projectRoot}/tsconfig.lib.json',
463
- ]);
464
- } finally {
465
- await workspace.cleanup();
466
- }
467
- });
468
-
469
- it('hashes every tsconfig the extends chain reaches, not just the one the command names', async () => {
470
- const workspace = await createWorkspace();
471
- try {
472
- // The shape that made this a silent cache hit: the options a check
473
- // resolves live one file ABOVE the config its command names.
474
- await workspace.write('tsconfig.base.json', '{"compilerOptions":{"strict":true}}\n');
475
- await workspace.write(
476
- 'packages/tsconfig.base.json',
477
- '{"extends":"../tsconfig.base.json","compilerOptions":{"noUnusedLocals":true}}\n',
478
- );
479
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
480
- await workspace.write('packages/example/tsconfig.lib.json', '{"extends":"../tsconfig.base.json"}\n');
481
- // A deeper chain reached from the other config, named without the
482
- // extension TypeScript lets a specifier omit.
483
- await workspace.write('packages/example/tsconfig.strict.json', '{"extends":"../tsconfig.base"}\n');
484
- await workspace.write('packages/example/tsconfig.test.json', '{"extends":"./tsconfig.strict.json"}\n');
485
-
486
- const targets = await inferProjectTargets(workspace, 'packages/example/package.json');
487
-
488
- // Every file in the chain, once, whichever config reached it.
489
- const configChain = [
490
- '{workspaceRoot}/tsconfig.base.json',
491
- '{workspaceRoot}/packages/tsconfig.base.json',
492
- '{workspaceRoot}/packages/example/tsconfig.strict.json',
493
- ];
494
- const checkToolchain = [
495
- '{workspaceRoot}/patches/**/*',
496
- '!{workspaceRoot}/patches/**/*.md',
497
- ...configChain,
498
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
499
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
500
- ];
501
- expect(targets.typecheck?.inputs).toEqual([
502
- 'versionlessProduction',
503
- '^production',
504
- ...checkToolchain,
505
- { env: 'SMOO_TYPECHECK_TSC' },
506
- '{projectRoot}/tsconfig.lib.json',
507
- ]);
508
- expect(targets['typecheck-tests']?.inputs).toEqual([
509
- 'versionlessDefault',
510
- '^production',
511
- ...checkToolchain,
512
- { env: 'SMOO_TYPECHECK_TSC' },
513
- '{projectRoot}/tsconfig.test.json',
514
- ]);
515
- // An emit reads the same options, and a stale artifact is worse than a
516
- // stale verdict.
517
- expect(targets['tsc-js']?.inputs).toEqual([
518
- 'production',
519
- '^production',
520
- '{workspaceRoot}/package.json',
521
- '{workspaceRoot}/bun.lock',
522
- '{workspaceRoot}/patches/**/*',
523
- '!{workspaceRoot}/patches/**/*.md',
524
- ...configChain,
525
- '{projectRoot}/tsconfig.lib.json',
526
- ]);
527
- // Typed lint runs the same program (`projectService`), so its verdict
528
- // moves with the same files.
529
- expect(targets.lint?.inputs).toEqual(expect.arrayContaining(configChain));
530
- } finally {
531
- await workspace.cleanup();
532
- }
533
- });
534
-
535
- it('refuses a project whose tsconfig extends a file that is not there', async () => {
536
- const workspace = await createWorkspace();
537
- try {
538
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
539
- await workspace.write('packages/example/tsconfig.lib.json', '{"extends":"../tsconfig.base.json"}\n');
540
-
541
- // Fail-closed, and the only safe direction: an ancestor left out of the
542
- // hash is a cached verdict nobody can invalidate. Nx wraps a createNodes
543
- // throw, so the reason lives in the nested error.
544
- const failure = await inferProjectTargets(workspace, 'packages/example/package.json').then(
545
- () => undefined,
546
- (error: unknown) => error,
547
- );
548
- if (!(failure instanceof AggregateCreateNodesError)) {
549
- throw new Error(`expected AggregateCreateNodesError, got ${String(failure)}`);
550
- }
551
- expect(failure.errors[0]?.[1]?.message).toMatch(/"extends": "\.\.\/tsconfig\.base\.json" names no file/);
552
- } finally {
553
- await workspace.cleanup();
554
- }
555
- });
556
-
557
- it('walks an extends cycle once, and leaves an installed config to the lockfile wherever it is stored', async () => {
558
- const workspace = await createWorkspace();
559
- // WHERE an installed config's bytes sit is the installer's business: bun
560
- // keeps them in a global store and points node_modules at it, so this one
561
- // is outside the workspace entirely.
562
- const store = await mkdtemp(join(tmpdir(), 'smoothbricks-nx-plugin-store-'));
563
- try {
564
- await workspace.write('tsconfig.base.json', '{"compilerOptions":{"strict":true}}\n');
565
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
566
- // TypeScript rejects a cycle; this walk must terminate on one anyway,
567
- // with both files hashed.
568
- await workspace.write('packages/example/tsconfig.lib.json', '{"extends":"./tsconfig.cycle.json"}\n');
569
- await workspace.write('packages/example/tsconfig.cycle.json', '{"extends":"./tsconfig.lib.json"}\n');
570
- // Which bytes are in that store is pinned by the lockfile and the root
571
- // manifest, both already inputs; naming the path would hash nothing.
572
- await writeFile(join(store, 'package.json'), '{"name":"@fixture/tsconfig"}\n');
573
- await writeFile(join(store, 'tsconfig.json'), '{"compilerOptions":{"noUnusedLocals":true}}\n');
574
- await mkdir(join(workspace.context.workspaceRoot, 'node_modules/@fixture'), { recursive: true });
575
- await symlink(store, join(workspace.context.workspaceRoot, 'node_modules/@fixture/tsconfig'), 'dir');
576
- await workspace.write('packages/example/tsconfig.test.json', '{"extends":"@fixture/tsconfig/tsconfig.json"}\n');
577
-
578
- const { result: targets, stderr } = await withCapturedStderr(() =>
579
- inferProjectTargets(workspace, 'packages/example/package.json'),
580
- );
581
- const inputs = targets.typecheck?.inputs ?? [];
582
-
583
- expect(inputs).toEqual([
584
- 'versionlessProduction',
585
- '^production',
586
- '{workspaceRoot}/patches/**/*',
587
- '!{workspaceRoot}/patches/**/*.md',
588
- '{workspaceRoot}/tsconfig.base.json',
589
- '{workspaceRoot}/packages/example/tsconfig.cycle.json',
590
- '{workspaceRoot}/packages/example/tsconfig.lib.json',
591
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
592
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
593
- { env: 'SMOO_TYPECHECK_TSC' },
594
- '{projectRoot}/tsconfig.lib.json',
595
- ]);
596
- expect(JSON.stringify(inputs)).not.toContain('node_modules');
597
- // And silently, because nothing was lost. The noisy version of this fires
598
- // on every graph build in a workspace that installs one Expo package.
599
- expect(stderr).toBe('');
600
- } finally {
601
- await rm(store, { recursive: true, force: true });
602
- await workspace.cleanup();
603
- }
604
- });
605
-
606
- it("hashes a workspace member's config reached through its package name", async () => {
607
- const workspace = await createWorkspace();
608
- try {
609
- const root = workspace.context.workspaceRoot;
610
- await workspace.write('tsconfig.base.json', '{"compilerOptions":{"strict":true}}\n');
611
- // The other half of that judgement: a package name can resolve to
612
- // workspace SOURCE, which no lockfile pins. Dropping it would be the
613
- // original bug wearing a package name.
614
- await workspace.write('packages/tsconfig/package.json', '{"name":"@fixture/tsconfig"}\n');
615
- await workspace.write(
616
- 'packages/tsconfig/base.json',
617
- '{"extends":"../../tsconfig.base.json","compilerOptions":{"noUnusedLocals":true}}\n',
618
- );
619
- await mkdir(join(root, 'node_modules/@fixture'), { recursive: true });
620
- await symlink(join(root, 'packages/tsconfig'), join(root, 'node_modules/@fixture/tsconfig'), 'dir');
621
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
622
- await workspace.write('packages/example/tsconfig.lib.json', '{"extends":"@fixture/tsconfig/base.json"}\n');
623
-
624
- const { result: targets, stderr } = await withCapturedStderr(() =>
625
- inferProjectTargets(workspace, 'packages/example/package.json'),
626
- );
627
-
628
- expect(targets.typecheck?.inputs).toEqual([
629
- 'versionlessProduction',
630
- '^production',
631
- '{workspaceRoot}/patches/**/*',
632
- '!{workspaceRoot}/patches/**/*.md',
633
- '{workspaceRoot}/tsconfig.base.json',
634
- '{workspaceRoot}/packages/tsconfig/base.json',
635
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
636
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
637
- { env: 'SMOO_TYPECHECK_TSC' },
638
- '{projectRoot}/tsconfig.lib.json',
639
- ]);
640
- expect(stderr).toBe('');
641
- } finally {
642
- await workspace.cleanup();
643
- }
644
- });
645
-
646
- it('says so when an extends chain leaves the workspace, where nothing can hash it', async () => {
647
- const workspace = await createWorkspace();
648
- const outside = await mkdtemp(join(tmpdir(), 'smoothbricks-nx-plugin-outside-'));
649
- try {
650
- await writeFile(join(outside, 'tsconfig.base.json'), '{"compilerOptions":{"noUnusedLocals":true}}\n');
651
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
652
- await workspace.write(
653
- 'packages/example/tsconfig.lib.json',
654
- `${JSON.stringify({ extends: join(outside, 'tsconfig.base.json') })}\n`,
655
- );
656
-
657
- const { result: targets, stderr } = await withCapturedStderr(() =>
658
- inferProjectTargets(workspace, 'packages/example/package.json'),
659
- );
660
-
661
- // Nx hashes workspace files only, and no lockfile pins this one either,
662
- // so the verdict really can go stale. A silent drop here is the bug this
663
- // walk exists to close, so it is said out loud instead.
664
- expect(stderr).toContain(join(outside, 'tsconfig.base.json'));
665
- expect(stderr).toContain('outside the workspace');
666
- expect(targets.typecheck?.inputs).toEqual([
667
- 'versionlessProduction',
668
- '^production',
669
- '{workspaceRoot}/patches/**/*',
670
- '!{workspaceRoot}/patches/**/*.md',
671
- '{workspaceRoot}/tsconfig.base.json',
672
- { json: '{workspaceRoot}/package.json', excludeFields: ['version', 'scripts', 'smoo', 'nx'] },
673
- { json: '{workspaceRoot}/bun.lock', excludeFields: ['workspaces'] },
674
- { env: 'SMOO_TYPECHECK_TSC' },
675
- '{projectRoot}/tsconfig.lib.json',
676
- ]);
677
- } finally {
678
- await rm(outside, { recursive: true, force: true });
679
- await workspace.cleanup();
680
- }
681
- });
682
-
683
- it('rebuilds current library declarations before test typechecking after clean', async () => {
684
- const workspace = await createWorkspace();
685
- try {
686
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
687
- await workspace.write('packages/example/tsconfig.lib.json', '{}\n');
688
- await workspace.write('packages/example/tsconfig.test.json', '{}\n');
689
-
690
- const targets = await inferProjectTargets(workspace, 'packages/example/package.json');
691
-
692
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
693
- expect(targets['typecheck-tests']?.dependsOn).toEqual(['tsc-js', 'typecheck']);
694
- } finally {
695
- await workspace.cleanup();
696
- }
697
- });
698
-
699
- it('infers vitest watch targets from explicit test commands', async () => {
700
- const workspace = await createWorkspace();
701
- try {
702
- await workspace.write(
703
- 'packages/example/package.json',
704
- '{"name":"example","scripts":{"test":"vitest run --coverage"}}\n',
705
- );
706
- await workspace.write('packages/example/tsconfig.test.json', '{}\n');
707
-
708
- const targets = await inferProjectTargets(workspace, 'packages/example/package.json');
709
-
710
- expect(targets['test-watch']?.continuous).toBe(true);
711
- expect(targets['test-watch']?.options).toMatchObject({
712
- command: 'vitest --coverage',
713
- cwd: 'packages/example',
714
- });
715
- } finally {
716
- await workspace.cleanup();
717
- }
718
- });
719
-
720
- it('makes lint check that the timing manifest names every file a timings-sharded Bun suite runs', async () => {
721
- const workspace = await createWorkspace();
722
- try {
723
- const shard = (n: number) => ({
724
- executor: '@smoothbricks/nx-plugin:bounded-exec',
725
- options: { command: `bun test --timings=test-timings.json --shard=${n}/2`, cwd: '{projectRoot}' },
726
- });
727
- await workspace.write(
728
- 'packages/sharded/package.json',
729
- JSON.stringify({ name: 'sharded', nx: { targets: { 'test-a': shard(1), 'test-b': shard(2) } } }),
730
- );
731
- await workspace.write(
732
- 'packages/counted/package.json',
733
- JSON.stringify({
734
- name: 'counted',
735
- nx: { targets: { 'test-a': { options: { command: 'bun test --shard=1/1', cwd: '{projectRoot}' } } } },
736
- }),
737
- );
738
-
739
- const sharded = await inferProjectTargets(workspace, 'packages/sharded/package.json');
740
- const counted = await inferProjectTargets(workspace, 'packages/counted/package.json');
741
-
742
- expect(sharded['shard-timings']).toEqual({
743
- executor: '@smoothbricks/nx-plugin:shard-timings',
744
- cache: false,
745
- outputs: [],
746
- options: { cwd: 'packages/sharded', args: ['--timings=test-timings.json'] },
747
- });
748
- expect(sharded.lint?.dependsOn).toEqual(['shard-timings']);
749
- expect(counted['shard-timings']).toBeUndefined();
750
- expect(counted.lint).toBeUndefined();
751
- } finally {
752
- await workspace.cleanup();
753
- }
754
- });
755
-
756
- it('infers aggregate build for package-local output targets without owning them', async () => {
757
- const workspace = await createWorkspace();
758
- try {
759
- await workspace.write(
760
- 'packages/tsdown/package.json',
761
- JSON.stringify({ name: 'tsdown', nx: { targets: { 'tsdown-js': { executor: 'nx:run-commands' } } } }),
762
- );
763
-
764
- const targets = await inferProjectTargets(workspace, 'packages/tsdown/package.json');
765
-
766
- expect(targets['tsc-js']).toBeUndefined();
767
- expect(targets['tsdown-js']).toBeUndefined();
768
- expect(targets.build?.executor).toBe('nx:noop');
769
- expect(targets.build?.dependsOn).toEqual(['^build', 'tsdown-js']);
770
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
771
- } finally {
772
- await workspace.cleanup();
773
- }
774
- });
775
-
776
- it('keeps a test runner out of the aggregate build however its name ends', async () => {
777
- const workspace = await createWorkspace();
778
- try {
779
- await workspace.write(
780
- 'packages/suites/package.json',
781
- JSON.stringify({
782
- name: 'suites',
783
- nx: {
784
- targets: {
785
- // A runner reading as "tool=test, output=bun". Suffix alone would
786
- // sweep it into `build`, which is a serialized test suite behind
787
- // every consumer's build.
788
- 'test-bun': { executor: 'nx:run-commands' },
789
- 'test-watch': { executor: 'nx:run-commands' },
790
- // A real emitter in the same family, to prove the exclusion is
791
- // the test-runner class and not the family itself.
792
- 'bundle-bun': { executor: 'nx:run-commands' },
793
- },
794
- },
795
- }),
796
- );
797
-
798
- const targets = await inferProjectTargets(workspace, 'packages/suites/package.json');
799
-
800
- expect(targets.build?.dependsOn).toEqual(['^build', 'bundle-bun']);
801
- } finally {
802
- await workspace.cleanup();
803
- }
804
- });
805
-
806
- it('keeps platform-only output families out of the ordinary aggregate build', async () => {
807
- const workspace = await createWorkspace();
808
- try {
809
- await workspace.write(
810
- 'packages/platform/package.json',
811
- JSON.stringify({
812
- name: 'platform',
813
- nx: {
814
- targets: {
815
- 'bundle-ios': { executor: 'nx:run-commands' },
816
- 'bundle-macos': { executor: 'nx:run-commands' },
817
- 'bundle-linux': { executor: 'nx:run-commands' },
818
- },
819
- },
820
- }),
821
- );
822
-
823
- const targets = await inferProjectTargets(workspace, 'packages/platform/package.json');
824
-
825
- expect(targets.build).toBeUndefined();
826
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
827
- // No ordinary aggregate above is the whole assertion: a platform suffix
828
- // is not an output family, so `bundle-ios`/`-macos`/`-linux` give this
829
- // project nothing for `build` to aggregate — only a `clean` to own their
830
- // outputs.
831
- } finally {
832
- await workspace.cleanup();
833
- }
834
- });
835
-
836
- //#region smoo!n/rust-output-target-inference
837
- it('infers generic cargo workspace targets without any rust output targets', async () => {
838
- const workspace = await createWorkspace();
839
- try {
840
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
841
- await workspace.write(
842
- 'packages/ferris/Cargo.toml',
843
- '[workspace]\nmembers = ["crates/ferris-core", "crates/ferris-wasm"]\n\n[profile.wasm-release]\ninherits = "release"\n',
844
- );
845
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
846
- await workspace.write(
847
- 'packages/ferris/crates/ferris-wasm/Cargo.toml',
848
- '[package]\nname = "ferris-wasm"\n\n[lib]\ncrate-type = ["cdylib", "rlib"]\n',
849
- );
850
-
851
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
852
-
853
- // Even a cdylib crate named *-wasm infers no cargo-wasm: rust output
854
- // targets are declared package-locally, never derived from crate metadata.
855
- expect(targets['cargo-wasm']).toBeUndefined();
856
- expect(targets['cargo-napi']).toBeUndefined();
857
- expect(targets['cargo-sweep']?.options).toMatchObject({
858
- command: 'cargo sweep --time 7',
859
- cwd: 'packages/ferris',
860
- });
861
- expect(targets['cargo-sweep']?.cache).toBe(false);
862
- // Never cached: the download lands in CARGO_HOME, so a cache hit would
863
- // report success over a registry that still cannot resolve the lockfile.
864
- expect(targets['cargo-fetch']?.cache).toBe(false);
865
- expect(targets['cargo-fetch']?.options).toEqual({
866
- commands: ['cargo fetch --locked'],
867
- cwd: 'packages/ferris',
868
- });
869
- // Every frozen cargo command carries the edge: offline cargo fails at
870
- // resolution, so each one needs the locked graph downloaded before it runs.
871
- for (const name of [
872
- 'cargo-test-compile',
873
- 'cargo-test-archive',
874
- 'cargo-lint',
875
- CARGO_CROSS_LINT_TARGET,
876
- 'mutation',
877
- 'bench',
878
- ]) {
879
- expect(targets[name]?.dependsOn).toContain('cargo-fetch');
880
- }
881
- expect(targets['cargo-sweep']?.dependsOn).toBeUndefined();
882
- // The archive and the compile it stands for hash every crate's sources
883
- // AND the outputs of the targets they depend on: generated crate inputs
884
- // are gitignored, so a repository that had to restate `inputs` to add
885
- // them replaced the crate union with the root's `default` and shipped a
886
- // stale archive to every per-crate test.
887
- for (const name of ['cargo-test-compile', 'cargo-test-archive', 'cargo-lint', CARGO_CROSS_LINT_TARGET]) {
888
- const inputs = targets[name]?.inputs ?? [];
889
- expect(inputs).toContainEqual({ dependentTasksOutputFiles: '**/*', transitive: false });
890
- expect(inputs).toContain('{workspaceRoot}/packages/ferris/crates/ferris-core/**/*');
891
- }
892
- expect(targets['cargo-test-compile']?.executor).toBe('nx:run-commands');
893
- expect(targets['cargo-test-compile']?.cache).toBe(false);
894
- expect(targets['cargo-test-compile']?.outputs).toEqual([]);
895
- expect(targets['cargo-test-compile']?.options).toMatchObject({
896
- command: 'cargo --frozen test --workspace --no-run',
897
- cwd: 'packages/ferris',
898
- });
899
- expect(targets['cargo-test']?.executor).toBe('nx:noop');
900
- expect(targets['cargo-test']?.dependsOn).toEqual(['cargo-test-ferris-core', 'cargo-test-ferris-wasm']);
901
- // One workspace compile, packed once. Every per-crate runner reads that
902
- // archive, so the runners fan out instead of chaining: none of them
903
- // builds, re-resolves features, or writes cargo's flocked `target/`.
904
- expect(targets['cargo-test-archive']?.executor).toBe('nx:run-commands');
905
- expect(targets['cargo-test-archive']?.cache).toBe(true);
906
- expect(targets['cargo-test-archive']?.outputs).toEqual(['{projectRoot}/.cache/nextest/archive.tar.zst']);
907
- expect(targets['cargo-test-archive']?.options).toMatchObject({ cwd: 'packages/ferris' });
908
- // nextest does not create the archive's parent directory and fails the
909
- // whole build if it is missing (measured: "error writing to archive").
910
- // The directory and the archive are ONE command, in the order the archive needs.
911
- expect(targets['cargo-test-archive']?.options?.commands).toBeUndefined();
912
- // `--tool-config-file`, never `--config-file`: the plugin's settings must
913
- // sit UNDER the repository's `.config/nextest.toml`, which is the only
914
- // place an `archive.include` for a cdylib or fixture can be declared.
915
- // `$PWD` because tool config paths must be absolute and an absolute path
916
- // in the command text would split one cache entry per checkout; through
917
- // the root `node_modules` link because the plugin's real location is a
918
- // different number of `../` away from each checkout.
919
- expect(String(targets['cargo-test-archive']?.options?.command)).toBe(
920
- 'mkdir -p .cache/nextest && cargo --frozen nextest archive --workspace --archive-file .cache/nextest/archive.tar.zst --user-config-file none --tool-config-file "smoo:$PWD/../../node_modules/@smoothbricks/nx-plugin/nextest.toml"',
921
- );
922
- expect(targets['cargo-test-archive']?.inputs).toContain('{projectRoot}/.config/nextest.toml');
923
- // Tests compile the dev profile only. Nx forwards a run's configuration
924
- // down every edge to each target that has it, so a release configuration
925
- // here would make a release `build` compile test binaries nobody runs.
926
- for (const name of ['cargo-test-compile', 'cargo-test-archive', 'cargo-test', 'cargo-test-ferris-core', 'test']) {
927
- expect(targets[name]).toBeDefined();
928
- expect(targets[name]?.configurations?.[RELEASE_CONFIGURATION]).toBeUndefined();
929
- }
930
- expect(targets['cargo-test-ferris-core']?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
931
- expect(targets['cargo-test-ferris-wasm']?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
932
- // The runner executes the archive's binaries, unpacked once for every
933
- // runner by the plugin's helper (through the root `node_modules` link,
934
- // so the hashed command names no machine path), and remaps the
935
- // workspace root: without `--workspace-remap`, a restored archive hands
936
- // tests the PRODUCING tree's absolute CARGO_MANIFEST_DIR (measured on a
937
- // moved tree). `--workspace` is not merely redundant here, nextest
938
- // rejects it beside a reused build.
939
- expect(targets['cargo-test-ferris-core']?.options?.command).toMatch(
940
- /^extracted="\$\(node \.\.\/\.\.\/node_modules\/@smoothbricks\/nx-plugin\/dist\/bin\/smoo-nx-nextest-extract\.js \.cache\/nextest\/archive\.tar\.zst\)" && cargo --frozen nextest run --binaries-metadata "\$extracted\/target\/nextest\/binaries-metadata\.json" --cargo-metadata "\$extracted\/target\/nextest\/cargo-metadata\.json" --target-dir-remap "\$extracted\/target" --workspace-remap \. -E 'package\(ferris-core\)' --no-fail-fast --no-tests=pass --user-config-file none --tool-config-file "smoo:\$PWD\/\.\.\/\.\.\/node_modules\/@smoothbricks\/nx-plugin\/nextest\.toml"$/,
941
- );
942
- expect(targets['cargo-test-ferris-core']?.inputs).toContain(
943
- '{workspaceRoot}/packages/ferris/.config/nextest.toml',
944
- );
945
- expect(targets['cargo-test-ferris-core']?.inputs).toEqual(
946
- expect.arrayContaining([
947
- '{workspaceRoot}/packages/ferris/Cargo.toml',
948
- '{workspaceRoot}/packages/ferris/Cargo.lock',
949
- '{workspaceRoot}/packages/ferris/crates/ferris-core/**/*',
950
- ]),
951
- );
952
- expect(targets['cargo-test-ferris-core']?.inputs).not.toContain(
953
- '{workspaceRoot}/packages/ferris/crates/ferris-wasm/**/*',
954
- );
955
- // One clippy for the workspace, writing the same `target/` as the dev
956
- // test compile: a directory of its own compiled every host unit twice.
957
- const [fmt, clippy] = targets['cargo-lint']?.options?.commands ?? [];
958
- expect(fmt).toBe('cargo fmt --all --check');
959
- expect(clippy).toBe(CARGO_LINT_CLIPPY_COMMAND);
960
- expect(clippy).toMatch(/^cargo --frozen clippy --workspace --all-targets /);
961
- for (const command of [clippy, targets['cargo-test-compile']?.options?.command]) {
962
- expect(command).not.toContain('--target-dir');
963
- }
964
- expect(targets['cargo-lint']?.options?.cwd).toBe(targets['cargo-test-compile']?.options?.cwd);
965
- expect(targets['cargo-lint']?.cache).toBe(true);
966
- expect(targets['cargo-lint']?.outputs).toEqual([]);
967
- expect(targets['cargo-lint']?.inputs).toEqual(
968
- expect.arrayContaining([
969
- '{workspaceRoot}/packages/ferris/crates/ferris-core/**/*',
970
- '{workspaceRoot}/packages/ferris/crates/ferris-wasm/**/*',
971
- ]),
972
- );
973
- expect(targets.lint?.dependsOn).toEqual(['cargo-lint']);
974
- expect(targets[CARGO_CROSS_LINT_TARGET]?.options).toMatchObject({
975
- command: CARGO_CROSS_LINT_COMMAND,
976
- cwd: 'packages/ferris',
977
- });
978
- expect(targets[CARGO_CROSS_LINT_TARGET]?.cache).toBe(true);
979
- expect(targets.lint?.dependsOn).not.toContain(CARGO_CROSS_LINT_TARGET);
980
- expect(targets.test?.executor).toBe('nx:noop');
981
- expect(targets.test?.dependsOn).toEqual(['cargo-test']);
982
- expect(targets.mutation?.cache).toBe(false);
983
- // On bounded-exec, so cargo-mutants' own per-core jobserver is sized to a CPU grant.
984
- expect(targets.mutation?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
985
- expect(targets.mutation?.options).toMatchObject({
986
- command: 'cargo --frozen mutants --workspace',
987
- timeoutMs: 6 * 60 * 60 * 1000,
988
- });
989
- expect(targets.bench?.options).toMatchObject({ command: 'cargo --frozen bench --workspace' });
990
- expectNoSchedulerThrottle(targets);
991
- } finally {
992
- await workspace.cleanup();
993
- }
994
- });
995
-
996
- it('cleans every cargo directory its own commands write, including the ones caching refuses', async () => {
997
- const workspace = await createWorkspace();
998
- try {
999
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
1000
- await workspace.write('packages/ferris/Cargo.toml', '[workspace]\nmembers = ["crates/ferris-core"]\n');
1001
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
1002
-
1003
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
1004
-
1005
- // A clippy target dir is not an Nx output — restoring a multi-GiB build
1006
- // tree from a cache is worse than rebuilding it — so `clean` cannot find
1007
- // these through `outputs`. They are read back off the commands that
1008
- // write them, which is why a new `--target-dir` cannot be forgotten here.
1009
- // The workspace `target/` every dev build shares is not one of them.
1010
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
1011
- expect(targets.clean?.cache).toBe(false);
1012
- expect(targets.clean?.options?.outputs).toEqual([
1013
- '{projectRoot}/dist',
1014
- '{workspaceRoot}/packages/ferris/.cache/nextest',
1015
- '{workspaceRoot}/packages/ferris/target/cargo-lint-cross',
1016
- ]);
1017
- } finally {
1018
- await workspace.cleanup();
1019
- }
1020
- });
1021
-
1022
- it('keeps Rust-only lint source-aware after migrating defaults without replacing mixed or custom lint', async () => {
1023
- const workspace = await createWorkspace();
1024
- const root = 'packages/ferris';
1025
- const defaults = {
1026
- targetDefaults: {
1027
- lint: {
1028
- executor: 'nx:run-commands',
1029
- options: { commands: ['biome check {projectRoot}', 'eslint {projectRoot}/src'] },
1030
- },
1031
- },
1032
- };
1033
- applyWorkspaceConfig(defaults);
1034
- const resolveLint = (targets: Record<string, TargetConfiguration>, declared: TargetConfiguration = {}) => {
1035
- let lint = targets.lint ?? {};
1036
- const synthesized = createTargetDefaultsResults(
1037
- { [root]: { root, targets } },
1038
- { [root]: { root, targets: { lint: declared } } },
1039
- defaults,
1040
- );
1041
- for (const [, , result] of synthesized) {
1042
- const target = result.projects?.[root]?.targets?.lint;
1043
- if (target) lint = mergeTargetConfigurations(target, lint);
1044
- }
1045
- return mergeTargetConfigurations(declared, lint);
1046
- };
1047
- try {
1048
- await workspace.write('biome.json', '{}\n');
1049
- await workspace.write('eslint.config.mjs', 'export default [{ files: ["**/*.ts"] }];\n');
1050
- await workspace.write(`${root}/package.json`, '{"name":"ferris"}\n');
1051
- await workspace.write(`${root}/Cargo.toml`, '[workspace]\nmembers = ["crates/core"]\n');
1052
- await workspace.write(`${root}/crates/core/Cargo.toml`, '[package]\nname = "ferris-core"\n');
1053
- const biome = `biome check --files-ignore-unknown=true '${root}'`;
1054
- const rust = await inferProjectTargets(workspace, `${root}/package.json`);
1055
- const rustLint = resolveLint(rust);
1056
- expect(rustLint.executor).toBe('nx:run-commands');
1057
- expect(rustLint.dependsOn).toEqual(['cargo-lint']);
1058
- expect(rustLint.options?.commands).toEqual([biome]);
1059
-
1060
- // A JavaScript source joins ESLint's file list the moment it appears, with no tsconfig to announce it.
1061
- await workspace.write(`${root}/src/check.js`, 'debugger;\n');
1062
- const withJavaScript = resolveLint(await inferProjectTargets(workspace, `${root}/package.json`));
1063
- expect(withJavaScript.dependsOn).toEqual(['cargo-lint']);
1064
- expect(withJavaScript.options?.commands).toEqual([biome, `eslint '${root}/src/check.js'`]);
1065
-
1066
- const custom = { executor: 'nx:run-commands', options: { command: 'custom-linter package.json' } };
1067
- await workspace.write(
1068
- `${root}/package.json`,
1069
- JSON.stringify({ name: 'ferris', nx: { targets: { lint: custom } } }),
1070
- );
1071
- const declared = await inferProjectTargets(workspace, `${root}/package.json`);
1072
- expect(resolveLint(declared, custom).options?.command).toBe(custom.options.command);
1073
-
1074
- await workspace.write(`${root}/package.json`, '{"name":"ferris"}\n');
1075
- await workspace.write(`${root}/tsconfig.lib.json`, '{"compilerOptions":{"outDir":"dist"}}\n');
1076
- await workspace.write(`${root}/src/index.ts`, 'export const value = 1;\n');
1077
- const mixed = await inferProjectTargets(workspace, `${root}/package.json`);
1078
- expect(resolveLint(mixed).options?.commands).toEqual([
1079
- biome,
1080
- `eslint '${root}/src/check.js' '${root}/src/index.ts'`,
1081
- ]);
1082
- expectNoSchedulerThrottle(mixed);
1083
- } finally {
1084
- await workspace.cleanup();
1085
- }
1086
- });
1087
-
1088
- it('lints the declared test program outside src and keys its sources and inherited declaration', async () => {
1089
- const workspace = await createWorkspace();
1090
- try {
1091
- await workspace.write('eslint.config.mjs', 'export default [{ files: ["**/*.ts"] }];\n');
1092
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
1093
- await workspace.write(
1094
- 'packages/test-base.json',
1095
- JSON.stringify({
1096
- include: ['\u0024{configDir}/tests/**/*.ts'],
1097
- exclude: ['\u0024{configDir}/tests/excluded.ts'],
1098
- files: ['contract/schema.d.ts'],
1099
- }),
1100
- );
1101
- await workspace.write('packages/example/tsconfig.test.json', '{"extends":"../test-base.json"}\n');
1102
- await workspace.write('packages/example/src/index.ts', 'export const value = 1;\n');
1103
- await workspace.write('packages/example/tests/check.test.ts', 'export const check = 1;\n');
1104
- await workspace.write('packages/example/tests/helper.ts', 'export const helper = 1;\n');
1105
- await workspace.write('packages/example/tests/excluded.ts', 'export const excluded = 1;\n');
1106
- await workspace.write('packages/example/other/stray.test.ts', 'export const stray = 1;\n');
1107
- await workspace.write('packages/contract/schema.d.ts', 'export interface Contract { value: number }\n');
1108
-
1109
- const { lint } = await inferProjectTargets(workspace, 'packages/example/package.json');
1110
- expect(lint?.options?.commands).toEqual([
1111
- "eslint 'packages/contract/schema.d.ts' 'packages/example/src/index.ts' 'packages/example/tests/check.test.ts' 'packages/example/tests/helper.ts'",
1112
- ]);
1113
- expect(lint?.metadata?.eslintFileSet).toEqual({
1114
- command: lint?.options?.commands?.[0],
1115
- files: [
1116
- 'packages/contract/schema.d.ts',
1117
- 'packages/example/src/index.ts',
1118
- 'packages/example/tests/check.test.ts',
1119
- 'packages/example/tests/helper.ts',
1120
- ],
1121
- });
1122
- expect(isEslintFileSet(lint?.metadata?.eslintFileSet)).toBe(true);
1123
- expect(isEslintFileSet({ command: 'eslint invalid', files: [null] })).toBe(false);
1124
- expect(lint?.inputs).toEqual(
1125
- expect.arrayContaining([
1126
- '{projectRoot}/tsconfig.test.json',
1127
- '{workspaceRoot}/packages/test-base.json',
1128
- '{workspaceRoot}/packages/contract/schema.d.ts',
1129
- '{workspaceRoot}/packages/example/tests/check.test.ts',
1130
- '{workspaceRoot}/packages/example/tests/helper.ts',
1131
- ]),
1132
- );
1133
- expect(lint?.inputs).not.toContain('{workspaceRoot}/packages/example/tests/excluded.ts');
1134
- expect(lint?.inputs).not.toContain('{workspaceRoot}/packages/example/other/stray.test.ts');
1135
- } finally {
1136
- await workspace.cleanup();
1137
- }
1138
- });
1139
-
1140
- it('lints and keys only the sources Nx indexes, never ignored files a build left on disk', async () => {
1141
- const workspace = await createWorkspace();
1142
- try {
1143
- await workspace.write('eslint.config.mjs', 'export default [{ files: ["**/*.ts"] }];\n');
1144
- // Generated outputs one build wrote and a fresh checkout lacks: a root ignore, a
1145
- // project-level one, and an .nxignore, the three ways Nx keeps a file out of its index.
1146
- await workspace.write('.gitignore', 'packages/example/src/generated/\n');
1147
- await workspace.write('packages/example/.gitignore', '*.generated.ts\n');
1148
- await workspace.write('.nxignore', 'packages/example/tests/nx-ignored.ts\n');
1149
- await workspace.write('packages/example/package.json', '{"name":"example"}\n');
1150
- await workspace.write('packages/example/tsconfig.test.json', '{"include":["tests/**/*.ts"]}\n');
1151
- await workspace.write('packages/example/src/index.ts', 'export const value = 1;\n');
1152
- await workspace.write('packages/example/src/generated/schemas.gen.ts', 'export const schemas = 1;\n');
1153
- await workspace.write('packages/example/src/catalog.generated.ts', 'export const catalog = 1;\n');
1154
- await workspace.write('packages/example/tests/check.test.ts', 'export const check = 1;\n');
1155
- await workspace.write('packages/example/tests/helpers/catalog.generated.ts', 'export const c = 1;\n');
1156
- await workspace.write('packages/example/tests/nx-ignored.ts', 'export const ignored = 1;\n');
1157
-
1158
- const { lint } = await inferProjectTargets(workspace, 'packages/example/package.json');
1159
- const files = ['packages/example/src/index.ts', 'packages/example/tests/check.test.ts'];
1160
- expect(lint?.metadata?.eslintFileSet).toEqual({
1161
- command: `eslint ${files.map((file) => `'${file}'`).join(' ')}`,
1162
- files,
1163
- });
1164
- expect(lint?.options?.commands).toEqual([lint?.metadata?.eslintFileSet.command]);
1165
- const programInputs = (lint?.inputs ?? []).filter(
1166
- (input): input is string => typeof input === 'string' && input.startsWith('{workspaceRoot}/packages/example/'),
1167
- );
1168
- expect(programInputs).toEqual(['{workspaceRoot}/packages/example/tests/check.test.ts']);
1169
- } finally {
1170
- await workspace.cleanup();
1171
- }
1172
- });
1173
-
1174
- it('attributes one repository-root Cargo workspace across package projects', async () => {
1175
- const workspace = await createWorkspace();
1176
- try {
1177
- await workspace.write('package.json', '{"name":"@fixture/codebase"}\n');
1178
- await workspace.write('packages/runtime/package.json', '{"name":"@fixture/runtime","nx":{"name":"runtime"}}\n');
1179
- await workspace.write('packages/wasm/package.json', '{"name":"@fixture/wasm","nx":{"name":"wasm"}}\n');
1180
- await workspace.write(
1181
- 'packages/native/package.json',
1182
- JSON.stringify({
1183
- name: '@fixture/native',
1184
- nx: { name: 'native' },
1185
- napi: {
1186
- binaryName: 'native',
1187
- targets: ['aarch64-apple-darwin'],
1188
- },
1189
- }),
1190
- );
1191
- await workspace.write(
1192
- 'Cargo.toml',
1193
- [
1194
- '[workspace]',
1195
- 'members = ["packages/runtime/crates/*", "packages/wasm", "packages/native/crates/*"]',
1196
- '',
1197
- ].join('\n'),
1198
- );
1199
- await workspace.write(
1200
- 'packages/runtime/crates/runtime-core/Cargo.toml',
1201
- '[package]\nname = "runtime-core"\n\n[package.metadata.smoothbricks.test]\nshards = 2\n',
1202
- );
1203
- await workspace.write(
1204
- 'packages/wasm/Cargo.toml',
1205
- [
1206
- '[package]',
1207
- 'name = "runtime-wasm"',
1208
- '',
1209
- '[lib]',
1210
- 'crate-type = ["cdylib", "rlib"]',
1211
- '',
1212
- '[package.metadata.smoothbricks.wasm-bindgen]',
1213
- 'targets = ["web"]',
1214
- '',
1215
- ].join('\n'),
1216
- );
1217
- await workspace.write(
1218
- 'packages/native/crates/native-napi/Cargo.toml',
1219
- '[package]\nname = "native-napi"\n\n[lib]\ncrate-type = ["cdylib"]\n',
1220
- );
1221
-
1222
- const inferred = await inferTargets(
1223
- ['package.json', 'packages/runtime/package.json', 'packages/wasm/package.json', 'packages/native/package.json'],
1224
- undefined,
1225
- workspace.context,
1226
- );
1227
- const projects = new Map(inferred.flatMap(([, result]) => Object.entries(result.projects ?? {})));
1228
- const root = projects.get('.')?.targets ?? {};
1229
- const runtime = projects.get('packages/runtime')?.targets ?? {};
1230
- const wasm = projects.get('packages/wasm')?.targets ?? {};
1231
- const native = projects.get('packages/native')?.targets ?? {};
1232
- const rootProject = '@fixture/codebase';
1233
- const rootFetch = { projects: [rootProject], target: 'cargo-fetch' };
1234
- const rootCompile = { projects: [rootProject], target: 'cargo-test-compile' };
1235
- const rootArchive = { projects: [rootProject], target: 'cargo-test-archive' };
1236
-
1237
- expect(
1238
- [...projects]
1239
- .filter(([, project]) => project.targets?.['cargo-test-compile'])
1240
- .map(([projectRoot]) => projectRoot),
1241
- ).toEqual(['.']);
1242
- expect(root['cargo-fetch']?.options).toEqual({
1243
- commands: ['cargo fetch --locked'],
1244
- cwd: '.',
1245
- });
1246
- expect(root['cargo-test-compile']?.options).toMatchObject({
1247
- command: 'cargo --frozen test --workspace --no-run',
1248
- cwd: '.',
1249
- });
1250
- // The root owns the one workspace clippy, run where the dev build runs.
1251
- expect(String(root['cargo-lint']?.options?.commands?.[1])).toContain('clippy --workspace');
1252
- expect(root['cargo-lint']?.options?.cwd).toBe(root['cargo-test-compile']?.options?.cwd);
1253
- expect(root['cargo-lint']?.dependsOn).toContain('cargo-fetch');
1254
- expect(root['cargo-test']?.dependsOn).toHaveLength(6);
1255
-
1256
- // Root mode: every piece of every project hangs off the one root archive,
1257
- // in any order. The crate is selected by filterset alone — `-p` would
1258
- // re-resolve features, and there is nothing left to build anyway.
1259
- expect(runtime['cargo-test-runtime-core-shard1']?.dependsOn).toEqual([rootFetch, rootArchive]);
1260
- expect(runtime['cargo-test-runtime-core-shard2']?.dependsOn).toEqual([rootFetch, rootArchive]);
1261
- expect(runtime['cargo-test-runtime-core-exceptions-shard1']?.dependsOn).toEqual([rootFetch, rootArchive]);
1262
- expect(runtime['cargo-test-runtime-core-exceptions-shard2']?.dependsOn).toEqual([rootFetch, rootArchive]);
1263
- expect(runtime['cargo-test-runtime-core-shard1']?.options).toMatchObject({ cwd: '.' });
1264
- // At the root the helper and the plugin's nextest config are the root's
1265
- // own `node_modules` link, no `../`.
1266
- expect(runtime['cargo-test-runtime-core-shard1']?.options?.command).toStartWith(
1267
- 'extracted="$(node node_modules/@smoothbricks/nx-plugin/dist/bin/smoo-nx-nextest-extract.js .cache/nextest/archive.tar.zst)" && ',
1268
- );
1269
- expect(runtime['cargo-test-runtime-core-shard1']?.options?.command).toContain(
1270
- `--target-dir-remap "$extracted/target" --workspace-remap . -E 'package(runtime-core)`,
1271
- );
1272
- expect(runtime['cargo-test-runtime-core-shard1']?.options?.command).toEndWith(
1273
- '--tool-config-file "smoo:$PWD/node_modules/@smoothbricks/nx-plugin/nextest.toml"',
1274
- );
1275
- expect(native['cargo-test-native-napi']?.options?.command).toContain('--no-tests=pass');
1276
- expect(runtime['cargo-test']?.dependsOn).toEqual([
1277
- 'cargo-test-runtime-core-shard1',
1278
- 'cargo-test-runtime-core-shard2',
1279
- 'cargo-test-runtime-core-exceptions-shard1',
1280
- 'cargo-test-runtime-core-exceptions-shard2',
1281
- ]);
1282
- // A package owning crates validates through the root's one clippy verdict.
1283
- expect(runtime['cargo-lint']?.dependsOn).toEqual([{ projects: [rootProject], target: 'cargo-lint' }]);
1284
- expect(runtime.lint?.dependsOn).toEqual(['cargo-lint']);
1285
- expect(runtime['cargo-lint-runtime-core']).toBeUndefined();
1286
- expect(runtime.clean).toBeUndefined();
1287
-
1288
- expect(wasm['cargo-test-runtime-wasm']?.dependsOn).toEqual([rootFetch, rootArchive]);
1289
- expect(wasm['cargo-wasm']?.inputs).toContain(CARGO_CLOSURE_INPUT);
1290
- expect(wasm['cargo-wasm']?.inputs).not.toContain('{workspaceRoot}/**/*.rs');
1291
- expect(wasm['cargo-wasm']?.options).toMatchObject({ cwd: '.' });
1292
- // Dev by default, in the workspace's own `target/`; only the release
1293
- // configuration compiles, and binds, the release artifact.
1294
- expect(wasm['cargo-wasm']?.options?.command).toBe(
1295
- [
1296
- 'cargo --frozen build --target wasm32-unknown-unknown -p runtime-wasm',
1297
- 'wasm-bindgen --target web --out-dir packages/wasm/dist-wasm/web target/wasm32-unknown-unknown/debug/runtime_wasm.wasm',
1298
- ].join(' && '),
1299
- );
1300
- expect(wasm['cargo-wasm']?.options?.commands).toBeUndefined();
1301
- expect(wasm['cargo-wasm']?.configurations?.[RELEASE_CONFIGURATION]).toEqual({
1302
- command: [
1303
- 'cargo --frozen build --release --target wasm32-unknown-unknown -p runtime-wasm',
1304
- 'wasm-bindgen --target web --out-dir packages/wasm/dist-wasm/web target/wasm32-unknown-unknown/release/runtime_wasm.wasm',
1305
- ].join(' && '),
1306
- });
1307
- expect(wasm['cargo-wasm']?.outputs).toEqual(['{projectRoot}/dist-wasm']);
1308
- expect(wasm['cargo-wasm']?.dependsOn).toEqual([rootFetch, '^build']);
1309
- expect(wasm.build?.dependsOn).toContainEqual(rootCompile);
1310
- expect(wasm.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
1311
-
1312
- // The crate whose project also builds the debug cdylib keeps that edge:
1313
- // its tests load the artifact `napi-debug` writes into `target/debug`.
1314
- expect(native['cargo-test-native-napi']?.dependsOn).toEqual([rootFetch, rootArchive, 'napi-debug']);
1315
- // The addon build consumes only its dependencies' outputs; it is not
1316
- // ordered behind the test compile.
1317
- expect(native['napi-debug']?.dependsOn).toEqual(['^build']);
1318
- // The addon depends on the package's napi block and the napi CLI's version,
1319
- // never on the package version or the whole lockfile: a release bumps both
1320
- // before it builds, and that must not recompile the native code.
1321
- const napiInputs = native['napi-debug']?.inputs ?? [];
1322
- expect(napiInputs).toContainEqual({ externalDependencies: ['@napi-rs/cli'] });
1323
- expect(
1324
- napiInputs.some((input) => typeof input === 'object' && 'runtime' in input && input.runtime.includes('.napi')),
1325
- ).toBe(true);
1326
- for (const [name, target] of Object.entries(native)) {
1327
- if (!name.startsWith('napi-') || target.cache !== true) continue;
1328
- expect(target.inputs).toContain(CARGO_CLOSURE_INPUT);
1329
- expect(target.inputs).not.toContain('{workspaceRoot}/**/*.rs');
1330
- }
1331
- const nativeClosure = projects.get('packages/native')?.namedInputs?.[CARGO_CLOSURE_INPUT] ?? [];
1332
- expect(nativeClosure).toContain(
1333
- '{workspaceRoot}/packages/native/crates/native-napi/**/{*.rs,Cargo.toml,.cargo/config,.cargo/config.toml}',
1334
- );
1335
- expect(nativeClosure.some((input) => typeof input === 'string' && input.includes('packages/runtime'))).toBe(
1336
- false,
1337
- );
1338
- expect(napiInputs).not.toContain('{workspaceRoot}/bun.lock');
1339
- expect(napiInputs.some((input) => typeof input === 'string' && input.endsWith('/package.json'))).toBe(false);
1340
- // ... and on the toolchain pin, which it must state itself: `napi build`
1341
- // compiles with the pinned rustc but never spells `cargo --frozen`, so
1342
- // the sweep that gives every other cargo target its identity skips it.
1343
- expect(napiInputs).toContain('{workspaceRoot}/devenv.lock');
1344
- expect(napiInputs).toContain('{workspaceRoot}/tooling/direnv/devenv.lock');
1345
- expect(native['napi-debug']?.options).toMatchObject({
1346
- cwd: '.',
1347
- command:
1348
- 'packages/native/node_modules/.bin/napi build --platform --no-js --dts native.napi.d.ts --manifest-path packages/native/crates/native-napi/Cargo.toml --package native-napi --package-json-path packages/native/package.json --output-dir packages/native/.cache/native-debug',
1349
- });
1350
- const platformBuild = (release: string): string =>
1351
- `packages/native/node_modules/.bin/napi build${release} --platform --no-js --dts native.darwin-arm64.d.ts --target aarch64-apple-darwin --manifest-path packages/native/crates/native-napi/Cargo.toml --package native-napi --package-json-path packages/native/package.json --output-dir packages/native/dist/native/darwin-arm64`;
1352
- expect(native['napi-arm64-macos']?.options).toMatchObject({ cwd: '.', command: platformBuild('') });
1353
- expect(native['napi-arm64-macos']?.configurations?.[RELEASE_CONFIGURATION]).toEqual({
1354
- command: platformBuild(' --release'),
1355
- });
1356
- expect(native.build?.dependsOn).toContainEqual(rootCompile);
1357
- expect(native.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
1358
- for (const inferred of [root, runtime, wasm, native]) {
1359
- expectNoSchedulerThrottle(inferred);
1360
- }
1361
- } finally {
1362
- await workspace.cleanup();
1363
- }
1364
- });
1365
-
1366
- it('keeps root packages, nested workspaces and multiple owned crates in their own lint graph', async () => {
1367
- const workspace = await createWorkspace();
1368
- const declared: Record<string, TargetConfiguration> = {
1369
- 'cargo-lint': { dependsOn: ['...', 'prepare-check'] },
1370
- lint: { dependsOn: ['cargo-lint', 'custom-check'] },
1371
- };
1372
- try {
1373
- await workspace.write('package.json', '{"name":"outer-root"}\n');
1374
- await workspace.write(
1375
- 'Cargo.toml',
1376
- '[workspace]\nmembers = ["packages/group/crates/*"]\nexclude = ["nested"]\n\n[package]\nname = "host-core"\n',
1377
- );
1378
- await workspace.write(
1379
- 'packages/group/package.json',
1380
- JSON.stringify({ name: 'group', nx: { targets: declared } }),
1381
- );
1382
- await workspace.write('packages/group/tsconfig.lib.json', '{}\n');
1383
- await workspace.write('packages/group/crates/alpha/Cargo.toml', '[package]\nname = "alpha-core"\n');
1384
- await workspace.write('packages/group/crates/beta/Cargo.toml', '[package]\nname = "beta-wasm"\n');
1385
- await workspace.write('nested/package.json', '{"name":"inner-root"}\n');
1386
- await workspace.write(
1387
- 'nested/Cargo.toml',
1388
- '[workspace]\nmembers = ["modules/leaf"]\n\n[package]\nname = "inner-host"\n',
1389
- );
1390
- await workspace.write('nested/modules/leaf/package.json', '{"name":"inner-leaf-project"}\n');
1391
- await workspace.write('nested/modules/leaf/Cargo.toml', '[package]\nname = "inner-leaf"\n');
1392
- const inferred = await inferTargets(
1393
- ['package.json', 'packages/group/package.json', 'nested/package.json', 'nested/modules/leaf/package.json'],
1394
- undefined,
1395
- workspace.context,
1396
- );
1397
- const projects = new Map(inferred.flatMap(([, result]) => Object.entries(result.projects ?? {})));
1398
- const outer = projects.get('.')?.targets ?? {};
1399
- const group = projects.get('packages/group')?.targets ?? {};
1400
- const inner = projects.get('nested')?.targets ?? {};
1401
- const leaf = projects.get('nested/modules/leaf')?.targets ?? {};
1402
- // Each cargo workspace root runs one clippy over all its members; the
1403
- // packages owning crates validate through that verdict.
1404
- expect(outer['cargo-lint']?.options?.cwd).toBe('.');
1405
- expect(String(outer['cargo-lint']?.options?.commands?.[1])).toContain('clippy --workspace');
1406
- // Workspace-anchored, because Nx hashes a `{projectRoot}` glob against
1407
- // only the files its project owns, and the group project owns alpha and
1408
- // beta: spelled from the root project, those globs hash nothing and the
1409
- // archive replays stale binaries against edited crates.
1410
- for (const name of ['cargo-lint', 'cargo-test-archive']) {
1411
- expect(outer[name]?.inputs).toEqual(
1412
- expect.arrayContaining([
1413
- '{workspaceRoot}/packages/group/crates/alpha/**/*',
1414
- '{workspaceRoot}/packages/group/crates/beta/**/*',
1415
- ]),
1416
- );
1417
- expect(
1418
- (outer[name]?.inputs ?? []).filter(
1419
- (input) => typeof input === 'string' && input.startsWith('{projectRoot}/packages/'),
1420
- ),
1421
- ).toEqual([]);
1422
- }
1423
- expect(group['cargo-lint']?.dependsOn).toEqual([{ projects: ['outer-root'], target: 'cargo-lint' }]);
1424
- expect(group.build?.dependsOn).toEqual([
1425
- '^build',
1426
- { projects: ['outer-root'], target: 'cargo-test-compile' },
1427
- 'tsc-js',
1428
- ]);
1429
- expect(outer['cargo-lint-host-core']).toBeUndefined();
1430
- expect(inner['cargo-lint']?.options).toMatchObject({ cwd: 'nested' });
1431
- expect(inner['cargo-lint']?.inputs).toContain('{workspaceRoot}/nested/**/*');
1432
- expect(inner['cargo-lint']?.inputs).toContain('{workspaceRoot}/nested/modules/leaf/**/*');
1433
- expect(inner['cargo-lint']?.inputs).not.toContain('{workspaceRoot}/packages/group/crates/alpha/**/*');
1434
- expect(leaf['cargo-lint']?.dependsOn).toEqual([{ projects: ['inner-root'], target: 'cargo-lint' }]);
1435
- expect(leaf['cargo-lint-inner-leaf']).toBeUndefined();
1436
- expect(leaf['cargo-test-inner-leaf']?.options?.cwd).toBe('nested');
1437
- expect(inner['cargo-test-compile']?.options?.cwd).toBe('nested');
1438
- expect(leaf['cargo-test-inner-leaf']?.dependsOn).toEqual([
1439
- { projects: ['inner-root'], target: 'cargo-fetch' },
1440
- { projects: ['inner-root'], target: 'cargo-test-archive' },
1441
- ]);
1442
- expect(inner['cargo-test-archive']?.options?.cwd).toBe('nested');
1443
- expect(resolveDeclaredOverInferred(group, declared, 'cargo-lint')).toMatchObject({
1444
- executor: 'nx:noop',
1445
- cache: true,
1446
- outputs: [],
1447
- dependsOn: [{ projects: ['outer-root'], target: 'cargo-lint' }, 'prepare-check'],
1448
- });
1449
- expect(resolveDeclaredOverInferred(group, declared, 'lint')?.dependsOn).toEqual(['cargo-lint', 'custom-check']);
1450
- } finally {
1451
- await workspace.cleanup();
1452
- }
1453
- });
1454
-
1455
- it('keys every cached cargo target on the declared toolchain pin', async () => {
1456
- const workspace = await createWorkspace();
1457
- try {
1458
- await writeCargoIdentityFixture(workspace);
1459
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
1460
- const cached = cachedCargoTargets(targets);
1461
-
1462
- // Named, so a family that stops being cached — or a new one that starts —
1463
- // shows up here rather than silently leaving the sweep below empty.
1464
- expect(cached.map(([name]) => name).sort()).toEqual([
1465
- 'cargo-cross-test-archive-aarch64-apple-darwin',
1466
- 'cargo-lint',
1467
- 'cargo-lint-cross',
1468
- 'cargo-test-archive',
1469
- 'cargo-test-ferris-core',
1470
- ]);
1471
- // An SDK or toolchain change must invalidate every one of them. The pin
1472
- // is the only thing in the identity that can see one, and it is declared
1473
- // at both fleet locations because a fileset matching nothing is free.
1474
- for (const [name, target] of cached) {
1475
- const declared = (target.inputs ?? []).filter(
1476
- (input) => typeof input === 'string' && input.endsWith('devenv.lock'),
1477
- );
1478
- expect([name, declared]).toEqual([
1479
- name,
1480
- ['{workspaceRoot}/devenv.lock', '{workspaceRoot}/tooling/direnv/devenv.lock'],
1481
- ]);
1482
- }
1483
- } finally {
1484
- await workspace.cleanup();
1485
- }
1486
- });
1487
-
1488
- // Without an `externalDependencies` input Nx keys a task whose executor is
1489
- // not an `@nx/` one on every package in the lockfile, so a lockfile-only
1490
- // commit re-ran every cargo verdict (measured in a consumer: every cargo-test-*
1491
- // runner and the archive re-keyed on a one-integrity bun.lock edit). Here
1492
- // the plugin is this repository's workspace project, which Nx refuses as an
1493
- // external dependency, so each target names none.
1494
- it('keys every cached cargo target on the npm packages it runs, not the lockfile', async () => {
1495
- const workspace = await createWorkspace();
1496
- try {
1497
- await writeCargoIdentityFixture(workspace);
1498
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
1499
- const cached = cachedCargoTargets(targets);
1500
- expect(cached.length).toBeGreaterThan(0);
1501
- for (const [name, target] of cached) {
1502
- const named = (target.inputs ?? []).filter(
1503
- (input) => typeof input === 'object' && 'externalDependencies' in input,
1504
- );
1505
- expect([name, named]).toEqual([name, [{ externalDependencies: [] }]]);
1506
- }
1507
- } finally {
1508
- await workspace.cleanup();
1509
- }
1510
- });
1511
-
1512
- it('names the installed plugin for a cargo target that runs its executor or files, and nothing for cargo alone', () => {
1513
- const plugin = 'node_modules/.bun/@smoothbricks+nx-plugin@0.4.26/node_modules/@smoothbricks/nx-plugin';
1514
- const runner = { executor: '@smoothbricks/nx-plugin:bounded-exec' };
1515
- const archive = `cargo --frozen nextest archive --workspace --tool-config-file "smoo:$PWD/${plugin}/nextest.toml"`;
1516
- const clippy = CARGO_LINT_CLIPPY_COMMAND;
1517
- expect(cargoCommandNpmPackages(runner, 'cargo --frozen nextest run', true)).toEqual(['@smoothbricks/nx-plugin']);
1518
- expect(cargoCommandNpmPackages({ executor: 'nx:run-commands' }, archive, true)).toEqual([
1519
- '@smoothbricks/nx-plugin',
1520
- ]);
1521
- expect(cargoCommandNpmPackages({ executor: 'nx:run-commands' }, clippy, true)).toEqual([]);
1522
- expect(cargoCommandNpmPackages(runner, archive, false)).toEqual([]);
1523
- });
1524
-
1525
- // The property that decides whether Rust can ever use a shared cache. A cargo
1526
- // target's identity used to include a dump of the ambient cargo environment,
1527
- // whose values are absolute `/nix/store/…` and per-checkout devenv state
1528
- // paths: no two machines agreed, and the same target hashed differently in a
1529
- // bare shell and inside a devenv profile, which made the pre-push
1530
- // cross-compile probe unsatisfiable by construction.
1531
- //
1532
- // The runtime value AND its command declaration must be portable: Nx also
1533
- // hashes the owning project's target configuration.
1534
- it('hashes no machine-local value into a cached cargo target', async () => {
1535
- const workspace = await createWorkspace();
1536
- try {
1537
- await writeCargoIdentityFixture(workspace);
1538
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
1539
- // Installed the way a consumer links it, so the inputs find the wrapper they name. After
1540
- // inference, whose fixture walk would follow the link.
1541
- await mkdir(join(workspace.context.workspaceRoot, 'node_modules/@smoothbricks'), { recursive: true });
1542
- await symlink(
1543
- fileURLToPath(new URL('..', import.meta.url)),
1544
- join(workspace.context.workspaceRoot, 'node_modules/@smoothbricks/nx-plugin'),
1545
- );
1546
- const offenders: string[] = [];
1547
- for (const [name, target] of cachedCargoTargets(targets)) {
1548
- for (const input of target.inputs ?? []) {
1549
- if (typeof input === 'string') {
1550
- if (!WORKSPACE_ANCHORED_INPUT.test(input)) offenders.push(`${name}: fileset ${input}`);
1551
- continue;
1552
- }
1553
- if ('env' in input) offenders.push(`${name}: environment input ${String(input.env)}`);
1554
- if (!('runtime' in input)) continue;
1555
- if (input.runtime.includes(fileURLToPath(new URL('..', import.meta.url)))) {
1556
- offenders.push(`${name}: runtime command names the plugin checkout`);
1557
- }
1558
- const value = await runtimeInputValue(input.runtime, workspace.context.workspaceRoot);
1559
- const rooted = PATH_OUTSIDE_WORKSPACE.exec(value);
1560
- if (rooted) offenders.push(`${name}: runtime input yields ${rooted[0].trim()} — from ${input.runtime}`);
1561
- }
1562
- }
1563
- expect(offenders).toEqual([]);
1564
- } finally {
1565
- await workspace.cleanup();
1566
- }
1567
- });
1568
-
1569
- // A consumer links the plugin from a checkout of its own, outside the
1570
- // workspace, and its forks sit at different depths. Nx hashes a project's
1571
- // configuration into every task of that project and of its dependents, so
1572
- // the configuration must not know how deep the workspace is: measured, a
1573
- // `../` count in the tool config path re-keyed 118 tasks of a fork of a warm
1574
- // main.
1575
- it('infers byte-identical cargo targets for a workspace at any depth', async () => {
1576
- const parent = await realpath(await mkdtemp(join(tmpdir(), 'smoothbricks-nx-plugin-depth-')));
1577
- const plugin = fileURLToPath(new URL('..', import.meta.url));
1578
- const pluginNextestConfig = await readFile(join(plugin, 'nextest.toml'), 'utf8');
1579
- try {
1580
- const inferred: string[] = [];
1581
- for (const dir of [parent, join(parent, 'a/b/c')]) {
1582
- await mkdir(dir, { recursive: true });
1583
- const workspace = await createWorkspace(dir);
1584
- const root = workspace.context.workspaceRoot;
1585
- await writeCargoIdentityFixture(workspace);
1586
- const project = await inferProject(workspace, 'packages/ferris/package.json');
1587
- // Installed the way a consumer links it: a checkout outside the
1588
- // workspace. After inference, whose fixture walk would follow it.
1589
- await mkdir(join(root, 'node_modules/@smoothbricks'), { recursive: true });
1590
- await symlink(plugin, join(root, 'node_modules/@smoothbricks/nx-plugin'));
1591
- // Stable is not enough: from where each command runs, the spelling
1592
- // must name the config the plugin ships.
1593
- const configured: string[] = [];
1594
- for (const [name, target] of cachedCargoTargets(project?.targets ?? {})) {
1595
- const named = /--tool-config-file "smoo:\$PWD\/([^"]+)"/.exec(String(target.options?.command));
1596
- if (!named?.[1]) continue;
1597
- configured.push(name);
1598
- const config = await readFile(join(root, String(target.options?.cwd), named[1]), 'utf8');
1599
- expect([name, config]).toEqual([name, pluginNextestConfig]);
1600
- }
1601
- expect(configured.sort()).toEqual([
1602
- 'cargo-cross-test-archive-aarch64-apple-darwin',
1603
- 'cargo-test-archive',
1604
- 'cargo-test-ferris-core',
1605
- ]);
1606
- inferred.push(JSON.stringify(project, null, 2));
1607
- }
1608
- expect(inferred[1]).toBe(inferred[0]);
1609
- } finally {
1610
- await rm(parent, { recursive: true, force: true });
1611
- }
1612
- });
1613
-
1614
- it('scopes each per-crate cargo-test command to exactly one package', async () => {
1615
- const workspace = await createWorkspace();
1616
- try {
1617
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
1618
- await workspace.write(
1619
- 'packages/ferris/Cargo.toml',
1620
- '[workspace]\nmembers = ["crates/ferris-core", "crates/ferris-wasm"]\n',
1621
- );
1622
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
1623
- await workspace.write('packages/ferris/crates/ferris-wasm/Cargo.toml', '[package]\nname = "ferris-wasm"\n');
1624
-
1625
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
1626
-
1627
- // Scoped by filterset over one archived workspace build: exactly one
1628
- // crate runs, and no `-p` re-resolves its features.
1629
- expect(cargoPackageSelection(String(targets['cargo-test-ferris-core']?.options?.command ?? ''))).toEqual({
1630
- prebuiltRun: true,
1631
- packageFlags: [],
1632
- filtered: ['ferris-core'],
1633
- });
1634
- expect(cargoPackageSelection(String(targets['cargo-test-ferris-wasm']?.options?.command ?? ''))).toEqual({
1635
- prebuiltRun: true,
1636
- packageFlags: [],
1637
- filtered: ['ferris-wasm'],
1638
- });
1639
- expect(targets['cargo-test-ferris-core']?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
1640
- expect(targets['cargo-test-ferris-wasm']?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
1641
- expect(targets['cargo-test']?.dependsOn).toEqual(['cargo-test-ferris-core', 'cargo-test-ferris-wasm']);
1642
- } finally {
1643
- await workspace.cleanup();
1644
- }
1645
- });
1646
-
1647
- it('extracts the test archive once for all per-crate runners, and again only when its bytes change', async () => {
1648
- const workspace = await createWorkspace();
1649
- const root = workspace.context.workspaceRoot;
1650
- const crates = ['ferris-a', 'ferris-b', 'ferris-c'];
1651
- try {
1652
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
1653
- await workspace.write('packages/ferris/Cargo.toml', '[workspace]\nmembers = ["crates/*"]\n');
1654
- for (const crate of crates) {
1655
- await workspace.write(`packages/ferris/crates/${crate}/Cargo.toml`, `[package]\nname = "${crate}"\n`);
1656
- }
1657
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
1658
- // Installed the way a consumer has it, so each command finds the helper it names.
1659
- await mkdir(join(root, 'node_modules/@smoothbricks'), { recursive: true });
1660
- await symlink(fileURLToPath(new URL('..', import.meta.url)), join(root, 'node_modules/@smoothbricks/nx-plugin'));
1661
- // A cargo that does what nextest does with an archive, and says so: an
1662
- // `--archive-file` unpacks it (into `--extract-to`, or a private temp
1663
- // dir when a run is given the archive itself), and a run reports which
1664
- // archive's binaries it executed. `metadata` names the workspace's
1665
- // target directory, where the extraction root lives.
1666
- const log = join(root, 'nextest.log');
1667
- await workspace.write(
1668
- 'bin/cargo',
1669
- [
1670
- '#!/bin/sh',
1671
- 'archive= dest= binaries=',
1672
- 'while [ $# -gt 0 ]; do',
1673
- ' case "$1" in',
1674
- ' metadata) printf \'{"target_directory":"%s/target"}\\n\' "$PWD"; exit 0 ;;',
1675
- ' --archive-file) archive=$2; shift ;;',
1676
- ' --extract-to) dest=$2; shift ;;',
1677
- ' --binaries-metadata) binaries=$2; shift ;;',
1678
- ' esac',
1679
- ' shift',
1680
- 'done',
1681
- 'if [ -n "$archive" ]; then',
1682
- ' echo "extract $(cat "$archive")" >> "$FAKE_NEXTEST_LOG"',
1683
- ' if [ -z "$dest" ]; then echo "run $(cat "$archive")" >> "$FAKE_NEXTEST_LOG"; exit 0; fi',
1684
- ' mkdir -p "$dest/target/nextest"',
1685
- ' cat "$archive" > "$dest/target/nextest/binaries-metadata.json"',
1686
- ' cat "$archive" > "$dest/target/nextest/cargo-metadata.json"',
1687
- ' exit 0',
1688
- 'fi',
1689
- 'echo "run $(cat "$binaries")" >> "$FAKE_NEXTEST_LOG"',
1690
- '',
1691
- ].join('\n'),
1692
- );
1693
- await chmod(join(root, 'bin/cargo'), 0o755);
1694
- // Every runner at once, through `sh -c` exactly as bounded-exec spawns it.
1695
- const runAll = () =>
1696
- Promise.all(
1697
- crates.map(async (crate) => {
1698
- const options = targets[`cargo-test-${crate}`]?.options;
1699
- const child = Bun.spawn(['sh', '-c', String(options?.command)], {
1700
- cwd: join(root, String(options?.cwd)),
1701
- env: { ...process.env, PATH: `${join(root, 'bin')}:${process.env.PATH}`, FAKE_NEXTEST_LOG: log },
1702
- stdout: 'pipe',
1703
- stderr: 'pipe',
1704
- });
1705
- const [exitCode, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]);
1706
- return { crate, exitCode, stderr };
1707
- }),
1708
- );
1709
-
1710
- await workspace.write('packages/ferris/.cache/nextest/archive.tar.zst', 'first archive');
1711
- for (const run of await runAll()) {
1712
- expect(run).toMatchObject({ exitCode: 0 });
1713
- }
1714
- expect((await readFile(log, 'utf8')).trim().split('\n').sort()).toEqual([
1715
- 'extract first archive',
1716
- 'run first archive',
1717
- 'run first archive',
1718
- 'run first archive',
1719
- ]);
1720
-
1721
- // A rebuilt archive is new bytes at the same path: the runners must not
1722
- // execute what the old one unpacked, and the old unpacking is garbage.
1723
- await workspace.write('packages/ferris/.cache/nextest/archive.tar.zst', 'second archive');
1724
- for (const run of await runAll()) {
1725
- expect(run).toMatchObject({ exitCode: 0 });
1726
- }
1727
- expect((await readFile(log, 'utf8')).trim().split('\n').sort()).toEqual([
1728
- 'extract first archive',
1729
- 'extract second archive',
1730
- 'run first archive',
1731
- 'run first archive',
1732
- 'run first archive',
1733
- 'run second archive',
1734
- 'run second archive',
1735
- 'run second archive',
1736
- ]);
1737
- // The old unpacking is gone from Cargo's build tree, and the archive's
1738
- // directory holds only the archive, the declared Nx output.
1739
- const extracted = join(root, 'packages/ferris/target', NEXTEST_EXTRACTION_DIRECTORY);
1740
- const unpacked = (await readdir(extracted, { recursive: true })).filter((path) =>
1741
- path.endsWith('binaries-metadata.json'),
1742
- );
1743
- expect(await Promise.all(unpacked.map((path) => readFile(join(extracted, path), 'utf8')))).toEqual([
1744
- 'second archive',
1745
- ]);
1746
- expect(await readdir(join(root, 'packages/ferris/.cache/nextest'))).toEqual(['archive.tar.zst']);
1747
- } finally {
1748
- await workspace.cleanup();
1749
- }
1750
- });
1751
-
1752
- it('infers a cached Cargo Wasm build directly from crate metadata', async () => {
1753
- const workspace = await createWorkspace();
1754
- try {
1755
- await workspace.write('packages/git-do/package.json', '{"name":"git-do"}\n');
1756
- await workspace.write(
1757
- 'packages/git-do/crates/git-do/Cargo.toml',
1758
- [
1759
- '[package]',
1760
- 'name = "git-do"',
1761
- '',
1762
- '[lib]',
1763
- 'name = "gitoxide_engine"',
1764
- 'crate-type = ["cdylib", "rlib"]',
1765
- '',
1766
- '[package.metadata.smoothbricks.wasm-bindgen]',
1767
- 'targets = ["nodejs", "web"]',
1768
- 'out-dir = "generated/wasm"',
1769
- '',
1770
- ].join('\n'),
1771
- );
1772
- await workspace.write('packages/git-do/tsconfig.lib.json', '{"compilerOptions":{"outDir":"dist"}}\n');
1773
-
1774
- const targets = await inferProjectTargets(workspace, 'packages/git-do/package.json');
1775
-
1776
- // A release bumps package.json and the lockfile before it builds; neither
1777
- // is part of a wasm artifact, so neither may be an input.
1778
- expect(targets['cargo-wasm']?.inputs).not.toContain('{projectRoot}/package.json');
1779
- expect(targets['cargo-wasm']?.inputs).not.toContain('{workspaceRoot}/bun.lock');
1780
- expect(targets['cargo-wasm']).toMatchObject({
1781
- executor: 'nx:run-commands',
1782
- cache: true,
1783
- dependsOn: ['cargo-fetch', '^build'],
1784
- inputs: expect.arrayContaining(['{projectRoot}/**/*.rs', '{projectRoot}/**/Cargo.toml']),
1785
- outputs: ['{projectRoot}/generated/wasm'],
1786
- options: {
1787
- command: [
1788
- 'cargo --frozen build --target wasm32-unknown-unknown --manifest-path crates/git-do/Cargo.toml',
1789
- 'wasm-bindgen --target nodejs --out-dir generated/wasm/node crates/git-do/target/wasm32-unknown-unknown/debug/gitoxide_engine.wasm',
1790
- 'wasm-bindgen --target web --out-dir generated/wasm/web crates/git-do/target/wasm32-unknown-unknown/debug/gitoxide_engine.wasm',
1791
- ].join(' && '),
1792
- cwd: 'packages/git-do',
1793
- },
1794
- });
1795
- // No workspace claims the crate, so cargo's default target dir is the one
1796
- // beside its own manifest, and the release configuration reads the
1797
- // release artifact from it.
1798
- expect(targets['cargo-wasm']?.options?.commands).toBeUndefined();
1799
- expect(targets['cargo-wasm']?.configurations?.[RELEASE_CONFIGURATION]).toEqual({
1800
- command: [
1801
- 'cargo --frozen build --release --target wasm32-unknown-unknown --manifest-path crates/git-do/Cargo.toml',
1802
- 'wasm-bindgen --target nodejs --out-dir generated/wasm/node crates/git-do/target/wasm32-unknown-unknown/release/gitoxide_engine.wasm',
1803
- 'wasm-bindgen --target web --out-dir generated/wasm/web crates/git-do/target/wasm32-unknown-unknown/release/gitoxide_engine.wasm',
1804
- ].join(' && '),
1805
- });
1806
- // A wasm-bindgen crate in a nested Cargo workspace still needs its locked
1807
- // graph downloaded, and the project root is not a member of it, so the
1808
- // fetch names the crate manifest instead of relying on cwd.
1809
- expect(targets['cargo-fetch']?.options).toEqual({
1810
- commands: ['cargo fetch --locked --manifest-path crates/git-do/Cargo.toml'],
1811
- cwd: 'packages/git-do',
1812
- });
1813
- expect(targets['tsc-js']?.dependsOn).toEqual(['^*-js', 'cargo-wasm']);
1814
- expect(targets.typecheck?.dependsOn).toEqual(['^*-js', 'cargo-wasm']);
1815
- expect(targets.build?.dependsOn).toEqual(['^build', 'cargo-wasm', 'tsc-js']);
1816
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
1817
- // A nested crate manifest is enough for output inference, but not for
1818
- // workspace-wide cargo-test/lint policy.
1819
- expect(targets['cargo-test']).toBeUndefined();
1820
- expect(targets['cargo-lint']).toBeUndefined();
1821
- expectNoSchedulerThrottle(targets);
1822
- } finally {
1823
- await workspace.cleanup();
1824
- }
1825
- });
1826
-
1827
- it('infers disjoint host and release targets from canonical N-API metadata', async () => {
1828
- const workspace = await createWorkspace();
1829
- try {
1830
- await workspace.write(
1831
- 'packages/cowshed/package.json',
1832
- JSON.stringify({
1833
- name: 'cowshed',
1834
- scripts: { test: 'nx run cowshed:test --outputStyle=stream' },
1835
- nx: {
1836
- targets: {
1837
- 'cli-arm64-macos': { executor: 'nx:run-commands', options: { command: 'true' } },
1838
- 'cli-x64-linux': { executor: 'nx:run-commands', options: { command: 'true' } },
1839
- },
1840
- },
1841
- napi: {
1842
- binaryName: 'cowshed',
1843
- targets: [
1844
- 'aarch64-apple-darwin',
1845
- 'x86_64-apple-darwin',
1846
- 'aarch64-unknown-linux-gnu',
1847
- 'x86_64-unknown-linux-gnu',
1848
- ],
1849
- },
1850
- }),
1851
- );
1852
- await workspace.write('packages/cowshed/Cargo.toml', '[workspace]\nmembers = ["crates/cowshed-napi"]\n');
1853
- await workspace.write(
1854
- 'packages/cowshed/crates/cowshed-napi/Cargo.toml',
1855
- '[package]\nname = "cowshed-napi"\n\n[lib]\ncrate-type = ["cdylib"]\n',
1856
- );
1857
- await workspace.write(
1858
- 'packages/cowshed/tsconfig.lib.json',
1859
- '{"compilerOptions":{"outDir":"dist/ts","tsBuildInfoFile":"dist/ts/tsconfig.lib.tsbuildinfo"}}\n',
1860
- );
1861
- await workspace.write('packages/cowshed/src/native.test.ts', 'export {};\n');
1862
-
1863
- const targets = await inferProjectTargets(workspace, 'packages/cowshed/package.json');
1864
-
1865
- expect(targets['cargo-wasm']).toBeUndefined();
1866
- expect(targets['tsc-js']?.outputs).toEqual(['{projectRoot}/dist/ts']);
1867
- // This fixture declares all four supported triples, so on EVERY supported
1868
- // runner the host's own triple is present and native: the host provider is
1869
- // that platform target and `cargo-napi` is never inferred. Tying the native
1870
- // regime to `-macos` asserted a macOS-only model and failed on Linux with
1871
- // zero host providers found. The dedicated `cargo-napi` regime is covered
1872
- // below against a platform no declared triple can serve, which reaches it
1873
- // on every runner instead of only on Linux.
1874
- const hostOs = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : null;
1875
- const hostArch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x64' : null;
1876
- const hostSuffix = hostOs !== null && hostArch !== null ? `-${hostArch}-${hostOs}` : null;
1877
- expect(hostSuffix).not.toBeNull();
1878
- expect(targets[`napi${hostSuffix}`]).toBeDefined();
1879
- expect(targets['cargo-napi']).toBeUndefined();
1880
-
1881
- // A platform outside NAPI_TARGET_CONVENTIONS leaves no native host target,
1882
- // which is precisely the condition that infers the dedicated host build.
1883
- const unservedHostTargets = await inferProjectTargets(
1884
- workspace,
1885
- 'packages/cowshed/package.json',
1886
- createNodesV2ForPlatform('win32', 'x64'),
1887
- );
1888
- expect(unservedHostTargets['cargo-napi']).toMatchObject({
1889
- executor: 'nx:run-commands',
1890
- cache: true,
1891
- // The dedicated host build consumes only its dependencies' outputs; it is
1892
- // not ordered behind the test compile.
1893
- dependsOn: ['^build'],
1894
- outputs: ['{projectRoot}/dist/native/host'],
1895
- options: {
1896
- cwd: 'packages/cowshed',
1897
- command:
1898
- 'napi build --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --package-json-path package.json --output-dir dist/native/host',
1899
- },
1900
- configurations: {
1901
- [RELEASE_CONFIGURATION]: {
1902
- command:
1903
- 'napi build --release --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --package-json-path package.json --output-dir dist/native/host',
1904
- },
1905
- },
1906
- });
1907
- expect(unservedHostTargets.build?.dependsOn).toEqual(['^build', 'cargo-test-compile', 'cargo-napi', 'tsc-js']);
1908
- expect(targets['napi-arm64-macos']?.outputs).toEqual(['{projectRoot}/dist/native/darwin-arm64']);
1909
- // Every local build compiles dev; only the release configuration ships.
1910
- const darwinArm64Build = (release: string): string =>
1911
- `napi build${release} --platform --no-js --dts cowshed.darwin-arm64.d.ts --target aarch64-apple-darwin --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --package-json-path package.json --output-dir dist/native/darwin-arm64`;
1912
- expect(targets['napi-arm64-macos']?.options).toMatchObject({ command: darwinArm64Build('') });
1913
- expect(targets['napi-arm64-macos']?.configurations?.[RELEASE_CONFIGURATION]).toEqual({
1914
- command: darwinArm64Build(' --release'),
1915
- });
1916
- expect(targets['napi-arm64-macos']?.options?.env).toBeUndefined();
1917
- // No cargo-test-compile edge here, on ANY host: the platform build consumes
1918
- // nothing from it, and a platform target's dependency closure may only reach
1919
- // its own family (`validatePlatformTargetDependencies`).
1920
- expect(targets['napi-arm64-macos']?.dependsOn).toBeUndefined();
1921
- // Every host infers the SAME Linux addon target: devenv's zig through the
1922
- // cargo-zigbuild executor, glibc pinned by the triple suffix. There is no
1923
- // native-versus-cross branch to diverge on, so forcing a Linux host and a
1924
- // macOS host must yield byte-identical Linux targets, and neither may
1925
- // carry a compiler environment or a toolchain prerequisite.
1926
- const linuxX64Targets = await inferProjectTargets(
1927
- workspace,
1928
- 'packages/cowshed/package.json',
1929
- createNodesV2ForPlatform('linux', 'x64'),
1930
- );
1931
- const darwinArm64Targets = await inferProjectTargets(
1932
- workspace,
1933
- 'packages/cowshed/package.json',
1934
- createNodesV2ForPlatform('darwin', 'arm64'),
1935
- );
1936
- expect(darwinArm64Targets['napi-x64-linux']).toMatchObject({
1937
- executor: '@smoothbricks/nx-plugin:cargo-zigbuild',
1938
- cache: true,
1939
- outputs: ['{projectRoot}/dist/native/linux-x64-gnu'],
1940
- options: {
1941
- target: 'x86_64-unknown-linux-gnu.2.17',
1942
- manifestPath: 'packages/cowshed/crates/cowshed-napi/Cargo.toml',
1943
- package: 'cowshed-napi',
1944
- output: '{projectRoot}/dist/native/linux-x64-gnu/cowshed.linux-x64-gnu.node',
1945
- },
1946
- configurations: { [RELEASE_CONFIGURATION]: { release: true } },
1947
- });
1948
- expect(darwinArm64Targets['napi-arm64-linux']?.options).toMatchObject({
1949
- target: 'aarch64-unknown-linux-gnu.2.17',
1950
- output: '{projectRoot}/dist/native/linux-arm64-gnu/cowshed.linux-arm64-gnu.node',
1951
- });
1952
- for (const suffix of ['arm64-linux', 'x64-linux']) {
1953
- expect(linuxX64Targets[`napi-${suffix}`]).toEqual(darwinArm64Targets[`napi-${suffix}`]);
1954
- expect(darwinArm64Targets[`napi-${suffix}`]?.dependsOn).toBeUndefined();
1955
- }
1956
- for (const inferred of [linuxX64Targets, darwinArm64Targets]) {
1957
- expect(Object.keys(inferred).filter((name) => name.startsWith('napi-toolchain-'))).toEqual([]);
1958
- expect(inferred['napi-debug']?.options?.env).toBeUndefined();
1959
- for (const suffix of ['arm64-macos', 'x64-macos']) {
1960
- expect(inferred[`napi-${suffix}`]?.options?.command).toContain('napi build');
1961
- expect(inferred[`napi-${suffix}`]?.options?.env).toBeUndefined();
1962
- }
1963
- }
1964
- // The aggregate build pulls in exactly the inferring host's
1965
- // platform-suffixed targets (publish still owns foreign platforms), and
1966
- // the only cargo-test work it owns is compiling the executables — every
1967
- // RUNNER is reached through `test`. Both hosts are asserted here so the
1968
- // expectation does not depend on which machine runs the suite: the
1969
- // previous form read `process.platform`, and the macOS answer was the only
1970
- // one anyone checked.
1971
- for (const [inferred, hostSuffix] of [
1972
- [linuxX64Targets, '-x64-linux'],
1973
- [darwinArm64Targets, '-arm64-macos'],
1974
- ] as const) {
1975
- const hostNapiTargets = [
1976
- 'cli-arm64-macos',
1977
- 'cli-x64-linux',
1978
- 'napi-arm64-macos',
1979
- 'napi-x64-macos',
1980
- 'napi-arm64-linux',
1981
- 'napi-x64-linux',
1982
- ]
1983
- .filter((name) => name.endsWith(hostSuffix))
1984
- .sort();
1985
- expect(hostNapiTargets.length).toBeGreaterThan(0);
1986
- expect(inferred.build?.dependsOn).toEqual(['^build', 'cargo-test-compile', 'tsc-js', ...hostNapiTargets]);
1987
- // Crate `cowshed-napi` names its bounded runner `cargo-test-cowshed-napi`;
1988
- // the retired `*-napi` output-family glob matched it on suffix alone and
1989
- // put the whole cargo test suite inside `nx run-many -t build`.
1990
- expect(inferred['cargo-test-cowshed-napi']).toBeDefined();
1991
- for (const dependency of inferred.build?.dependsOn ?? []) {
1992
- expect(String(dependency).startsWith('cargo-test-')).toBe(dependency === 'cargo-test-compile');
1993
- }
1994
- for (const dependency of inferred.build?.dependsOn ?? []) {
1995
- if (typeof dependency === 'string' && /-(?:arm64|x64)-(?:macos|linux)$/.test(dependency)) {
1996
- expect(dependency.endsWith(hostSuffix)).toBe(true);
1997
- }
1998
- }
1999
- }
2000
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
2001
- // The test suite runs against the dev-profile addon, never a release
2002
- // platform build: napi-debug shares target/debug with cargo-test, keeps
2003
- // the release binaries off the test critical path, and lives outside
2004
- // dist/ so the wholesale-packaged dist/ tree can never ship it.
2005
- expect(targets['napi-debug']).toMatchObject({
2006
- executor: 'nx:run-commands',
2007
- cache: true,
2008
- dependsOn: ['^build'],
2009
- outputs: ['{projectRoot}/.cache/native-debug'],
2010
- options: {
2011
- cwd: 'packages/cowshed',
2012
- command:
2013
- 'napi build --platform --no-js --dts cowshed.napi.d.ts --manifest-path crates/cowshed-napi/Cargo.toml --package cowshed-napi --package-json-path package.json --output-dir .cache/native-debug',
2014
- },
2015
- });
2016
- expect(targets['cargo-test']?.dependsOn).toEqual(['cargo-test-cowshed-napi']);
2017
- // cargo-fetch survives the napi-debug edge: the per-crate runner is itself
2018
- // a frozen cargo command, so its precondition is its own edge. It reads
2019
- // the workspace archive and still waits for the debug cdylib its own
2020
- // project builds, because its tests load that artifact from `target/`.
2021
- expect(targets['cargo-test-cowshed-napi']?.dependsOn).toEqual([
2022
- 'cargo-fetch',
2023
- 'cargo-test-archive',
2024
- 'napi-debug',
2025
- ]);
2026
- expect(targets['cargo-test-cowshed-napi']?.options?.command).toMatch(
2027
- /^extracted="\$\(node \.\.\/\.\.\/node_modules\/@smoothbricks\/nx-plugin\/dist\/bin\/smoo-nx-nextest-extract\.js \.cache\/nextest\/archive\.tar\.zst\)" && cargo --frozen nextest run --binaries-metadata "\$extracted\/target\/nextest\/binaries-metadata\.json" --cargo-metadata "\$extracted\/target\/nextest\/cargo-metadata\.json" --target-dir-remap "\$extracted\/target" --workspace-remap \. -E 'package\(cowshed-napi\)' --no-fail-fast --no-tests=pass --user-config-file none --tool-config-file "smoo:\$PWD\/.*nextest\.toml"$/,
2028
- );
2029
- expect(targets['napi-test']).toMatchObject({
2030
- executor: '@smoothbricks/nx-plugin:bounded-exec',
2031
- cache: true,
2032
- dependsOn: ['cargo-test', 'napi-debug', 'tsc-js', '^build'],
2033
- options: {
2034
- command: 'bun test --config=../bunfig.toml --timeout=0 native.test.ts',
2035
- cwd: 'packages/cowshed/src',
2036
- env: { NAPI_DEBUG_ADDON: '1' },
2037
- idleTimeoutMs: BOUNDED_TEST_IDLE_TIMEOUT_MS,
2038
- killAfterMs: 10000,
2039
- },
2040
- });
2041
- expectNoSchedulerThrottle(targets);
2042
- await workspace.write('packages/cowshed/bunfig.napi-test.toml', '[test]\n');
2043
- const targetsWithDedicatedBunfig = await inferProjectTargets(workspace, 'packages/cowshed/package.json');
2044
- expect(targetsWithDedicatedBunfig['napi-test']?.options?.command).toBe(
2045
- 'bun test --config=../bunfig.napi-test.toml --timeout=0 native.test.ts',
2046
- );
2047
- } finally {
2048
- await workspace.cleanup();
2049
- }
2050
- });
2051
-
2052
- it('keeps an explicit package-local cargo-wasm target singular and feeding the aggregate build', async () => {
2053
- const workspace = await createWorkspace();
2054
- try {
2055
- await workspace.write(
2056
- 'packages/columine/package.json',
2057
- JSON.stringify({
2058
- name: 'columine',
2059
- nx: {
2060
- targets: {
2061
- 'cargo-wasm': { executor: 'nx:run-commands', outputs: ['{projectRoot}/dist/**/*.wasm'] },
2062
- },
2063
- },
2064
- }),
2065
- );
2066
- await workspace.write(
2067
- 'packages/columine/Cargo.toml',
2068
- '[workspace]\nmembers = ["crates/columine-wasm"]\n\n[profile.wasm-release]\ninherits = "release"\n',
2069
- );
2070
- await workspace.write(
2071
- 'packages/columine/crates/columine-wasm/Cargo.toml',
2072
- '[package]\nname = "columine-wasm"\n\n[lib]\ncrate-type = ["cdylib", "rlib"]\n\n[package.metadata.smoothbricks.wasm-bindgen]\ntargets = ["web"]\n',
2073
- );
2074
-
2075
- const targets = await inferProjectTargets(workspace, 'packages/columine/package.json');
2076
-
2077
- // The declared target stays the only cargo-wasm: inference never emits a
2078
- // duplicate for Nx to merge, even with a cdylib *-wasm member crate present.
2079
- expect(targets['cargo-wasm']).toBeUndefined();
2080
- // Its declared *-wasm output-family name feeds the aggregate build and
2081
- // clean by concrete name, and the cargo workspace's test-executable
2082
- // compilation comes with it.
2083
- expect(targets.build?.executor).toBe('nx:noop');
2084
- expect(targets.build?.dependsOn).toEqual(['^build', 'cargo-test-compile', 'cargo-wasm']);
2085
- expect(targets.clean?.executor).toBe('@smoothbricks/nx-plugin:clean-outputs');
2086
- } finally {
2087
- await workspace.cleanup();
2088
- }
2089
- });
2090
-
2091
- it('binds the wasm a package workspace member writes into that workspace target dir', async () => {
2092
- const workspace = await createWorkspace();
2093
- try {
2094
- await workspace.write('packages/columine/package.json', '{"name":"columine"}\n');
2095
- await workspace.write('packages/columine/Cargo.toml', '[workspace]\nmembers = ["crates/columine-wasm"]\n');
2096
- await workspace.write(
2097
- 'packages/columine/crates/columine-wasm/Cargo.toml',
2098
- '[package]\nname = "columine-wasm"\n\n[lib]\ncrate-type = ["cdylib", "rlib"]\n\n[package.metadata.smoothbricks.wasm-bindgen]\ntargets = ["web"]\n',
2099
- );
2100
-
2101
- const targets = await inferProjectTargets(workspace, 'packages/columine/package.json');
2102
-
2103
- // Cargo writes a member's artifacts under its workspace root, not beside
2104
- // the member's manifest, so the bindgen input is read from there.
2105
- expect(targets['cargo-wasm']?.options?.command).toBe(
2106
- [
2107
- 'cargo --frozen build --target wasm32-unknown-unknown --manifest-path crates/columine-wasm/Cargo.toml',
2108
- 'wasm-bindgen --target web --out-dir dist-wasm/web target/wasm32-unknown-unknown/debug/columine_wasm.wasm',
2109
- ].join(' && '),
2110
- );
2111
- } finally {
2112
- await workspace.cleanup();
2113
- }
2114
- });
2115
-
2116
- it('partitions ordinary and exceptional tests into disjoint hash shards of the same declared count', async () => {
2117
- const workspace = await createWorkspace();
2118
- try {
2119
- await workspace.write('packages/rusty/package.json', '{"name":"rusty"}\n');
2120
- await workspace.write('packages/rusty/Cargo.toml', '[workspace]\nmembers = ["crates/big", "crates/small"]\n');
2121
- await workspace.write(
2122
- 'packages/rusty/crates/big/Cargo.toml',
2123
- '[package]\nname = "big"\n\n[package.metadata.smoothbricks.test]\nshards = 3\n',
2124
- );
2125
- await workspace.write('packages/rusty/crates/small/Cargo.toml', '[package]\nname = "small"\n');
2126
-
2127
- const targets = await inferProjectTargets(workspace, 'packages/rusty/package.json');
2128
-
2129
- // An unsharded crate keeps the bare name and takes no --partition, so
2130
- // declaring nothing is exactly the old single-target behaviour.
2131
- expect(targets['cargo-test-small']?.options?.command).toMatch(
2132
- /--workspace-remap \. -E 'package\(small\)' --no-fail-fast --no-tests=pass --user-config-file none/,
2133
- );
2134
- // The shards partition the crate MINUS the classes nextest.toml singles
2135
- // out, i of N. Those are lifted out because a test carrying a raised
2136
- // slow-timeout costs what the suite does not — the compile-fail test
2137
- // rustc's a fixture for 25.6s on a cold target dir against 1.8s warm.
2138
- const exceptional = exceptionalTestFilter(fileURLToPath(new URL('../nextest.toml', import.meta.url)));
2139
- if (exceptional === null) {
2140
- throw new Error('nextest.toml declares no overrides; this test asserts the pin that protects them');
2141
- }
2142
- for (const index of [1, 2, 3]) {
2143
- expect(targets[`cargo-test-big-shard${index}`]?.options?.command).toContain(
2144
- `-E 'package(big) and not (${exceptional})' --partition hash:${index}/3 --no-fail-fast --no-tests=pass`,
2145
- );
2146
- expect(targets[`cargo-test-big-shard${index}`]?.options?.idleTimeoutMs).toBe(BOUNDED_TEST_IDLE_TIMEOUT_MS);
2147
- expect(targets[`cargo-test-big-shard${index}`]?.options).not.toHaveProperty('timeoutMs');
2148
- }
2149
- // Exceptional partitions are the exact complement, hashed by the same
2150
- // declared count; each keeps the full bounded window.
2151
- for (const index of [1, 2, 3]) {
2152
- const name = `cargo-test-big-exceptions-shard${index}`;
2153
- expect(targets[name]?.options?.command).toContain(
2154
- `-E 'package(big) and (${exceptional})' --partition hash:${index}/3 --no-fail-fast --no-tests=pass`,
2155
- );
2156
- expect(targets[name]?.options?.idleTimeoutMs).toBe(BOUNDED_TEST_IDLE_TIMEOUT_MS);
2157
- expect(packageNameFromCargoTestTarget(name)).toBe('big');
2158
- }
2159
- expect(targets['cargo-test-big-exceptions']).toBeUndefined();
2160
- // An unsharded crate needs no pin: its whole suite is already one run.
2161
- expect(targets['cargo-test-small-exceptions']).toBeUndefined();
2162
- expect(targets['cargo-test-big']).toBeUndefined();
2163
- // Every piece reaches the aggregate, and they all hang off the one
2164
- // archive: a run extracts binaries to its own temp directory and writes
2165
- // nothing to cargo's target/, so no piece waits on another.
2166
- expect(targets['cargo-test']?.dependsOn).toEqual([
2167
- 'cargo-test-big-shard1',
2168
- 'cargo-test-big-shard2',
2169
- 'cargo-test-big-shard3',
2170
- 'cargo-test-big-exceptions-shard1',
2171
- 'cargo-test-big-exceptions-shard2',
2172
- 'cargo-test-big-exceptions-shard3',
2173
- 'cargo-test-small',
2174
- ]);
2175
- for (const name of [
2176
- 'cargo-test-big-shard1',
2177
- 'cargo-test-big-shard2',
2178
- 'cargo-test-big-shard3',
2179
- 'cargo-test-big-exceptions-shard1',
2180
- 'cargo-test-big-exceptions-shard2',
2181
- 'cargo-test-big-exceptions-shard3',
2182
- 'cargo-test-small',
2183
- ]) {
2184
- expect(targets[name]?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
2185
- }
2186
- // Pieces of one crate share its inputs: they are one suite, split only to
2187
- // fit the bound, so any change to the crate invalidates all of them.
2188
- expect(targets['cargo-test-big-shard2']?.inputs).toEqual(targets['cargo-test-big-shard1']?.inputs);
2189
- expect(targets['cargo-test-big-exceptions-shard1']?.inputs).toEqual(targets['cargo-test-big-shard1']?.inputs);
2190
- // Exceptional pieces fan out like the ordinary ones: nothing is exclusive.
2191
- expectNoSchedulerThrottle(targets);
2192
- } finally {
2193
- await workspace.cleanup();
2194
- }
2195
- });
2196
-
2197
- it('runs the serial test group once, unpartitioned, and excludes its tests from every crate piece on macOS', async () => {
2198
- const workspace = await createWorkspace();
2199
- try {
2200
- await workspace.write('packages/rusty/package.json', '{"name":"rusty"}\n');
2201
- await workspace.write('packages/rusty/Cargo.toml', '[workspace]\nmembers = ["crates/big", "crates/small"]\n');
2202
- await workspace.write(
2203
- 'packages/rusty/crates/big/Cargo.toml',
2204
- '[package]\nname = "big"\n\n[package.metadata.smoothbricks.test]\nshards = 3\n',
2205
- );
2206
- await workspace.write('packages/rusty/crates/small/Cargo.toml', '[package]\nname = "small"\n');
2207
- await workspace.write(
2208
- 'packages/rusty/.config/nextest.toml',
2209
- [
2210
- '[test-groups.real-apfs]',
2211
- 'max-threads = 1',
2212
- '',
2213
- '[[profile.default.overrides]]',
2214
- "filter = 'test(/real_apfs_/)'",
2215
- `platform = 'cfg(target_os="macos")'`,
2216
- "test-group = 'real-apfs'",
2217
- '',
2218
- ].join('\n'),
2219
- );
2220
-
2221
- const macos = await inferProjectTargets(
2222
- workspace,
2223
- 'packages/rusty/package.json',
2224
- createNodesV2ForPlatform('darwin', 'arm64'),
2225
- );
2226
- const serial = '(test(/real_apfs_/))';
2227
- const group = macos['cargo-test-group-real-apfs'];
2228
- // One runner for the workspace, owned by the cargo root beside the archive it executes: a progress bound and no
2229
- // ceiling like every test target, one CPU token, no partition and no thread flag. A filter that selects
2230
- // nothing fails the run.
2231
- expect(group?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
2232
- expect(group?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
2233
- expect(String(group?.options?.command)).toContain('nextest run ');
2234
- expect(String(group?.options?.command)).toContain(
2235
- `-E '${serial}' --no-fail-fast --no-tests=fail --user-config-file none`,
2236
- );
2237
- expect(group?.options).not.toHaveProperty('timeoutMs');
2238
- expect(group?.options?.idleTimeoutMs).toBe(BOUNDED_TEST_IDLE_TIMEOUT_MS);
2239
- expect(group?.options?.killAfterMs).toBe(BOUNDED_TEST_KILL_AFTER_MS);
2240
- expect(group?.options?.parallelism).toBe(1);
2241
- expect(group?.inputs).toContain('{workspaceRoot}/packages/rusty/.config/nextest.toml');
2242
- expect(JSON.stringify(group?.inputs)).toContain('nextest-code-bound.ts');
2243
- expect(JSON.stringify(macos['cargo-test-small']?.inputs)).not.toContain('nextest-code-bound.ts');
2244
- expect(String(group?.options?.command)).not.toMatch(/--partition|test-threads|max-fail/);
2245
-
2246
- // Every crate piece excludes the group's tests, so each test is selected by exactly one target.
2247
- const exceptional = exceptionalTestFilter(fileURLToPath(new URL('../nextest.toml', import.meta.url)));
2248
- if (exceptional === null) {
2249
- throw new Error('nextest.toml declares no overrides; this test asserts the pin that protects them');
2250
- }
2251
- expect(macos['cargo-test-small']?.options?.command).toContain(
2252
- `-E 'package(small) and not ((test(/real_apfs_/)))' --no-fail-fast --no-tests=pass`,
2253
- );
2254
- for (const index of [1, 2, 3]) {
2255
- expect(macos[`cargo-test-big-shard${index}`]?.options?.command).toContain(
2256
- `-E 'package(big) and not (${exceptional}) and not ((test(/real_apfs_/)))' --partition hash:${index}/3 --no-fail-fast --no-tests=pass`,
2257
- );
2258
- expect(macos[`cargo-test-big-exceptions-shard${index}`]?.options?.command).toContain(
2259
- `-E 'package(big) and (${exceptional}) and not ((test(/real_apfs_/)))' --partition hash:${index}/3 --no-fail-fast --no-tests=pass`,
2260
- );
2261
- }
2262
- // `cargo-test` and `test` are the ordinary suite alone: neither infers an edge to the group.
2263
- expect(macos['cargo-test']?.dependsOn).not.toContain('cargo-test-group-real-apfs');
2264
- expect(macos.test?.dependsOn).toEqual(['cargo-test']);
2265
-
2266
- // Off macOS nextest applies the group nowhere, so it is not inferred and no piece excludes its tests.
2267
- const linux = await inferProjectTargets(
2268
- workspace,
2269
- 'packages/rusty/package.json',
2270
- createNodesV2ForPlatform('linux', 'x64'),
2271
- );
2272
- expect(linux['cargo-test-group-real-apfs']).toBeUndefined();
2273
- expect(linux['cargo-test-small']?.options?.command).toContain(
2274
- `-E 'package(small)' --no-fail-fast --no-tests=pass`,
2275
- );
2276
- expect(linux['cargo-test']?.dependsOn).not.toContain('cargo-test-group-real-apfs');
2277
- expect(linux.test?.dependsOn).toEqual(['cargo-test']);
2278
- } finally {
2279
- await workspace.cleanup();
2280
- }
2281
- });
2282
-
2283
- it("scopes each serial group's runner inputs to its packages and their closure, and keeps an unscoped group workspace-wide", async () => {
2284
- const workspace = await createWorkspace();
2285
- try {
2286
- await writeApfsSplitFixture(workspace, [
2287
- ...APFS_SPLIT_GROUPS,
2288
- '[test-groups.wide]',
2289
- 'max-threads = 1',
2290
- '',
2291
- ...serialOverride('test(/wide_/)', 'wide'),
2292
- ]);
2293
- const root = (await inferApfsSplit(workspace)).get('.') ?? {};
2294
- const device = root['cargo-test-group-real-apfs'];
2295
- const host = root['cargo-test-group-real-apfs-host'];
2296
- const wide = root['cargo-test-group-wide'];
2297
-
2298
- // A group scoped to packages hashes those crates and every crate they link, and no other.
2299
- expect(hashedCrates(device)).toEqual(['cowshed-apfs', 'cowshed-apfs-tests', 'cowshed-os']);
2300
- expect(hashedCrates(host)).toEqual(['cowshed-apfs', 'cowshed-cli', 'cowshed-core', 'cowshed-os']);
2301
- // A filter scoped to no package keeps every member's tree, as the archive hashes them.
2302
- expect(hashedCrates(wide)).toEqual([
2303
- 'cowshed-apfs',
2304
- 'cowshed-apfs-tests',
2305
- 'cowshed-cli',
2306
- 'cowshed-core',
2307
- 'cowshed-os',
2308
- 'lmao-core',
2309
- ]);
2310
-
2311
- // The proof as the three cases it makes. An unrelated crate reruns neither scoped group. A scenario
2312
- // edit reruns the device group alone: the scenarios are a crate of their own that no host crate
2313
- // depends on. A change to the production substrate, or to what it links, reruns both, because the
2314
- // host crates link it too. Nothing here excludes a tests tree, and the test support every real-image
2315
- // binary compiles in stays hashed for both groups.
2316
- const hashedBy = (path: string) => ({
2317
- device: hashes(device, path),
2318
- host: hashes(host, path),
2319
- wide: hashes(wide, path),
2320
- });
2321
- expect(hashedBy('packages/lmao/crates/lmao-core/src/lib.rs')).toEqual({ device: false, host: false, wide: true });
2322
- expect(hashedBy('packages/cowshed/crates/cowshed-apfs-tests/src/tests.rs')).toEqual({
2323
- device: true,
2324
- host: false,
2325
- wide: true,
2326
- });
2327
- expect(hashedBy('packages/cowshed/crates/cowshed-core/src/lib.rs')).toEqual({
2328
- device: false,
2329
- host: true,
2330
- wide: true,
2331
- });
2332
- expect(hashedBy('packages/cowshed/crates/cowshed-cli/src/lib.rs')).toEqual({
2333
- device: false,
2334
- host: true,
2335
- wide: true,
2336
- });
2337
- for (const shared of [
2338
- 'packages/cowshed/crates/cowshed-apfs/src/lib.rs',
2339
- 'packages/cowshed/crates/cowshed-apfs/tests/support/blank_image.rs',
2340
- 'packages/cowshed/crates/cowshed-os/src/lib.rs',
2341
- ]) {
2342
- expect(hashedBy(shared), shared).toEqual({ device: true, host: true, wide: true });
2343
- }
2344
- for (const group of [device, host]) {
2345
- const exclusions = (group?.inputs ?? []).filter(
2346
- (input): input is string => typeof input === 'string' && input.startsWith('!'),
2347
- );
2348
- expect(exclusions.filter((input) => /\btests?\b/.test(input))).toEqual([]);
2349
- }
2350
-
2351
- // Every scoped group still hashes every member manifest, the repository's nextest config and the
2352
- // run-wrapper its tests are bounded by: those decide a verdict whichever crates it selects.
2353
- for (const group of [device, host, wide]) {
2354
- expect(group?.inputs).toContain('{workspaceRoot}/packages/lmao/crates/lmao-core/Cargo.toml');
2355
- expect(group?.inputs).toContain('{workspaceRoot}/.config/nextest.toml');
2356
- expect(JSON.stringify(group?.inputs)).toContain('nextest-code-bound.ts');
2357
- }
2358
- } finally {
2359
- await workspace.cleanup();
2360
- }
2361
- });
2362
-
2363
- it('refuses a serial group scoped to a package that is not a member of the Cargo workspace', async () => {
2364
- const workspace = await createWorkspace();
2365
- try {
2366
- await writeApfsSplitFixture(workspace, [
2367
- '[test-groups.real-apfs]',
2368
- 'max-threads = 1',
2369
- '',
2370
- ...serialOverride('package(cowshed-missing) and test(/real_apfs_/)', 'real-apfs'),
2371
- ]);
2372
- // Nx wraps a createNodes throw in AggregateCreateNodesError, so the reason is in the nested error.
2373
- const failure = await inferApfsSplit(workspace).then(
2374
- () => undefined,
2375
- (error: unknown) => error,
2376
- );
2377
- if (!(failure instanceof AggregateCreateNodesError)) {
2378
- throw new Error(`expected AggregateCreateNodesError, got ${String(failure)}`);
2379
- }
2380
- expect(failure.errors[0]?.[1]?.message).toMatch(
2381
- /test-group "real-apfs" selects package\(cowshed-missing\), which is not a member of the Cargo workspace/,
2382
- );
2383
- } finally {
2384
- await workspace.cleanup();
2385
- }
2386
- });
2387
-
2388
- it('keeps cargo-test and test to the ordinary suite, so no gate of the root or a member reaches a serial group', async () => {
2389
- const workspace = await createWorkspace();
2390
- try {
2391
- await writeApfsSplitFixture(workspace, APFS_SPLIT_GROUPS);
2392
- const macos = await inferApfsSplit(workspace);
2393
- const root = macos.get('.') ?? {};
2394
- const cowshed = macos.get('packages/cowshed') ?? {};
2395
- const lmao = macos.get('packages/lmao') ?? {};
2396
-
2397
- // `cargo-test` is the ordinary suite alone, whichever project owns the aggregate.
2398
- expect(root['cargo-test']?.dependsOn).toEqual([
2399
- { projects: ['cowshed'], target: 'cargo-test-cowshed-apfs' },
2400
- { projects: ['cowshed'], target: 'cargo-test-cowshed-apfs-tests' },
2401
- { projects: ['cowshed'], target: 'cargo-test-cowshed-cli' },
2402
- { projects: ['cowshed'], target: 'cargo-test-cowshed-core' },
2403
- { projects: ['cowshed'], target: 'cargo-test-cowshed-os' },
2404
- { projects: ['lmao'], target: 'cargo-test-lmao-core' },
2405
- ]);
2406
- expect(cowshed['cargo-test']?.dependsOn).toEqual([
2407
- 'cargo-test-cowshed-apfs',
2408
- 'cargo-test-cowshed-apfs-tests',
2409
- 'cargo-test-cowshed-cli',
2410
- 'cargo-test-cowshed-core',
2411
- 'cargo-test-cowshed-os',
2412
- ]);
2413
- expect(lmao['cargo-test']?.dependsOn).toEqual(['cargo-test-lmao-core']);
2414
-
2415
- // Ordinary test inference excludes serial groups at both the root and every member. Explicit repository
2416
- // host aggregates, not inference, own those edges.
2417
- for (const targets of [root, cowshed, lmao]) {
2418
- expect(targets.test?.dependsOn).toEqual(['cargo-test']);
2419
- }
2420
-
2421
- // Inference orders nothing between the groups: that edge is the repository's explicit config.
2422
- for (const name of ['cargo-test-group-real-apfs', 'cargo-test-group-real-apfs-host']) {
2423
- expect(root[name]?.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive']);
2424
- }
2425
-
2426
- // Every crate piece, scoped to a package the groups hold or not, excludes both groups' tests.
2427
- const exclusion =
2428
- 'not ((package(cowshed-apfs-tests) and test(/real_apfs_/)) or ' +
2429
- '(package(cowshed-core) and (test(/real_apfs_/) or binary(apfs_native_macos))) or ' +
2430
- '(package(cowshed-cli) and test(/real_apfs_/)))';
2431
- const pieces: ReadonlyArray<readonly [TargetConfiguration | undefined, string]> = [
2432
- [cowshed['cargo-test-cowshed-apfs'], 'cowshed-apfs'],
2433
- [cowshed['cargo-test-cowshed-apfs-tests'], 'cowshed-apfs-tests'],
2434
- [lmao['cargo-test-lmao-core'], 'lmao-core'],
2435
- ];
2436
- for (const [piece, crate] of pieces) {
2437
- expect(piece?.options?.command, crate).toContain(
2438
- `-E 'package(${crate}) and ${exclusion}' --no-fail-fast --no-tests=pass`,
2439
- );
2440
- }
2441
-
2442
- // Off macOS the groups are not inferred at all, and the gate is the same ordinary suite.
2443
- const linux = await inferApfsSplit(workspace, createNodesV2ForPlatform('linux', 'x64'));
2444
- expect(linux.get('.')?.test?.dependsOn).toEqual(['cargo-test']);
2445
- expect(linux.get('packages/cowshed')?.test?.dependsOn).toEqual(['cargo-test']);
2446
- expect(linux.get('.')?.['cargo-test-group-real-apfs-host']).toBeUndefined();
2447
- } finally {
2448
- await workspace.cleanup();
2449
- }
2450
- });
2451
-
2452
- it('runs the host group after the device group through the explicit targetDefaults edge, and no test gate runs either', async () => {
2453
- const workspace = await createWorkspace();
2454
- try {
2455
- await writeApfsSplitFixture(workspace, APFS_SPLIT_GROUPS);
2456
- const macos = await inferApfsSplit(workspace);
2457
- const rootProject = '@fixture/codebase';
2458
- const rootTargets = macos.get('.') ?? {};
2459
-
2460
- // The edge as the repository's nx.json states it. Nx expands `...` to the inferred list, so the
2461
- // archive and the locked fetch stay ahead of the host group beside the device group.
2462
- const nxJson = {
2463
- targetDefaults: { 'cargo-test-group-real-apfs-host': { dependsOn: ['...', 'cargo-test-group-real-apfs'] } },
2464
- };
2465
- let host = rootTargets['cargo-test-group-real-apfs-host'] ?? {};
2466
- for (const [, , result] of createTargetDefaultsResults(
2467
- { '.': { root: '.', targets: rootTargets } },
2468
- {},
2469
- nxJson,
2470
- )) {
2471
- const target = result.projects?.['.']?.targets?.['cargo-test-group-real-apfs-host'];
2472
- if (target) host = mergeTargetConfigurations(target, host);
2473
- }
2474
- expect(host.dependsOn).toEqual(['cargo-fetch', 'cargo-test-archive', 'cargo-test-group-real-apfs']);
2475
-
2476
- const nodes: Record<string, ProjectGraphProjectNode> = {
2477
- [rootProject]: {
2478
- name: rootProject,
2479
- type: 'app',
2480
- data: { root: '.', targets: { ...rootTargets, 'cargo-test-group-real-apfs-host': host } },
2481
- },
2482
- cowshed: {
2483
- name: 'cowshed',
2484
- type: 'lib',
2485
- data: { root: 'packages/cowshed', targets: macos.get('packages/cowshed') ?? {} },
2486
- },
2487
- lmao: {
2488
- name: 'lmao',
2489
- type: 'lib',
2490
- data: { root: 'packages/lmao', targets: macos.get('packages/lmao') ?? {} },
2491
- },
2492
- };
2493
- const graph: ProjectGraph = { nodes, dependencies: { [rootProject]: [], cowshed: [], lmao: [] } };
2494
- const task = (project: string, target: string): string => `${project}:${target}`;
2495
- // Every task `from` waits on, directly or through the tasks it waits on.
2496
- const reached = (dependencies: Record<string, string[]>, from: string): string[] => {
2497
- const seen = new Set<string>();
2498
- const pending = [from];
2499
- while (pending.length > 0) {
2500
- const next = pending.pop();
2501
- if (next === undefined || seen.has(next)) continue;
2502
- seen.add(next);
2503
- pending.push(...(dependencies[next] ?? []));
2504
- }
2505
- return [...seen];
2506
- };
2507
- const groupsReached = (dependencies: Record<string, string[]>, from: string): string[] =>
2508
- reached(dependencies, from).filter((id) => id.includes(':cargo-test-group-'));
2509
- const device = task(rootProject, 'cargo-test-group-real-apfs');
2510
- const hosted = task(rootProject, 'cargo-test-group-real-apfs-host');
2511
-
2512
- // The task graph `nx run-many -t test` runs reaches neither group, from the root or from a member.
2513
- for (const project of [rootProject, 'cowshed']) {
2514
- const gate = createTaskGraph(graph, {}, [project], ['test'], undefined, {});
2515
- expect(groupsReached(gate.dependencies, task(project, 'test'))).toEqual([]);
2516
- }
2517
-
2518
- // When a run selects both groups, the host starts only once the device group is done, so two real-image
2519
- // runners never overlap, and the device group waits on no other group.
2520
- const named = createTaskGraph(
2521
- graph,
2522
- {},
2523
- [rootProject],
2524
- ['test', 'cargo-test-group-real-apfs', 'cargo-test-group-real-apfs-host'],
2525
- undefined,
2526
- {},
2527
- );
2528
- expect(named.dependencies[hosted]).toContain(device);
2529
- expect(groupsReached(named.dependencies, device)).toEqual([device]);
2530
- expect(groupsReached(named.dependencies, task(rootProject, 'test'))).toEqual([]);
2531
- } finally {
2532
- await workspace.cleanup();
2533
- }
2534
- });
2535
-
2536
- it('rejects a shard count that cannot describe a partition', async () => {
2537
- const workspace = await createWorkspace();
2538
- try {
2539
- await workspace.write('packages/rusty/package.json', '{"name":"rusty"}\n');
2540
- await workspace.write('packages/rusty/Cargo.toml', '[workspace]\nmembers = ["crates/big"]\n');
2541
- await workspace.write(
2542
- 'packages/rusty/crates/big/Cargo.toml',
2543
- '[package]\nname = "big"\n\n[package.metadata.smoothbricks.test]\nshards = 0\n',
2544
- );
2545
-
2546
- // Nx wraps a createNodes throw in AggregateCreateNodesError, so the
2547
- // reason a maintainer needs is in the nested error, not the top message.
2548
- const failure = await inferProjectTargets(workspace, 'packages/rusty/package.json').then(
2549
- () => undefined,
2550
- (error: unknown) => error,
2551
- );
2552
- if (!(failure instanceof AggregateCreateNodesError)) {
2553
- throw new Error(`expected AggregateCreateNodesError, got ${String(failure)}`);
2554
- }
2555
- expect(failure.errors[0]?.[1]?.message).toMatch(/smoothbricks\.test\.shards must be an integer >= 1, got 0/);
2556
- } finally {
2557
- await workspace.cleanup();
2558
- }
2559
- });
2560
-
2561
- it('lets explicit nx.targets suppress output and aggregate inference, and skips non-workspace Cargo.toml', async () => {
2562
- const workspace = await createWorkspace();
2563
- try {
2564
- await workspace.write(
2565
- 'packages/custom/package.json',
2566
- '{"name":"custom","nx":{"targets":{"cargo-wasm":{"options":{"command":"custom"}},"test":{}}}}\n',
2567
- );
2568
- await workspace.write('packages/custom/Cargo.toml', '[workspace]\nmembers = ["crates/x-wasm"]\n');
2569
- await workspace.write(
2570
- 'packages/custom/crates/x-wasm/Cargo.toml',
2571
- '[package]\nname = "x-wasm"\n\n[lib]\ncrate-type = ["cdylib"]\n',
2572
- );
2573
-
2574
- const targets = await inferProjectTargets(workspace, 'packages/custom/package.json');
2575
- expect(targets['cargo-wasm']).toBeUndefined();
2576
- expect(targets.test).toEqual({ dependsOn: ['^build', 'build'] });
2577
- expect(targets['cargo-test']).toBeDefined();
2578
-
2579
- // A member crate's own Cargo.toml (no [workspace]) infers nothing.
2580
- await workspace.write('packages/member/package.json', '{"name":"member"}\n');
2581
- await workspace.write('packages/member/Cargo.toml', '[package]\nname = "member"\n');
2582
- const memberTargets = await inferProjectTargets(workspace, 'packages/member/package.json');
2583
- expect(memberTargets).toEqual({});
2584
- } finally {
2585
- await workspace.cleanup();
2586
- }
2587
- });
2588
-
2589
- it('gives a declared TypeScript test the ^build/build dependsOn base targetDefaults must not supply', async () => {
2590
- const workspace = await createWorkspace();
2591
- try {
2592
- await workspace.write(
2593
- 'packages/money/package.json',
2594
- JSON.stringify({
2595
- name: 'money',
2596
- nx: {
2597
- targets: {
2598
- test: {
2599
- executor: '@smoothbricks/nx-plugin:bounded-exec',
2600
- options: { command: 'bun test', cwd: '{projectRoot}' },
2601
- },
2602
- },
2603
- },
2604
- }),
2605
- );
2606
- await workspace.write('packages/money/tsconfig.lib.json', '{}\n');
2607
-
2608
- const targets = await inferProjectTargets(workspace, 'packages/money/package.json');
2609
- expect(targets.test).toEqual({ dependsOn: ['^build', 'build'] });
2610
- expect(targets['cargo-test']).toBeUndefined();
2611
- } finally {
2612
- await workspace.cleanup();
2613
- }
2614
- });
2615
-
2616
- it('keeps inferring a cargo target the package partially declares', async () => {
2617
- const workspace = await createWorkspace();
2618
- const declared: Record<string, TargetConfiguration> = {
2619
- // One added edge per target. Everything that makes each target do its job
2620
- // — executor, options, inputs, cache — must survive the declaration
2621
- // instead of being replaced wholesale by it.
2622
- 'cargo-test': { dependsOn: ['cargo-test-ferris-core', 'cargo-wasm'] },
2623
- 'cargo-test-compile': { dependsOn: ['cargo-wasm'] },
2624
- 'cargo-lint': { inputs: ['{projectRoot}/clippy.toml'] },
2625
- mutation: { options: { command: 'cargo mutants --in-diff' } },
2626
- bench: { cache: true },
2627
- };
2628
- try {
2629
- await workspace.write(
2630
- 'packages/ferris/package.json',
2631
- JSON.stringify({ name: 'ferris', nx: { targets: declared } }),
2632
- );
2633
- await workspace.write('packages/ferris/Cargo.toml', '[workspace]\nmembers = ["crates/ferris-core"]\n');
2634
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
2635
-
2636
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
2637
-
2638
- // The aggregate stays a no-op that reaches bounded crate runners. A
2639
- // partial declaration must keep that inferred base, not erase the chain.
2640
- expect(targets['cargo-test']?.executor).toBe('nx:noop');
2641
- expect(targets['cargo-test-ferris-core']?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
2642
- expect(targets['cargo-test-compile']?.executor).toBe('nx:run-commands');
2643
- expect(targets['cargo-lint']?.options).toMatchObject({
2644
- commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
2645
- });
2646
-
2647
- const cargoTest = resolveDeclaredOverInferred(targets, declared, 'cargo-test');
2648
- expect(cargoTest?.executor).toBe('nx:noop');
2649
- expect(cargoTest?.cache).toBe(true);
2650
- expect(cargoTest?.dependsOn).toEqual(['cargo-test-ferris-core', 'cargo-wasm']);
2651
- expect(cargoTest?.options).toBeUndefined();
2652
- expect(targets['cargo-test-ferris-core']?.options?.command).toContain("-E 'package(ferris-core)'");
2653
- expect(targets['cargo-test-ferris-core']?.options?.idleTimeoutMs).toBe(BOUNDED_TEST_IDLE_TIMEOUT_MS);
2654
-
2655
- const cargoTestCompile = resolveDeclaredOverInferred(targets, declared, 'cargo-test-compile');
2656
- expect(cargoTestCompile?.executor).toBe('nx:run-commands');
2657
- // A replacing array drops every inferred edge, cargo-fetch included: the
2658
- // package now owns ordering the locked fetch ahead of its frozen compile.
2659
- expect(cargoTestCompile?.dependsOn).toEqual(['cargo-wasm']);
2660
- expect(targets['cargo-test-compile']?.dependsOn).toEqual(['cargo-fetch']);
2661
- expect(cargoTestCompile?.options).toMatchObject({
2662
- command: 'cargo --frozen test --workspace --no-run',
2663
- });
2664
-
2665
- // A declared array replaces the inferred one; the command it guards stays.
2666
- const cargoLint = resolveDeclaredOverInferred(targets, declared, 'cargo-lint');
2667
- expect(cargoLint?.inputs).toEqual(['{projectRoot}/clippy.toml']);
2668
- expect(cargoLint?.options).toMatchObject({
2669
- commands: ['cargo fmt --all --check', CARGO_LINT_CLIPPY_COMMAND],
2670
- });
2671
-
2672
- // `options` merges key by key, so a declared command overrides only itself.
2673
- const mutation = resolveDeclaredOverInferred(targets, declared, 'mutation');
2674
- expect(mutation?.options).toEqual({
2675
- command: 'cargo mutants --in-diff',
2676
- cwd: 'packages/ferris',
2677
- timeoutMs: 6 * 60 * 60 * 1000,
2678
- });
2679
- expect(mutation?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
2680
- expect(mutation?.cache).toBe(false);
2681
-
2682
- const bench = resolveDeclaredOverInferred(targets, declared, 'bench');
2683
- expect(bench?.cache).toBe(true);
2684
- expect(bench?.options).toMatchObject({ command: 'cargo --frozen bench --workspace' });
2685
- } finally {
2686
- await workspace.cleanup();
2687
- }
2688
- });
2689
-
2690
- it('lets a declared dependsOn spread expand the inferred cargo chain', async () => {
2691
- const workspace = await createWorkspace();
2692
- // Additive intent has Nx's own spelling: `'...'` expands the inferred list
2693
- // at the token, so an added edge keeps the inferred cargo edges.
2694
- const declared: Record<string, TargetConfiguration> = {
2695
- 'cargo-test': { dependsOn: ['...', 'cargo-wasm'] },
2696
- };
2697
- try {
2698
- await workspace.write(
2699
- 'packages/ferris/package.json',
2700
- JSON.stringify({ name: 'ferris', nx: { targets: declared } }),
2701
- );
2702
- await workspace.write('packages/ferris/Cargo.toml', '[workspace]\nmembers = ["crates/ferris-core"]\n');
2703
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
2704
-
2705
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
2706
-
2707
- // The spread expands exactly once, against the single inferred base this
2708
- // plugin emits — re-implementing the overlay here would double it.
2709
- const cargoTest = resolveDeclaredOverInferred(targets, declared, 'cargo-test');
2710
- expect(cargoTest?.dependsOn).toEqual(['cargo-test-ferris-core', 'cargo-wasm']);
2711
- expect(cargoTest?.executor).toBe('nx:noop');
2712
- } finally {
2713
- await workspace.cleanup();
2714
- }
2715
- });
2716
-
2717
- it('gives a private wrangler project a deploy that runs the stage CLI, uncached, behind its build half', async () => {
2718
- const workspace = await createWorkspace();
2719
- try {
2720
- await workspace.write('packages/site/package.json', '{"name":"site","private":true}\n');
2721
- await workspace.write('packages/site/wrangler.toml', 'name = "site"\n');
2722
- const targets = await inferProjectTargets(workspace, 'packages/site/package.json');
2723
-
2724
- // One target taking a stage, never a configuration per stage: pull-request stages are
2725
- // `prN` for unbounded N, so `--configuration` could not name the stage that matters most.
2726
- expect(targets.deploy?.options).toEqual({
2727
- command: 'smoo wrangler deploy-stage --stage {args.stage}',
2728
- cwd: 'packages/site',
2729
- });
2730
- // A cache hit on deploy would mean "we once uploaded this hash", which a rollback falsifies
2731
- // silently; the step has to run and read live state instead.
2732
- expect(targets.deploy?.cache).toBe(false);
2733
- expect(targets.deploy?.outputs).toEqual([]);
2734
- // No build half of any kind here, so no edge is claimed: wrangler bundles its own
2735
- // TypeScript, so a worker with neither `build` nor `deploy-build` is legitimate.
2736
- expect(targets.deploy?.dependsOn).toBeUndefined();
2737
- } finally {
2738
- await workspace.cleanup();
2739
- }
2740
- });
2741
-
2742
- it('infers no deploy for a PUBLISHED package whose wrangler manifest documents a binding', async () => {
2743
- const workspace = await createWorkspace();
2744
- try {
2745
- // The shape that regressed a consumer: a library published to npm that ships a wrangler
2746
- // manifest so consumers can declare the Durable Object binding it implements. Structurally
2747
- // identical to a worker's, so only the manifest's own `private` flag tells them apart.
2748
- await workspace.write(
2749
- 'packages/acme-cloudflare/package.json',
2750
- '{"name":"@acme/cloudflare","nx":{"tags":["npm:private"]}}\n',
2751
- );
2752
- await workspace.write(
2753
- 'packages/acme-cloudflare/wrangler.toml',
2754
- '# Wrangler configuration for @acme/cloudflare Durable Object\nname = "acme-cloudflare"\nmain = "src/index.ts"\ncompatibility_date = "2025-01-01"\n',
2755
- );
2756
- const targets = await inferProjectTargets(workspace, 'packages/acme-cloudflare/package.json');
2757
-
2758
- expect(Object.keys(targets)).not.toContain('deploy');
2759
- } finally {
2760
- await workspace.cleanup();
2761
- }
2762
- });
2763
-
2764
- it('points an inferred deploy at the declared deploy-build, and caches that half', async () => {
2765
- const workspace = await createWorkspace();
2766
- const declared = {
2767
- 'deploy-build': { executor: 'nx:run-commands', options: { command: 'bun tooling/build-site.ts' } },
2768
- };
2769
- try {
2770
- await workspace.write(
2771
- 'packages/site/package.json',
2772
- JSON.stringify({ name: 'site', private: true, nx: { targets: declared } }),
2773
- );
2774
- await workspace.write('packages/site/wrangler.toml', 'name = "site"\n');
2775
- const targets = await inferProjectTargets(workspace, 'packages/site/package.json');
2776
-
2777
- expect(targets.deploy?.dependsOn).toEqual(['deploy-build']);
2778
- // Only the project knows what building it means, so the plugin supplies the policy for
2779
- // that half and nothing else.
2780
- expect(resolveDeclaredOverInferred(targets, declared, 'deploy-build')?.cache).toBe(true);
2781
- expect(resolveDeclaredOverInferred(targets, declared, 'deploy-build')?.options).toEqual({
2782
- command: 'bun tooling/build-site.ts',
2783
- });
2784
- } finally {
2785
- await workspace.cleanup();
2786
- }
2787
- });
2788
-
2789
- it('falls back to the aggregate build when a wrangler project emits one', async () => {
2790
- const workspace = await createWorkspace();
2791
- try {
2792
- await workspace.write('packages/site/package.json', '{"name":"site","private":true}\n');
2793
- await workspace.write('packages/site/wrangler.toml', 'name = "site"\n');
2794
- // tsconfig.lib.json is what puts an emitting target, and so the `build` aggregate, on a project.
2795
- await workspace.write('packages/site/tsconfig.lib.json', '{}\n');
2796
- const targets = await inferProjectTargets(workspace, 'packages/site/package.json');
2797
-
2798
- expect(targets.build).toBeDefined();
2799
- expect(targets.deploy?.dependsOn).toEqual(['build']);
2800
- } finally {
2801
- await workspace.cleanup();
2802
- }
2803
- });
2804
-
2805
- it('lets a dependsOn-only declaration add a cross-project edge without restating the command', async () => {
2806
- const workspace = await createWorkspace();
2807
- // The whole point of inferring: ordering is expressed in Nx's own vocabulary, and the
2808
- // consumer never retypes the command, cwd, cache or outputs to get it.
2809
- const declared: Record<string, TargetConfiguration> = {
2810
- deploy: { dependsOn: ['...', { projects: ['backend'], target: 'deploy', params: 'forward' }] },
2811
- };
2812
- try {
2813
- await workspace.write(
2814
- 'packages/site/package.json',
2815
- JSON.stringify({ name: 'site', private: true, nx: { targets: declared } }),
2816
- );
2817
- await workspace.write('packages/site/wrangler.toml', 'name = "site"\n');
2818
- await workspace.write('packages/site/tsconfig.lib.json', '{}\n');
2819
- const targets = await inferProjectTargets(workspace, 'packages/site/package.json');
2820
-
2821
- const deploy = resolveDeclaredOverInferred(targets, declared, 'deploy');
2822
- // `...` expands to the inferred list at its position, so the inferred build edge survives
2823
- // beside the declared one.
2824
- expect(deploy?.dependsOn).toEqual(['build', { projects: ['backend'], target: 'deploy', params: 'forward' }]);
2825
- expect(deploy?.options).toEqual({
2826
- command: 'smoo wrangler deploy-stage --stage {args.stage}',
2827
- cwd: 'packages/site',
2828
- });
2829
- expect(deploy?.cache).toBe(false);
2830
- expect(deploy?.outputs).toEqual([]);
2831
- } finally {
2832
- await workspace.cleanup();
2833
- }
2834
- });
2835
-
2836
- it('infers no deploy for a project with no wrangler manifest', async () => {
2837
- const workspace = await createWorkspace();
2838
- try {
2839
- await workspace.write('packages/lib/package.json', '{"name":"plain-lib"}\n');
2840
- const targets = await inferProjectTargets(workspace, 'packages/lib/package.json');
2841
-
2842
- expect(Object.keys(targets)).not.toContain('deploy');
2843
- expect(Object.keys(targets)).not.toContain('deploy-build');
2844
- } finally {
2845
- await workspace.cleanup();
2846
- }
2847
- });
2848
-
2849
- it('orders a three-project chain of INFERRED deploys through one run-many', async () => {
2850
- const workspace = await createWorkspace();
2851
- // c is deepest: a's deploy calls into b's, b's calls into c's. No project declares a deploy
2852
- // target — each only has a wrangler manifest and, where it needs ordering, the edge. Nothing
2853
- // here says "round one" or "round two", and no project knows the depth.
2854
- const chain: Record<string, string[]> = { a: ['b:deploy'], b: ['c:deploy'], c: [] };
2855
- try {
2856
- const nodes: Record<string, ProjectGraphProjectNode> = {};
2857
- for (const [name, edges] of Object.entries(chain)) {
2858
- const declared: Record<string, TargetConfiguration> =
2859
- edges.length > 0 ? { deploy: { dependsOn: ['...', ...edges] } } : {};
2860
- await workspace.write(`packages/${name}/wrangler.toml`, `name = "${name}"\n`);
2861
- await workspace.write(
2862
- `packages/${name}/package.json`,
2863
- JSON.stringify({ name, private: true, nx: { targets: declared } }),
2864
- );
2865
- const targets = await inferProjectTargets(workspace, `packages/${name}/package.json`);
2866
- const deploy = resolveDeclaredOverInferred(targets, declared, 'deploy');
2867
- // The edge rides on the inferred target: its executor and command still carry the run.
2868
- expect(deploy?.executor).toBe('nx:run-commands');
2869
- expect(deploy?.options?.command).toBe('smoo wrangler deploy-stage --stage {args.stage}');
2870
- if (deploy === undefined) throw new Error(`${name} infers no deploy`);
2871
- nodes[name] = { name, type: 'app', data: { root: `packages/${name}`, targets: { ...targets, deploy } } };
2872
- }
2873
- const graph: ProjectGraph = { nodes, dependencies: { a: [], b: [], c: [] } };
2874
-
2875
- // The task graph `nx run-many -t deploy --projects=a,b,c` runs: Nx starts a task only once
2876
- // every task it depends on has finished, so this is the order.
2877
- const tasks = createTaskGraph(graph, {}, ['a', 'b', 'c'], ['deploy'], undefined, { stage: 'staging' });
2878
- expect(tasks.dependencies).toEqual({ 'a:deploy': ['b:deploy'], 'b:deploy': ['c:deploy'], 'c:deploy': [] });
2879
- expect(tasks.roots).toEqual(['c:deploy']);
2880
- } finally {
2881
- await workspace.cleanup();
2882
- }
2883
- });
2884
-
2885
- it('archives a declared foreign triple beside the host archive, and runs it without building', async () => {
2886
- const workspace = await createWorkspace();
2887
- try {
2888
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
2889
- await workspace.write(
2890
- 'packages/ferris/Cargo.toml',
2891
- '[workspace]\nmembers = ["crates/ferris-core"]\n\n' +
2892
- '[workspace.metadata.smoothbricks.test]\n' +
2893
- 'cross-targets = [{ target = "aarch64-apple-darwin", cargo = "scripts/cargo-for-nextest.sh" }]\n',
2894
- );
2895
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
2896
- await workspace.write('packages/ferris/scripts/cargo-for-nextest.sh', '#!/bin/sh\nexec cargo "$@"\n');
2897
-
2898
- const targets = await inferProjectTargets(workspace, 'packages/ferris/package.json');
2899
- const archive = targets['cargo-cross-test-archive-aarch64-apple-darwin'];
2900
- const run = targets['cargo-cross-test-aarch64-apple-darwin'];
2901
-
2902
- // A distinct archive file, declared as this target's output: the host
2903
- // archive must survive a cross build and each must be cached as itself.
2904
- expect(archive?.outputs).toEqual(['{projectRoot}/.cache/nextest/archive-aarch64-apple-darwin.tar.zst']);
2905
- expect(targets['cargo-test-archive']?.outputs).toEqual(['{projectRoot}/.cache/nextest/archive.tar.zst']);
2906
- expect(archive?.cache).toBe(true);
2907
- // Everything the host archive hashes, plus the declared driver: the
2908
- // script that decides how the foreign link happens is an input of the
2909
- // bytes it produces.
2910
- for (const input of targets['cargo-test-archive']?.inputs ?? []) {
2911
- expect(archive?.inputs).toContainEqual(input);
2912
- }
2913
- expect(archive?.inputs).toContain('{projectRoot}/scripts/cargo-for-nextest.sh');
2914
- expect(archive?.options?.env).toEqual({ CARGO: 'scripts/cargo-for-nextest.sh' });
2915
- // The runner needs no driver: it never invokes cargo at all.
2916
- expect(run?.options?.env).toBeUndefined();
2917
- expect(archive?.options?.commands).toBeUndefined();
2918
- // `cargo-nextest`, not `cargo nextest`: cargo overwrites CARGO for its
2919
- // subcommands, and CARGO is the only seam a cross cargo driver has.
2920
- expect(String(archive?.options?.command)).toMatch(
2921
- /^mkdir -p \.cache\/nextest && cargo-nextest nextest archive --workspace --target aarch64-apple-darwin --frozen --archive-file \.cache\/nextest\/archive-aarch64-apple-darwin\.tar\.zst --user-config-file none --tool-config-file "smoo:\$PWD\/.*nextest\.toml"$/,
2922
- );
2923
- expect(archive?.configurations?.[RELEASE_CONFIGURATION]).toBeUndefined();
2924
- expect(run?.configurations?.[RELEASE_CONFIGURATION]).toBeUndefined();
2925
- // The archive BUILDS, so it needs the locked registry graph; the runner
2926
- // never touches cargo, so it needs nothing and depends on nothing.
2927
- expect(archive?.dependsOn).toEqual(['cargo-fetch']);
2928
- expect(run?.dependsOn).toEqual([]);
2929
- expect(String(run?.options?.command)).toMatch(
2930
- /^cargo-nextest nextest run --archive-file \.cache\/nextest\/archive-aarch64-apple-darwin\.tar\.zst --workspace-remap \. --no-tests=pass --user-config-file none --tool-config-file "smoo:\$PWD\/.*nextest\.toml"$/,
2931
- );
2932
- expect(run?.executor).toBe('@smoothbricks/nx-plugin:bounded-exec');
2933
- // Not a crate: the per-crate coverage policy reads `cargo-test-<name>`,
2934
- // so a triple must not land in that namespace, and neither target may
2935
- // join the test aggregate a host machine runs.
2936
- expect(packageNameFromCargoTestTarget('cargo-cross-test-archive-aarch64-apple-darwin')).toBeNull();
2937
- expect(packageNameFromCargoTestTarget('cargo-cross-test-aarch64-apple-darwin')).toBeNull();
2938
- expect(targets['cargo-test']?.dependsOn).toEqual(['cargo-test-ferris-core']);
2939
- expect(targets.build?.dependsOn ?? []).not.toContain('cargo-cross-test-archive-aarch64-apple-darwin');
2940
- expectNoSchedulerThrottle(targets);
2941
- } finally {
2942
- await workspace.cleanup();
2943
- }
2944
- });
2945
-
2946
- it('refuses a cross-targets declaration that cannot name a target or a file', async () => {
2947
- const workspace = await createWorkspace();
2948
- try {
2949
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
2950
- await workspace.write(
2951
- 'packages/ferris/Cargo.toml',
2952
- '[workspace]\nmembers = ["crates/ferris-core"]\n\n' +
2953
- '[workspace.metadata.smoothbricks.test]\ncross-targets = ["aarch64 apple darwin; rm -rf /"]\n',
2954
- );
2955
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
2956
-
2957
- const failure = await inferProjectTargets(workspace, 'packages/ferris/package.json').then(
2958
- () => undefined,
2959
- (error: unknown) => error,
2960
- );
2961
- if (!(failure instanceof AggregateCreateNodesError)) {
2962
- throw new Error(`expected AggregateCreateNodesError, got ${String(failure)}`);
2963
- }
2964
- expect(failure.errors[0]?.[1]?.message).toMatch(/cross-targets entries must be target triples like/);
2965
- } finally {
2966
- await workspace.cleanup();
2967
- }
2968
- });
2969
- //#endregion
2970
- });
2971
-
2972
- /**
2973
- * Target-inference fixtures declare real Cargo workspaces. Supply their empty
2974
- * Rust library and initial lock before inference, rather than relying on a
2975
- * rejected Cargo query. Explicit sources and locks, including planted failures,
2976
- * remain untouched.
2977
- */
2978
- async function prepareCargoFixture(root: string): Promise<void> {
2979
- const manifests = (await readdir(root, { recursive: true }))
2980
- .filter((path) => path === 'Cargo.toml' || path.endsWith('/Cargo.toml'))
2981
- .filter((path) => !path.split('/').some((part) => ['node_modules', 'target', '.nx'].includes(part)));
2982
- const workspaces: string[] = [];
2983
- for (const manifest of manifests) {
2984
- const path = join(root, manifest);
2985
- const contents = await readFile(path, 'utf8');
2986
- if (/^\[package\]\s*$/m.test(contents)) {
2987
- const source = join(dirname(path), 'src/lib.rs');
2988
- if (!(await Bun.file(source).exists())) {
2989
- await mkdir(dirname(source), { recursive: true });
2990
- await writeFile(source, '// Empty Cargo fixture library.\n');
2991
- }
2992
- }
2993
- if (/^\[workspace\]\s*$/m.test(contents)) workspaces.push(path);
2994
- }
2995
- for (const manifest of workspaces) {
2996
- if (await Bun.file(join(dirname(manifest), 'Cargo.lock')).exists()) continue;
2997
- const child = Bun.spawn(['cargo', 'generate-lockfile', '--offline', '--manifest-path', manifest], {
2998
- env: process.env,
2999
- cwd: root,
3000
- stdout: 'pipe',
3001
- stderr: 'pipe',
3002
- });
3003
- const [code, stdout, stderr] = await Promise.all([
3004
- child.exited,
3005
- new Response(child.stdout).text(),
3006
- new Response(child.stderr).text(),
3007
- ]);
3008
- if (code !== 0) throw new Error(`Cargo fixture ${manifest} could not lock:\n${stdout}${stderr}`);
3009
- }
3010
- }
3011
-
3012
- async function createWorkspace(parent = tmpdir()): Promise<WorkspaceFixture> {
3013
- // Canonical, because macOS puts the temp directory behind a /private symlink
3014
- // and a daemon never sees an edit made under a root named through one.
3015
- const root = await realpath(await mkdtemp(join(parent, 'smoothbricks-nx-plugin-')));
3016
-
3017
- return {
3018
- context: {
3019
- workspaceRoot: root,
3020
- nxJsonConfiguration: {},
3021
- },
3022
- async write(filePath: string, contents: string): Promise<void> {
3023
- const absolutePath = join(root, filePath);
3024
- await mkdir(dirname(absolutePath), { recursive: true });
3025
- await writeFile(absolutePath, contents);
3026
- },
3027
- async cleanup(): Promise<void> {
3028
- await rm(root, { recursive: true, force: true });
3029
- },
3030
- };
3031
- }
3032
-
3033
- interface WorkspaceFixture {
3034
- context: CreateNodesContextV2;
3035
- write(filePath: string, contents: string): Promise<void>;
3036
- cleanup(): Promise<void>;
3037
- }
3038
-
3039
- /**
3040
- * What inference told the operator while it ran. The plugin degrades out loud
3041
- * — a hash it cannot make complete is a cache verdict nobody can invalidate —
3042
- * so the stream is part of its behavior, not decoration.
3043
- */
3044
- async function withCapturedStderr<T>(run: () => Promise<T>): Promise<{ result: T; stderr: string }> {
3045
- const original = process.stderr.write.bind(process.stderr);
3046
- let stderr = '';
3047
- process.stderr.write = (chunk: string | Uint8Array) => {
3048
- stderr += typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
3049
- return true;
3050
- };
3051
- try {
3052
- return { result: await run(), stderr };
3053
- } finally {
3054
- process.stderr.write = original;
3055
- }
3056
- }
3057
-
3058
- /**
3059
- * A fileset Nx resolves against the workspace, or a named input nx.json
3060
- * declares. Anything else is a path this machine happens to have.
3061
- */
3062
- const WORKSPACE_ANCHORED_INPUT = /^!?(?:\{(?:projectRoot|workspaceRoot)\}\/|\^?[A-Za-z][\w-]*$)/;
3063
-
3064
- /** A path rooted outside the workspace, wherever it appears in a hashed value. */
3065
- const PATH_OUTSIDE_WORKSPACE = /(?:^|[^\w.\-~])(\/[\w.-]+\/[\w.-]+)/;
3066
-
3067
- /**
3068
- * One Cargo workspace producing every cached cargo target family inference can
3069
- * make: the host archive, a per-crate run, both lint verdicts, and — through
3070
- * the `cross-targets` declaration — the foreign-triple archive, which states
3071
- * its own inputs instead of receiving them from the `cargo --frozen` sweep.
3072
- */
3073
- async function writeCargoIdentityFixture(workspace: WorkspaceFixture): Promise<void> {
3074
- await workspace.write('packages/ferris/package.json', '{"name":"ferris"}\n');
3075
- await workspace.write(
3076
- 'packages/ferris/Cargo.toml',
3077
- '[workspace]\nmembers = ["crates/ferris-core"]\n\n' +
3078
- '[workspace.metadata.smoothbricks.test]\n' +
3079
- 'cross-targets = [{ target = "aarch64-apple-darwin", cargo = "scripts/cargo-for-nextest.sh" }]\n',
3080
- );
3081
- await workspace.write('packages/ferris/crates/ferris-core/Cargo.toml', '[package]\nname = "ferris-core"\n');
3082
- await workspace.write('packages/ferris/scripts/cargo-for-nextest.sh', '#!/bin/sh\nexec cargo "$@"\n');
3083
- }
3084
-
3085
- /**
3086
- * The targets a cache verdict can be wrong about: cached, and running cargo.
3087
- * Derived rather than listed, so a new cargo family joins these assertions the
3088
- * day it is inferred instead of the day someone remembers to add it.
3089
- */
3090
- function cachedCargoTargets(targets: Record<string, TargetConfiguration>): [string, TargetConfiguration][] {
3091
- return Object.entries(targets).filter(([, target]) => {
3092
- const command: unknown = target.options?.command;
3093
- const commands: unknown = target.options?.commands;
3094
- const text = [
3095
- typeof command === 'string' ? command : '',
3096
- ...(Array.isArray(commands) ? commands.filter((entry) => typeof entry === 'string') : []),
3097
- ].join('\n');
3098
- return target.cache === true && /\bcargo/.test(text);
3099
- });
3100
- }
3101
-
3102
- async function inferProject(
3103
- workspace: WorkspaceFixture,
3104
- packageJsonPath: string,
3105
- createNodes: CreateNodesV2 = createNodesV2,
3106
- ) {
3107
- const [, infer] = createNodes;
3108
- await prepareCargoFixture(workspace.context.workspaceRoot);
3109
- // Each inference indexes the tree as it is now, as a fresh Nx process would: the
3110
- // in-process workspace context otherwise keeps the files of the first inference.
3111
- resetWorkspaceContext();
3112
- const result = await infer([packageJsonPath], undefined, workspace.context);
3113
- return result[0]?.[1].projects?.[dirname(packageJsonPath)];
3114
- }
3115
-
3116
- /**
3117
- * Inference against a chosen nx.json. The versionless manifest inputs reach as
3118
- * far as the workspace's own `namedInputs` allow, so the workspace
3119
- * configuration is an input to inference and not a constant of the fixture.
3120
- */
3121
- async function inferProjectWithNxJson(
3122
- workspace: WorkspaceFixture,
3123
- packageJsonPath: string,
3124
- nxJsonConfiguration: CreateNodesContextV2['nxJsonConfiguration'],
3125
- ) {
3126
- const [, infer] = createNodesV2;
3127
- await prepareCargoFixture(workspace.context.workspaceRoot);
3128
- resetWorkspaceContext();
3129
- const result = await infer([packageJsonPath], undefined, {
3130
- workspaceRoot: workspace.context.workspaceRoot,
3131
- nxJsonConfiguration,
3132
- });
3133
- return result[0]?.[1].projects?.[dirname(packageJsonPath)];
3134
- }
3135
-
3136
- async function inferProjectTargets(
3137
- workspace: WorkspaceFixture,
3138
- packageJsonPath: string,
3139
- createNodes?: CreateNodesV2,
3140
- ): Promise<Record<string, TargetConfiguration>> {
3141
- return (await inferProject(workspace, packageJsonPath, createNodes))?.targets ?? {};
3142
- }
3143
-
3144
- /**
3145
- * The configuration Nx resolves for a target this plugin infers and the package
3146
- * also declares. Nx merges a package-local `nx.targets` entry over an inference
3147
- * plugin's target one layer later — the precedence order is specified plugins →
3148
- * target defaults → default plugins, and the package.json reader is a default
3149
- * plugin — so composing with the same merge function the graph uses makes these
3150
- * assertions the resolved configuration rather than a guess about it.
3151
- */
3152
- function resolveDeclaredOverInferred(
3153
- targets: Record<string, TargetConfiguration>,
3154
- declared: Record<string, TargetConfiguration>,
3155
- name: string,
3156
- ): TargetConfiguration | undefined {
3157
- const inferred = targets[name];
3158
- return inferred && mergeTargetConfigurations(declared[name] ?? {}, inferred);
3159
- }
3160
-
3161
- /**
3162
- * How a cargo test command is scoped to one crate, split into the three facts
3163
- * that can independently go wrong.
3164
- *
3165
- * `--binaries-metadata` must be present: the runner executes binaries one
3166
- * workspace `cargo nextest archive --workspace` already built, so a per-crate
3167
- * run cannot compile anything. Narrowing comes from the nextest filterset,
3168
- * which selects what RUNS. `--package` narrows too, but it re-resolves that
3169
- * crate's features, which is a build — 57.9s of a 120s bounded budget on a
3170
- * hosted 3-core macOS runner when the runners still built — so its presence is
3171
- * a regression even though it selects the same tests. nextest rejects it
3172
- * outright beside a reused build, and this assertion says so before cargo does.
3173
- */
3174
- function cargoPackageSelection(command: string): {
3175
- prebuiltRun: boolean;
3176
- packageFlags: string[];
3177
- filtered: string[];
3178
- } {
3179
- const tokens = command.split(/\s+/);
3180
- const packageFlags: string[] = [];
3181
- for (let i = 0; i < tokens.length; i++) {
3182
- if (tokens[i] === '--package' || tokens[i] === '-p') {
3183
- const name = tokens[i + 1];
3184
- if (name !== undefined && name.length > 0) {
3185
- packageFlags.push(name);
3186
- }
3187
- }
3188
- }
3189
- return {
3190
- prebuiltRun: tokens.includes('--binaries-metadata'),
3191
- packageFlags,
3192
- filtered: [...command.matchAll(/\bpackage\(([^)]+)\)/g)].flatMap((match) =>
3193
- match[1] === undefined ? [] : [match[1]],
3194
- ),
3195
- };
3196
- }
3197
-
3198
- /**
3199
- * Inference never throttles the scheduler: no target is exclusive and no
3200
- * run-commands target is run one command at a time. A pair that really is
3201
- * producer and consumer is one `&&` command; everything else is left to Nx and
3202
- * to the locks Cargo owns.
3203
- */
3204
- function expectNoSchedulerThrottle(targets: Record<string, TargetConfiguration>): void {
3205
- for (const [name, target] of Object.entries(targets)) {
3206
- expect(target.parallelism, `${name} parallelism`).toBeUndefined();
3207
- expect(target.options?.parallel, `${name} options.parallel`).toBeUndefined();
3208
- }
3209
- }
3210
-
3211
- /** A default-profile override that puts the tests `filter` selects in `group`, on the platform serial groups run on. */
3212
- function serialOverride(filter: string, group: string): string[] {
3213
- return [
3214
- '[[profile.default.overrides]]',
3215
- `filter = '${filter}'`,
3216
- `platform = 'cfg(target_os="macos")'`,
3217
- `test-group = '${group}'`,
3218
- '',
3219
- ];
3220
- }
3221
-
3222
- /** The real-image split in miniature: a device group over one crate, a host group over the two crates above it. */
3223
- const APFS_SPLIT_GROUPS: readonly string[] = [
3224
- '[test-groups.real-apfs]',
3225
- 'max-threads = 1',
3226
- '',
3227
- '[test-groups.real-apfs-host]',
3228
- 'max-threads = 1',
3229
- '',
3230
- ...serialOverride('package(cowshed-apfs-tests) and test(/real_apfs_/)', 'real-apfs'),
3231
- ...serialOverride('package(cowshed-core) and (test(/real_apfs_/) or binary(apfs_native_macos))', 'real-apfs-host'),
3232
- ...serialOverride('package(cowshed-cli) and test(/real_apfs_/)', 'real-apfs-host'),
3233
- ];
3234
-
3235
- /**
3236
- * A repository-root Cargo workspace with two projects: `cowshed` holds the production device layer (`cowshed-apfs`,
3237
- * which links `cowshed-os` and carries the test support the crates above it compile in), the real-image scenarios in a
3238
- * crate of their own (`cowshed-apfs-tests`, which nothing depends on) and the host crates, and `lmao` holds a crate no
3239
- * group can reach. `nextest` is the repository's `.config/nextest.toml`.
3240
- */
3241
- async function writeApfsSplitFixture(workspace: WorkspaceFixture, nextest: readonly string[]): Promise<void> {
3242
- const crate = (
3243
- project: string,
3244
- name: string,
3245
- dependencies: readonly string[] = [],
3246
- section: 'dependencies' | 'dev-dependencies' = 'dependencies',
3247
- ): Promise<void> =>
3248
- workspace.write(
3249
- `packages/${project}/crates/${name}/Cargo.toml`,
3250
- [
3251
- '[package]',
3252
- `name = "${name}"`,
3253
- ...(dependencies.length === 0
3254
- ? []
3255
- : ['', `[${section}]`, ...dependencies.map((dependency) => `${dependency} = { path = "../${dependency}" }`)]),
3256
- '',
3257
- ].join('\n'),
3258
- );
3259
- await workspace.write('package.json', '{"name":"@fixture/codebase"}\n');
3260
- await workspace.write('packages/cowshed/package.json', '{"name":"@fixture/cowshed","nx":{"name":"cowshed"}}\n');
3261
- await workspace.write('packages/lmao/package.json', '{"name":"@fixture/lmao","nx":{"name":"lmao"}}\n');
3262
- await workspace.write('Cargo.toml', '[workspace]\nmembers = ["packages/*/crates/*"]\n');
3263
- await crate('cowshed', 'cowshed-os');
3264
- await crate('cowshed', 'cowshed-apfs', ['cowshed-os']);
3265
- await crate('cowshed', 'cowshed-apfs-tests', ['cowshed-apfs', 'cowshed-os'], 'dev-dependencies');
3266
- await crate('cowshed', 'cowshed-core', ['cowshed-apfs', 'cowshed-os']);
3267
- await crate('cowshed', 'cowshed-cli', ['cowshed-core']);
3268
- await crate('lmao', 'lmao-core');
3269
- await workspace.write(
3270
- 'packages/cowshed/crates/cowshed-apfs/tests/support/blank_image.rs',
3271
- '// shared test support\n',
3272
- );
3273
- await workspace.write('.config/nextest.toml', nextest.join('\n'));
3274
- }
3275
-
3276
- /** Inference over the split fixture's three projects in the one call Nx makes: project root to inferred targets. */
3277
- async function inferApfsSplit(
3278
- workspace: WorkspaceFixture,
3279
- createNodes: CreateNodesV2 = createNodesV2ForPlatform('darwin', 'arm64'),
3280
- ): Promise<Map<string, Record<string, TargetConfiguration>>> {
3281
- const [, infer] = createNodes;
3282
- await prepareCargoFixture(workspace.context.workspaceRoot);
3283
- resetWorkspaceContext();
3284
- const inferred = await infer(
3285
- ['package.json', 'packages/cowshed/package.json', 'packages/lmao/package.json'],
3286
- undefined,
3287
- workspace.context,
3288
- );
3289
- return new Map(
3290
- inferred.flatMap(([, result]) =>
3291
- Object.entries(result.projects ?? {}).map(([root, project]): [string, Record<string, TargetConfiguration>] => [
3292
- root,
3293
- project.targets ?? {},
3294
- ]),
3295
- ),
3296
- );
3297
- }
3298
-
3299
- /** The crates whose whole tree a target hashes: one `{workspaceRoot}/…/crates/<crate>/**\/*` fileset each. */
3300
- function hashedCrates(target: TargetConfiguration | undefined): string[] {
3301
- const crates = (target?.inputs ?? []).flatMap((input) =>
3302
- typeof input === 'string'
3303
- ? (/^\{workspaceRoot\}\/packages\/[^/]+\/crates\/([^/]+)\/\*\*\/\*$/.exec(input)?.[1] ?? [])
3304
- : [],
3305
- );
3306
- return [...new Set(crates)].sort((left, right) => left.localeCompare(right));
3307
- }
3308
-
3309
- /** Whether Nx would hash `path` (workspace-relative) under the `{workspaceRoot}` filesets of `target`'s inputs. */
3310
- function hashes(target: TargetConfiguration | undefined, path: string): boolean {
3311
- const filesets = (target?.inputs ?? []).flatMap((input) =>
3312
- typeof input === 'string' && input.includes('{workspaceRoot}') ? [input] : [],
3313
- );
3314
- const matches = (fileset: string): boolean => new Bun.Glob(fileset.replace('{workspaceRoot}/', '')).match(path);
3315
- return (
3316
- filesets.some((input) => !input.startsWith('!') && matches(input)) &&
3317
- !filesets.some((input) => input.startsWith('!') && matches(input.slice(1)))
3318
- );
3319
- }