@smoothbricks/nx-plugin 0.4.25 → 0.4.27

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 (348) hide show
  1. package/README.md +1078 -98
  2. package/dist/bin/smoo-nx-bound-failures.d.ts +3 -0
  3. package/dist/bin/smoo-nx-bound-failures.d.ts.map +1 -0
  4. package/dist/bin/smoo-nx-bound-failures.js +31 -0
  5. package/dist/bin/smoo-nx-cargo-hash.js +28 -3
  6. package/dist/bin/smoo-nx-exec.js +16 -85
  7. package/dist/bin/smoo-nx-failures.d.ts +3 -0
  8. package/dist/bin/smoo-nx-failures.d.ts.map +1 -0
  9. package/dist/bin/smoo-nx-failures.js +3 -0
  10. package/dist/bin/smoo-nx-nextest-extract.js +3 -2
  11. package/dist/bin/smoo-nx-test-walks.d.ts +3 -0
  12. package/dist/bin/smoo-nx-test-walks.d.ts.map +1 -0
  13. package/dist/bin/smoo-nx-test-walks.js +34 -0
  14. package/dist/bounded-test-policy.d.ts +7 -1
  15. package/dist/bounded-test-policy.d.ts.map +1 -1
  16. package/dist/bounded-test-policy.js +101 -40
  17. package/dist/build-state-output-policy.d.ts +25 -0
  18. package/dist/build-state-output-policy.d.ts.map +1 -0
  19. package/dist/build-state-output-policy.js +64 -0
  20. package/dist/cargo-closure-input.d.ts +16 -17
  21. package/dist/cargo-closure-input.d.ts.map +1 -1
  22. package/dist/cargo-closure-input.js +37 -44
  23. package/dist/cargo-dev-profile.d.ts +37 -0
  24. package/dist/cargo-dev-profile.d.ts.map +1 -0
  25. package/dist/cargo-dev-profile.js +108 -0
  26. package/dist/cargo-source-hash.d.ts +50 -8
  27. package/dist/cargo-source-hash.d.ts.map +1 -1
  28. package/dist/cargo-source-hash.js +691 -71
  29. package/dist/cargo-toolchain-policy.d.ts +4 -0
  30. package/dist/cargo-toolchain-policy.d.ts.map +1 -1
  31. package/dist/cargo-toolchain-policy.js +5 -0
  32. package/dist/cargo-workspace.d.ts +108 -12
  33. package/dist/cargo-workspace.d.ts.map +1 -1
  34. package/dist/cargo-workspace.js +299 -18
  35. package/dist/cross-check-policy.d.ts +21 -3
  36. package/dist/cross-check-policy.d.ts.map +1 -1
  37. package/dist/cross-check-policy.js +24 -6
  38. package/dist/disk-command-policy.d.ts +7 -0
  39. package/dist/disk-command-policy.d.ts.map +1 -0
  40. package/dist/disk-command-policy.js +98 -0
  41. package/dist/ensure-built-receipt.d.ts +25 -0
  42. package/dist/ensure-built-receipt.d.ts.map +1 -0
  43. package/dist/ensure-built-receipt.js +261 -0
  44. package/dist/ensure-built-witness.d.ts +57 -0
  45. package/dist/ensure-built-witness.d.ts.map +1 -0
  46. package/dist/ensure-built-witness.js +412 -0
  47. package/dist/ensure-built.d.ts +213 -12
  48. package/dist/ensure-built.d.ts.map +1 -1
  49. package/dist/ensure-built.js +624 -177
  50. package/dist/eslint-file-set.d.ts +7 -0
  51. package/dist/eslint-file-set.d.ts.map +1 -0
  52. package/dist/eslint-file-set.js +12 -0
  53. package/dist/executors/bounded-exec/cpu-pool.d.ts +63 -0
  54. package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -0
  55. package/dist/executors/bounded-exec/cpu-pool.js +379 -0
  56. package/dist/executors/bounded-exec/cpu-tokens.d.ts +82 -0
  57. package/dist/executors/bounded-exec/cpu-tokens.d.ts.map +1 -0
  58. package/dist/executors/bounded-exec/cpu-tokens.js +114 -0
  59. package/dist/executors/bounded-exec/disk-lease.d.ts +61 -0
  60. package/dist/executors/bounded-exec/disk-lease.d.ts.map +1 -0
  61. package/dist/executors/bounded-exec/disk-lease.js +91 -0
  62. package/dist/executors/bounded-exec/executor.d.ts +45 -2
  63. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  64. package/dist/executors/bounded-exec/executor.js +447 -52
  65. package/dist/executors/bounded-exec/gateway-lease.d.ts +52 -0
  66. package/dist/executors/bounded-exec/gateway-lease.d.ts.map +1 -0
  67. package/dist/executors/bounded-exec/gateway-lease.js +143 -0
  68. package/dist/executors/bounded-exec/hang-diagnostics.d.ts +35 -0
  69. package/dist/executors/bounded-exec/hang-diagnostics.d.ts.map +1 -0
  70. package/dist/executors/bounded-exec/hang-diagnostics.js +231 -0
  71. package/dist/executors/bounded-exec/progress.d.ts +35 -0
  72. package/dist/executors/bounded-exec/progress.d.ts.map +1 -0
  73. package/dist/executors/bounded-exec/progress.js +79 -0
  74. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts +3 -0
  75. package/dist/executors/bounded-exec/ram-temp-fixtures.d.ts.map +1 -0
  76. package/dist/executors/bounded-exec/ram-temp-fixtures.js +12 -0
  77. package/dist/executors/bounded-exec/ram-temp-held.d.ts +91 -0
  78. package/dist/executors/bounded-exec/ram-temp-held.d.ts.map +1 -0
  79. package/dist/executors/bounded-exec/ram-temp-held.js +152 -0
  80. package/dist/executors/bounded-exec/ram-temp.d.ts +223 -0
  81. package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -0
  82. package/dist/executors/bounded-exec/ram-temp.js +1528 -0
  83. package/dist/executors/bounded-exec/schema.d.ts +29 -11
  84. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  85. package/dist/executors/bounded-exec/verdict.d.ts +162 -0
  86. package/dist/executors/bounded-exec/verdict.d.ts.map +1 -0
  87. package/dist/executors/bounded-exec/verdict.js +318 -0
  88. package/dist/executors/shard-timings/executor.d.ts +14 -0
  89. package/dist/executors/shard-timings/executor.d.ts.map +1 -0
  90. package/dist/executors/shard-timings/executor.js +25 -0
  91. package/dist/executors/shard-timings/schema.d.ts +4 -0
  92. package/dist/executors/shard-timings/schema.d.ts.map +1 -0
  93. package/dist/executors/shard-timings/schema.js +1 -0
  94. package/dist/failure-summary.d.ts +5 -0
  95. package/dist/failure-summary.d.ts.map +1 -0
  96. package/dist/failure-summary.js +118 -0
  97. package/dist/generators/create-package/generator.d.ts.map +1 -1
  98. package/dist/generators/create-package/generator.js +6 -2
  99. package/dist/index.d.ts +14 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +435 -230
  102. package/dist/managed-assets.d.ts +6 -0
  103. package/dist/managed-assets.d.ts.map +1 -1
  104. package/dist/managed-files/ci-workflow.d.ts +13 -0
  105. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  106. package/dist/managed-files/ci-workflow.js +44 -13
  107. package/dist/managed-files/files.d.ts +7 -1
  108. package/dist/managed-files/files.d.ts.map +1 -1
  109. package/dist/managed-files/files.js +62 -8
  110. package/dist/managed-files/json-edit.d.ts +21 -0
  111. package/dist/managed-files/json-edit.d.ts.map +1 -0
  112. package/dist/managed-files/json-edit.js +295 -0
  113. package/dist/managed-files/managed-format.d.ts +33 -1
  114. package/dist/managed-files/managed-format.d.ts.map +1 -1
  115. package/dist/managed-files/managed-format.js +82 -2
  116. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts +7 -0
  117. package/dist/managed-files/pr-preview-cleanup-workflow.d.ts.map +1 -1
  118. package/dist/managed-files/pr-preview-cleanup-workflow.js +68 -4
  119. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  120. package/dist/managed-files/publish-workflow.js +231 -48
  121. package/dist/managed-files/tree.d.ts +5 -0
  122. package/dist/managed-files/tree.d.ts.map +1 -1
  123. package/dist/managed-files/tree.js +5 -3
  124. package/dist/manifest-hash.js +3 -2
  125. package/dist/nextest-code-bound.d.ts +62 -0
  126. package/dist/nextest-code-bound.d.ts.map +1 -0
  127. package/dist/nextest-code-bound.js +154 -0
  128. package/dist/nextest-extraction.d.ts +24 -8
  129. package/dist/nextest-extraction.d.ts.map +1 -1
  130. package/dist/nextest-extraction.js +42 -7
  131. package/dist/package-target-policy.d.ts.map +1 -1
  132. package/dist/package-target-policy.js +3 -5
  133. package/dist/release-config-policy.d.ts.map +1 -1
  134. package/dist/release-config-policy.js +3 -5
  135. package/dist/runtime-input.d.ts +14 -0
  136. package/dist/runtime-input.d.ts.map +1 -0
  137. package/dist/runtime-input.js +15 -0
  138. package/dist/rust-tokens.d.ts +11 -0
  139. package/dist/rust-tokens.d.ts.map +1 -0
  140. package/dist/rust-tokens.js +81 -0
  141. package/dist/task-results.d.ts +6 -0
  142. package/dist/task-results.d.ts.map +1 -0
  143. package/dist/task-results.js +61 -0
  144. package/dist/test-program.d.ts +54 -0
  145. package/dist/test-program.d.ts.map +1 -0
  146. package/dist/test-program.js +292 -0
  147. package/dist/test-timings.d.ts +71 -0
  148. package/dist/test-timings.d.ts.map +1 -0
  149. package/dist/test-timings.js +393 -0
  150. package/dist/test-walk-policy.d.ts +103 -0
  151. package/dist/test-walk-policy.d.ts.map +1 -0
  152. package/dist/test-walk-policy.js +657 -0
  153. package/dist/testing.d.ts +177 -0
  154. package/dist/testing.d.ts.map +1 -0
  155. package/dist/testing.js +824 -0
  156. package/dist/type-guards.d.ts +3 -0
  157. package/dist/type-guards.d.ts.map +1 -0
  158. package/dist/type-guards.js +4 -0
  159. package/dist/typecheck-test-policy.d.ts +8 -5
  160. package/dist/typecheck-test-policy.d.ts.map +1 -1
  161. package/dist/typecheck-test-policy.js +113 -100
  162. package/dist/workspace-config-policy.d.ts +8 -0
  163. package/dist/workspace-config-policy.d.ts.map +1 -1
  164. package/dist/workspace-config-policy.js +175 -63
  165. package/dist/workspace-index.d.ts +12 -0
  166. package/dist/workspace-index.d.ts.map +1 -0
  167. package/dist/workspace-index.js +17 -0
  168. package/dist/workspace-manifest.d.ts +37 -1
  169. package/dist/workspace-manifest.d.ts.map +1 -1
  170. package/executors.json +5 -0
  171. package/loader.js +13 -11
  172. package/managed/raw/envrc +33 -62
  173. package/managed/raw/git-format-staged.yml +30 -35
  174. package/managed/raw/patches/nx@23.2.1.patch +3484 -0
  175. package/managed/raw/tooling/direnv/apple-developer.sh +83 -0
  176. package/managed/raw/tooling/direnv/developer-links.ts +607 -17
  177. package/managed/raw/tooling/direnv/devenv.smoo.nix +314 -92
  178. package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +20 -11
  179. package/managed/raw/tooling/direnv/linked-snapshots.ts +845 -0
  180. package/managed/raw/tooling/direnv/nx-socket-dir.sh +82 -0
  181. package/managed/raw/tooling/direnv/repo-path +14 -2
  182. package/managed/raw/tooling/direnv/setup-environment.ts +1009 -118
  183. package/managed/raw/tooling/direnv/toolchain-stamp.ts +45 -3
  184. package/managed/raw/tooling/direnv/ttsc-env.sh +39 -0
  185. package/managed/raw/tooling/git-hooks/commit-msg.sh +5 -6
  186. package/managed/raw/tooling/git-hooks/pre-commit.sh +7 -6
  187. package/managed/raw/tooling/git-hooks/pre-push.sh +20 -15
  188. package/managed/templates/github/actions/cache-nix-devenv/action.yml +6 -6
  189. package/managed/templates/github/actions/cache-node-modules/action.yml +6 -4
  190. package/managed/templates/github/actions/cache-nx/action.yml +1 -1
  191. package/managed/templates/github/actions/cache-ttsc-plugins/action.yml +1 -1
  192. package/managed/templates/github/actions/forgejo-artifact.cjs +99 -0
  193. package/managed/templates/github/actions/forgejo-download-artifact/action.yml +49 -0
  194. package/managed/templates/github/actions/forgejo-download-artifact/index.cjs +7 -0
  195. package/managed/templates/github/actions/forgejo-upload-artifact/action.yml +65 -0
  196. package/managed/templates/github/actions/forgejo-upload-artifact/index.cjs +7 -0
  197. package/managed/templates/github/actions/setup-devenv/action.yml +21 -3
  198. package/managed/templates/github/workflows/managed-files.yml +1 -2
  199. package/nextest.toml +8 -75
  200. package/package.json +75 -13
  201. package/runtime-input.sh +81 -0
  202. package/src/__tests__/counted-cargo-process.ts +286 -0
  203. package/src/__tests__/counted-cargo.ts +730 -0
  204. package/src/__tests__/fixture-cargo-home.ts +36 -0
  205. package/src/__tests__/fixture-nx-env.ts +157 -2
  206. package/src/__tests__/progress-clock.ts +43 -0
  207. package/src/__tests__/runtime-input.ts +23 -0
  208. package/src/bin/smoo-nx-bound-failures.test.ts +127 -0
  209. package/src/bin/smoo-nx-bound-failures.ts +33 -0
  210. package/src/bin/smoo-nx-cargo-hash.ts +28 -3
  211. package/src/bin/smoo-nx-exec.ts +17 -86
  212. package/src/bin/smoo-nx-failures.ts +4 -0
  213. package/src/bin/smoo-nx-nextest-extract.ts +3 -2
  214. package/src/bin/smoo-nx-test-walks.ts +42 -0
  215. package/src/bounded-test-policy.test.ts +268 -22
  216. package/src/bounded-test-policy.ts +114 -42
  217. package/src/build-state-output-policy.test.ts +115 -0
  218. package/src/build-state-output-policy.ts +90 -0
  219. package/src/bun-bootstrap.test.ts +57 -3
  220. package/src/bun-file-packages.test.ts +47 -0
  221. package/src/cargo-closure-input.test.ts +432 -62
  222. package/src/cargo-closure-input.ts +51 -57
  223. package/src/cargo-dev-profile.ts +137 -0
  224. package/src/cargo-resolve-cache.test.ts +1044 -0
  225. package/src/cargo-source-hash.test.ts +203 -93
  226. package/src/cargo-source-hash.ts +762 -75
  227. package/src/cargo-toolchain-policy.ts +6 -0
  228. package/src/cargo-workspace.test.ts +320 -0
  229. package/src/cargo-workspace.ts +344 -18
  230. package/src/cross-check-policy.test.ts +59 -1
  231. package/src/cross-check-policy.ts +25 -6
  232. package/src/disk-command-policy.test.ts +61 -0
  233. package/src/disk-command-policy.ts +107 -0
  234. package/src/ensure-built-receipt.test.ts +184 -0
  235. package/src/ensure-built-receipt.ts +263 -0
  236. package/src/ensure-built-witness.test.ts +344 -0
  237. package/src/ensure-built-witness.ts +252 -0
  238. package/src/ensure-built.test.ts +1043 -483
  239. package/src/ensure-built.ts +870 -197
  240. package/src/eslint-file-set.ts +9 -0
  241. package/src/executors/bounded-exec/cpu-pool.test.ts +454 -0
  242. package/src/executors/bounded-exec/cpu-pool.ts +417 -0
  243. package/src/executors/bounded-exec/cpu-tokens.test.ts +269 -0
  244. package/src/executors/bounded-exec/cpu-tokens.ts +177 -0
  245. package/src/executors/bounded-exec/disk-lease.test.ts +185 -0
  246. package/src/executors/bounded-exec/disk-lease.ts +139 -0
  247. package/src/executors/bounded-exec/executor-host.test.ts +778 -0
  248. package/src/executors/bounded-exec/executor.test.ts +1116 -63
  249. package/src/executors/bounded-exec/executor.ts +565 -67
  250. package/src/executors/bounded-exec/gateway-lease.ts +176 -0
  251. package/src/executors/bounded-exec/hang-diagnostics.test.ts +285 -0
  252. package/src/executors/bounded-exec/hang-diagnostics.ts +283 -0
  253. package/src/executors/bounded-exec/progress.test.ts +79 -0
  254. package/src/executors/bounded-exec/progress.ts +118 -0
  255. package/src/executors/bounded-exec/ram-temp-fixtures.ts +12 -0
  256. package/src/executors/bounded-exec/ram-temp-held.test.ts +264 -0
  257. package/src/executors/bounded-exec/ram-temp-held.ts +242 -0
  258. package/src/executors/bounded-exec/ram-temp-host.test.ts +605 -0
  259. package/src/executors/bounded-exec/ram-temp.test.ts +674 -0
  260. package/src/executors/bounded-exec/ram-temp.ts +1918 -0
  261. package/src/executors/bounded-exec/schema.json +11 -5
  262. package/src/executors/bounded-exec/schema.ts +27 -11
  263. package/src/executors/bounded-exec/verdict.test.ts +440 -0
  264. package/src/executors/bounded-exec/verdict.ts +433 -0
  265. package/src/executors/shard-timings/executor.ts +36 -0
  266. package/src/executors/shard-timings/schema.json +21 -0
  267. package/src/executors/shard-timings/schema.ts +4 -0
  268. package/src/failure-summary.ts +119 -0
  269. package/src/generators/bounded-test-targets/generator.test.ts +4 -4
  270. package/src/generators/bun-test-tracing/generator.test.ts +2 -2
  271. package/src/generators/create-package/generator.test.ts +6 -0
  272. package/src/generators/create-package/generator.ts +6 -2
  273. package/src/host-controller-wiring.test.ts +31 -0
  274. package/src/index.test.ts +1070 -360
  275. package/src/index.ts +524 -255
  276. package/src/linked-snapshots.nx.test.ts +172 -0
  277. package/src/managed-assets.ts +12 -0
  278. package/src/managed-files/ci-workflow.ts +54 -13
  279. package/src/managed-files/files.ts +65 -9
  280. package/src/managed-files/forgejo-artifact.test.ts +395 -0
  281. package/src/managed-files/generator.test.ts +60 -1
  282. package/src/managed-files/json-edit.test.ts +216 -0
  283. package/src/managed-files/json-edit.ts +290 -0
  284. package/src/managed-files/managed-format-json.test.ts +308 -0
  285. package/src/managed-files/managed-format.ts +90 -2
  286. package/src/managed-files/pr-preview-cleanup-workflow.ts +69 -3
  287. package/src/managed-files/publish-workflow.ts +285 -67
  288. package/src/managed-files/repo-path.test.ts +129 -0
  289. package/src/managed-files/trace-db-artifact.test.ts +7 -0
  290. package/src/managed-files/tree.ts +11 -3
  291. package/src/manifest-hash.ts +3 -2
  292. package/src/nextest-code-bound.test.ts +155 -0
  293. package/src/nextest-code-bound.ts +195 -0
  294. package/src/nextest-extraction.test.ts +37 -5
  295. package/src/nextest-extraction.ts +51 -9
  296. package/src/nextest-partitions.test.ts +495 -0
  297. package/src/nx-cache-bound.test.ts +109 -0
  298. package/src/nx-cache-restore-mtime.test.ts +170 -0
  299. package/src/nx-daemon-claim.test.ts +277 -0
  300. package/src/nx-daemon-idle-cpu.test.ts +81 -0
  301. package/src/nx-daemon-idle-policy.test.ts +51 -0
  302. package/src/nx-daemon-ignore-files.test.ts +210 -0
  303. package/src/nx-daemon-root-normalization.test.ts +105 -0
  304. package/src/nx-daemon-validity.test.ts +925 -0
  305. package/src/nx-dot-input-policy.test.ts +353 -0
  306. package/src/nx-failure-life-cycles.test.ts +207 -0
  307. package/src/nx-files-archive-racy.test.ts +97 -0
  308. package/src/nx-foreign-workspace-env.test.ts +329 -0
  309. package/src/nx-incomplete-run-summary.test.ts +70 -0
  310. package/src/nx-plugin-load-errors.test.ts +120 -0
  311. package/src/nx-project-resolution-cache.test.ts +176 -0
  312. package/src/nx-raw-inputs.test.ts +166 -0
  313. package/src/nx-resident-graph-workers.test.ts +112 -0
  314. package/src/nx-run-information.test.ts +118 -0
  315. package/src/nx-skipped-task-exit.test.ts +180 -0
  316. package/src/nx-state-location.test.ts +63 -0
  317. package/src/nx-store-resolution.test.ts +99 -0
  318. package/src/nx-task-graph-cycles.test.ts +148 -0
  319. package/src/nx-task-output-lease.test.ts +414 -0
  320. package/src/nx-use-local.test.ts +103 -0
  321. package/src/package-target-policy.ts +3 -6
  322. package/src/release-config-policy.ts +3 -6
  323. package/src/runtime-input.test.ts +215 -0
  324. package/src/runtime-input.ts +17 -0
  325. package/src/rust-tokens.ts +78 -0
  326. package/src/serial-group-wiring.test.ts +326 -0
  327. package/src/task-history-namespace.test.ts +181 -0
  328. package/src/task-results.test.ts +226 -0
  329. package/src/task-results.ts +75 -0
  330. package/src/test-program.test.ts +303 -0
  331. package/src/test-program.ts +341 -0
  332. package/src/test-timings.test.ts +240 -0
  333. package/src/test-timings.ts +311 -0
  334. package/src/test-walk-policy.test.ts +585 -0
  335. package/src/test-walk-policy.ts +731 -0
  336. package/src/testing.test.ts +509 -0
  337. package/src/testing.ts +922 -0
  338. package/src/type-guards.ts +4 -0
  339. package/src/typecheck-test-policy.test.ts +496 -11
  340. package/src/typecheck-test-policy.ts +137 -103
  341. package/src/workspace-config-policy.test.ts +212 -13
  342. package/src/workspace-config-policy.ts +101 -73
  343. package/src/workspace-index.ts +18 -0
  344. package/src/workspace-manifest.ts +41 -1
  345. package/test-timings.json +85 -28
  346. package/managed/raw/tooling/direnv/inherited-devenv.ts +0 -615
  347. package/managed/raw/tooling/direnv/shared-caches.sh +0 -53
  348. package/src/__tests__/in-process-nx-index.ts +0 -9
@@ -1,8 +1,17 @@
1
- import { execFile, execFileSync, spawnSync } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { realpathSync, statSync } from 'node:fs';
4
- import { lstat, readdir, readFile, readlink, realpath } from 'node:fs/promises';
5
- import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
1
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { channel } from 'node:diagnostics_channel';
4
+ import { constants, existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
5
+ import { access, lstat, mkdir, readdir, readFile, readlink, realpath, rename, rm, stat, writeFile, } from 'node:fs/promises';
6
+ import { createRequire } from 'node:module';
7
+ import { homedir } from 'node:os';
8
+ import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
+ import native from 'nx/src/native/index.js';
10
+ import { workspaceDataDirectoryForWorkspace } from 'nx/src/utils/cache-directory.js';
11
+ import { CARGO_TOOLCHAIN_PIN_INPUTS } from './cargo-toolchain-policy.js';
12
+ import { rustTokens } from './rust-tokens.js';
13
+ const { IS_WASM, WorkspaceContext } = native;
14
+ const cargoResolveEvents = channel('@smoothbricks/nx-plugin:cargo-resolve');
6
15
  /**
7
16
  * Narrowed field by field, not by typia: graph inference imports this module,
8
17
  * and a workspace that loads the plugin from its sources runs them without
@@ -25,11 +34,16 @@ function parseCargoMetadata(json) {
25
34
  return {
26
35
  packages: list(member(document, 'packages'), 'packages').map((pkg) => ({
27
36
  id: text(member(pkg, 'id'), 'package id'),
37
+ name: text(member(pkg, 'name'), 'package name'),
38
+ version: text(member(pkg, 'version'), 'package version'),
28
39
  source: member(pkg, 'source') === null ? null : text(member(pkg, 'source'), 'package source'),
29
40
  manifest_path: text(member(pkg, 'manifest_path'), 'package manifest_path'),
30
41
  targets: list(member(pkg, 'targets'), 'package targets').map((target) => ({
31
42
  src_path: text(member(target, 'src_path'), 'target src_path'),
32
43
  })),
44
+ ...(member(pkg, 'governing_manifest_path') === undefined
45
+ ? {}
46
+ : { governing_manifest_path: text(member(pkg, 'governing_manifest_path'), 'governing manifest') }),
33
47
  })),
34
48
  resolve: resolveGraph === null
35
49
  ? null
@@ -45,6 +59,65 @@ function parseCargoMetadata(json) {
45
59
  workspace_root: text(member(document, 'workspace_root'), 'workspace_root'),
46
60
  };
47
61
  }
62
+ /**
63
+ * Nx workers handle termination by exiting, so their exit hook kills owned
64
+ * Cargo groups. Standalone callers need signal forwarding after detaching
65
+ * Cargo from the terminal; handlers are installed only where the caller has
66
+ * not already chosen a signal disposition, and removed after the last child.
67
+ * The hooks are in place before the first child is spawned: a child runs as
68
+ * soon as it is spawned, and a signal that reached this process before its
69
+ * hooks would end it on the default action with Cargo's group left running.
70
+ * Uncatchable SIGKILL cannot execute either hook.
71
+ */
72
+ const cargoChildren = new Set();
73
+ function killCargoChild(child) {
74
+ if (process.platform === 'win32' || child.pid === undefined)
75
+ child.kill('SIGKILL');
76
+ else {
77
+ try {
78
+ process.kill(-child.pid, 'SIGKILL');
79
+ }
80
+ catch (error) {
81
+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH'))
82
+ throw error;
83
+ }
84
+ }
85
+ }
86
+ function killCargoChildren() {
87
+ for (const child of cargoChildren)
88
+ killCargoChild(child);
89
+ }
90
+ const forwardedSignals = new Set();
91
+ const cargoSignalHandlers = {
92
+ SIGINT: () => forwardCargoSignal('SIGINT'),
93
+ SIGTERM: () => forwardCargoSignal('SIGTERM'),
94
+ SIGHUP: () => forwardCargoSignal('SIGHUP'),
95
+ };
96
+ function removeCargoSignalHandlers() {
97
+ for (const signal of forwardedSignals)
98
+ process.removeListener(signal, cargoSignalHandlers[signal]);
99
+ forwardedSignals.clear();
100
+ }
101
+ function forwardCargoSignal(signal) {
102
+ killCargoChildren();
103
+ removeCargoSignalHandlers();
104
+ process.kill(process.pid, signal);
105
+ }
106
+ function ownCargoChildren() {
107
+ process.on('exit', killCargoChildren);
108
+ for (const signal of Object.keys(cargoSignalHandlers)) {
109
+ if (signal !== 'SIGINT' && signal !== 'SIGTERM' && signal !== 'SIGHUP')
110
+ continue;
111
+ if (process.listenerCount(signal) !== 0)
112
+ continue;
113
+ process.on(signal, cargoSignalHandlers[signal]);
114
+ forwardedSignals.add(signal);
115
+ }
116
+ }
117
+ function disownCargoChildren() {
118
+ process.removeListener('exit', killCargoChildren);
119
+ removeCargoSignalHandlers();
120
+ }
48
121
  /**
49
122
  * Cargo's stdout, or its failure with Cargo's stderr in the message. Not
50
123
  * `promisify` from `node:util`: importing that module makes Node probe color
@@ -53,10 +126,79 @@ function parseCargoMetadata(json) {
53
126
  * under its own pid, which a runtime input would hash as a new digest on
54
127
  * every run.
55
128
  */
56
- function runCargo(args, cwd) {
57
- // The executor form: the workspace compiles against es2022, which has no `Promise.withResolvers`.
129
+ function runCargo(args, cwd, boundMs = CARGO_RESOLVE_BOUND_MS) {
130
+ // spawn forwards detached groups; execFile does not. The public ES2022
131
+ // library API requires the constructor form, not Promise.withResolvers.
58
132
  return new Promise((settle, reject) => {
59
- execFile('cargo', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }, (error, stdout) => error === null ? settle(stdout) : reject(error));
133
+ // Hooks first: a signal caught from here on runs its listener after this
134
+ // synchronous body, by which time the child is in `cargoChildren`.
135
+ if (cargoChildren.size === 0)
136
+ ownCargoChildren();
137
+ let child;
138
+ try {
139
+ child = spawn('cargo', args, {
140
+ cwd,
141
+ detached: process.platform !== 'win32',
142
+ stdio: ['ignore', 'pipe', 'pipe'],
143
+ });
144
+ }
145
+ catch (error) {
146
+ if (cargoChildren.size === 0)
147
+ disownCargoChildren();
148
+ throw error;
149
+ }
150
+ cargoChildren.add(child);
151
+ let stdout = '';
152
+ let stderr = '';
153
+ let stdoutBytes = 0;
154
+ let stderrBytes = 0;
155
+ let failure;
156
+ const fail = (error) => {
157
+ failure ??= error;
158
+ killCargoChild(child);
159
+ };
160
+ const timer = setTimeout(() => fail(new Error(`cargo ${args.join(' ')} in ${cwd} did not finish within ${boundMs}ms; killed it, ` +
161
+ 'because an unbounded Cargo wait hangs every project-graph construction with no output')), boundMs);
162
+ child.stdout.setEncoding('utf8');
163
+ child.stderr.setEncoding('utf8');
164
+ child.stdout.on('data', (chunk) => {
165
+ if (failure !== undefined)
166
+ return;
167
+ stdoutBytes += Buffer.byteLength(chunk);
168
+ if (stdoutBytes > 64 * 1024 * 1024) {
169
+ fail(new Error('Cargo stdout exceeded 64 MiB'));
170
+ return;
171
+ }
172
+ stdout += chunk;
173
+ });
174
+ child.stderr.on('data', (chunk) => {
175
+ if (failure !== undefined)
176
+ return;
177
+ stderrBytes += Buffer.byteLength(chunk);
178
+ if (stderrBytes > 64 * 1024 * 1024) {
179
+ fail(new Error('Cargo stderr exceeded 64 MiB'));
180
+ return;
181
+ }
182
+ stderr += chunk;
183
+ });
184
+ child.on('error', (error) => {
185
+ failure ??= error;
186
+ });
187
+ child.stdout.on('error', fail);
188
+ child.stderr.on('error', fail);
189
+ child.on('close', (code, signal) => {
190
+ clearTimeout(timer);
191
+ cargoChildren.delete(child);
192
+ if (cargoChildren.size === 0)
193
+ disownCargoChildren();
194
+ if (failure !== undefined)
195
+ reject(failure);
196
+ else if (code !== 0) {
197
+ reject(new Error(`cargo ${args.join(' ')} failed (${signal ?? code}): ${stderr.trim()}`));
198
+ }
199
+ else
200
+ settle(stdout);
201
+ });
60
202
  });
61
203
  }
62
204
  /** Directories the hash never descends into: build output, VCS and volume metadata, installed packages. */
@@ -64,6 +206,7 @@ export const HASH_SKIPPED_DIRECTORIES = [
64
206
  'target',
65
207
  '.git',
66
208
  'node_modules',
209
+ '.nx',
67
210
  '.cache',
68
211
  '.cowshed',
69
212
  '.fseventsd',
@@ -85,8 +228,8 @@ export const CARGO_ANCESTOR_INPUTS = ['Cargo.toml', '.cargo/config', '.cargo/con
85
228
  * directory actually depend on, so an edit to an unrelated workspace member
86
229
  * leaves the digest alone.
87
230
  *
88
- * This covers Rust sources and Cargo configuration, matching the plugin's
89
- * in-workspace Rust inputs. Build scripts' other data/environment inputs remain
231
+ * This covers Rust sources, literal compiled-in files and Cargo configuration,
232
+ * matching the plugin's in-workspace Rust inputs. Build scripts' other data/environment inputs remain
90
233
  * explicit Nx inputs, just as they are for in-workspace crates. Files git
91
234
  * ignores beneath a package are left out, like Nx's own file inputs: a
92
235
  * generated source is its producer's output, which the consuming target hashes
@@ -97,51 +240,460 @@ export const CARGO_ANCESTOR_INPUTS = ['Cargo.toml', '.cargo/config', '.cargo/con
97
240
  // on stderr ("Blocking waiting for file lock on package cache") a
98
241
  // timing-dependent number of times when Nx hashes many tasks at once, which
99
242
  // made one unchanged tree produce four different task hashes per run. Cargo's
100
- // stderr is kept for the failure path only, where execFile attaches it to the
243
+ // stderr is kept for the failure path only, where runCargo includes it in the
101
244
  // rejected error. Git runs under the same rule.
102
245
  const CHILD_STDIO = ['ignore', 'pipe', 'pipe'];
103
- /** Locked, offline `cargo metadata` for the workspace `manifestPath` names, run from `cwd`. */
104
- export async function readCargoResolve(manifestPath, cwd) {
105
- const stdout = await runCargo(['metadata', '--format-version', '1', '--locked', '--offline', '--manifest-path', resolve(manifestPath)], cwd);
106
- const metadata = parseCargoMetadata(stdout);
107
- const local = await Promise.all(metadata.packages
108
- .filter((pkg) => pkg.source === null)
109
- .map(async (pkg) => {
110
- const manifest = await realpath(pkg.manifest_path);
111
- const sources = await Promise.all(pkg.targets.map((target) => realpath(target.src_path)));
112
- return { id: pkg.id, directory: dirname(manifest), manifest, sources };
113
- }));
246
+ /**
247
+ * Git reads only the repository, never the operator's home (cowshed
248
+ * `04_sandbox.md`, runtime inputs). A host client's runtime input runs in a
249
+ * workspace's sandboxed daemon with the host's HOME: git dies on the global
250
+ * configuration the sandbox denies, and its global ignore file
251
+ * (`~/.config/git/ignore`, read even without a global configuration) would
252
+ * decide which sources the key covers. Neither belongs to the tree.
253
+ */
254
+ const ISOLATED_GIT_ARGS = ['-c', 'core.excludesFile=/dev/null'];
255
+ function isolatedGitEnv() {
256
+ return { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
257
+ }
258
+ /** A Cargo resolution refusal: no stale closure or runtime whole-workspace substitute is safe. */
259
+ export class CargoMetadataError extends Error {
260
+ manifestPath;
261
+ constructor(manifestPath, cause) {
262
+ const detail = cause instanceof Error
263
+ ? `${cause.name}: ${cause.message}`
264
+ : typeof cause === 'object' && cause !== null && 'message' in cause
265
+ ? String(cause.message)
266
+ : String(cause);
267
+ super(`Locked offline Cargo resolution failed for ${manifestPath}: ${detail}`, { cause });
268
+ this.name = 'CargoMetadataError';
269
+ this.manifestPath = manifestPath;
270
+ }
271
+ }
272
+ const resolves = new Map();
273
+ // v2 retains package name/version for checkout-independent artifact input identities.
274
+ const RESOLVE_CACHE_SCHEMA = 'cargo-resolve-v2';
275
+ /**
276
+ * The longest one Cargo child, or one wait for a foreign resolve flight's lock, may take.
277
+ * Both waits sit on every project-graph construction, so an unbounded one is a silent,
278
+ * output-free hang of every gate that resolves the graph (a stopped lock holder, a Cargo
279
+ * process convoy): at the bound the wait fails, naming what it waited on and for how long.
280
+ */
281
+ export const CARGO_RESOLVE_BOUND_MS = 300_000;
282
+ /**
283
+ * The full manifest SET, not merely the last closure: adding a glob workspace
284
+ * member must invalidate resolution even when Cargo.lock did not change.
285
+ * Graph callers supply Nx's already-current index; standalone hash callers
286
+ * take a fresh native snapshot. File contents below are read directly so an
287
+ * edit within Nx's mtime granularity cannot reuse a stale resolution.
288
+ */
289
+ function resolutionFiles(root, manifest, cargo, indexed) {
290
+ const paths = new Set([manifest]);
291
+ for (const file of indexed)
292
+ paths.add(resolve(root, file));
293
+ for (const pkg of cargo?.local ?? []) {
294
+ paths.add(pkg.manifest);
295
+ paths.add(pkg.governingManifest);
296
+ }
297
+ if (cargo !== null)
298
+ paths.add(join(cargo.root, 'Cargo.toml'));
299
+ const directories = new Set([root]);
300
+ for (const file of paths)
301
+ directories.add(dirname(file));
302
+ for (const directory of directories) {
303
+ paths.add(join(directory, 'Cargo.lock'));
304
+ for (let ancestor = directory;; ancestor = dirname(ancestor)) {
305
+ paths.add(join(ancestor, '.cargo/config'));
306
+ paths.add(join(ancestor, '.cargo/config.toml'));
307
+ paths.add(join(ancestor, 'rust-toolchain'));
308
+ paths.add(join(ancestor, 'rust-toolchain.toml'));
309
+ paths.add(join(ancestor, 'Cargo.toml'));
310
+ if (dirname(ancestor) === ancestor)
311
+ break;
312
+ }
313
+ }
314
+ for (const pin of CARGO_TOOLCHAIN_PIN_INPUTS)
315
+ paths.add(pin.replace('{workspaceRoot}', root));
316
+ const cargoHome = resolve(process.env.CARGO_HOME ?? join(homedir(), '.cargo'));
317
+ paths.add(join(cargoHome, 'config'));
318
+ paths.add(join(cargoHome, 'config.toml'));
319
+ return paths;
320
+ }
321
+ /** Toolchain selection can change even while the declared pin's bytes do not. */
322
+ async function cargoExecutable() {
323
+ for (const directory of (process.env.PATH ?? '').split(delimiter)) {
324
+ const executable = resolve(directory, process.platform === 'win32' ? 'cargo.exe' : 'cargo');
325
+ try {
326
+ await access(executable, constants.X_OK);
327
+ return await realpath(executable);
328
+ }
329
+ catch (error) {
330
+ if (!(error instanceof Error &&
331
+ 'code' in error &&
332
+ (error.code === 'ENOENT' || error.code === 'EACCES' || error.code === 'ENOTDIR')))
333
+ throw error;
334
+ }
335
+ }
336
+ return '<cargo-not-on-PATH>';
337
+ }
338
+ async function resolutionKey(root, manifest, cargo, indexed) {
339
+ const cargoHome = resolve(process.env.CARGO_HOME ?? join(homedir(), '.cargo'));
340
+ const executable = await cargoExecutable();
341
+ const hash = createHash('sha256').update(`${RESOLVE_CACHE_SCHEMA}\0${root}\0${manifest}\0${cargoHome}\0${executable}\0${process.env.RUSTUP_TOOLCHAIN ?? ''}\0${process.env.RUSTUP_HOME ?? ''}\0`);
342
+ for (const file of [...resolutionFiles(root, manifest, cargo, indexed)].sort()) {
343
+ hash.update(file).update('\0');
344
+ try {
345
+ const [bytes, canonical] = await Promise.all([readFile(file), realpath(file)]);
346
+ hash.update(`${canonical}\0${bytes.length}\0`).update(bytes);
347
+ }
348
+ catch (error) {
349
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
350
+ throw error;
351
+ hash.update('missing');
352
+ }
353
+ hash.update('\0');
354
+ }
355
+ return hash.digest('hex');
356
+ }
357
+ function cargoFromMetadata(metadata) {
114
358
  return {
115
- root: await realpath(metadata.workspace_root),
359
+ root: metadata.workspace_root,
116
360
  members: new Set(metadata.workspace_members),
117
- local,
361
+ local: metadata.packages
362
+ .filter((pkg) => pkg.source === null)
363
+ .map((pkg) => {
364
+ if (pkg.governing_manifest_path === undefined)
365
+ throw new Error('Cargo cache omitted a governing manifest');
366
+ return {
367
+ id: pkg.id,
368
+ name: pkg.name,
369
+ version: pkg.version,
370
+ directory: dirname(pkg.manifest_path),
371
+ manifest: pkg.manifest_path,
372
+ sources: pkg.targets.map((target) => target.src_path),
373
+ governingManifest: pkg.governing_manifest_path,
374
+ };
375
+ }),
118
376
  edges: metadata.resolve === null
119
377
  ? null
120
- : new Map(metadata.resolve.nodes.map((node) => [node.id, node.deps.map((dependency) => dependency.pkg)])),
378
+ : new Map(metadata.resolve.nodes.map((node) => [node.id, node.deps.map((dep) => dep.pkg)])),
121
379
  };
122
380
  }
381
+ async function loadResolveCache(file) {
382
+ let content;
383
+ try {
384
+ content = await readFile(file, 'utf8');
385
+ }
386
+ catch (error) {
387
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
388
+ return null;
389
+ throw error;
390
+ }
391
+ try {
392
+ const newline = content.indexOf('\n');
393
+ const key = content.slice(0, newline);
394
+ if (newline === -1 || !/^[a-f0-9]{64}$/.test(key))
395
+ throw new Error('invalid content-key header');
396
+ const metadata = parseCargoMetadata(content.slice(newline + 1));
397
+ return { key, cargo: cargoFromMetadata(metadata) };
398
+ }
399
+ catch (error) {
400
+ process.stderr.write(`@smoothbricks/nx-plugin: discarding corrupt Cargo resolution cache ${file}: ${error instanceof Error ? error.message : String(error)}\n`);
401
+ return null;
402
+ }
403
+ }
123
404
  /**
124
- * The canonical root manifest of the Cargo workspace that governs `pkg`.
125
- * Metadata's `workspace_root` describes only the invoking workspace, which is
126
- * the answer for its own members. Any other path package asks Cargo, which
127
- * resolves an explicit `package.workspace` as well as the ancestor search.
405
+ * One content-keyed resolution per Cargo workspace, across concurrent graph
406
+ * calls and workers. A bounded child owns Nx's kernel FileLock while the
407
+ * resolution runs; in-process callers join before asking for that lease.
408
+ * A changed key queues behind the old child instead of receiving its stale answer.
128
409
  */
129
- export async function governingManifest(cargo, pkg, cwd) {
130
- if (cargo.members.has(pkg.id))
131
- return realpath(join(cargo.root, 'Cargo.toml'));
132
- const stdout = await runCargo(['locate-project', '--workspace', '--manifest-path', pkg.manifest, '--message-format', 'plain'], cwd);
133
- return realpath(stdout.trim());
410
+ export async function readCargoResolve(manifestPath, cwd, indexed, boundMs = CARGO_RESOLVE_BOUND_MS) {
411
+ let manifest = resolve(manifestPath);
412
+ try {
413
+ const root = await realpath(cwd);
414
+ manifest = await realpath(manifest);
415
+ const index = indexed ?? new Set(new WorkspaceContext(root, workspaceDataDirectoryForWorkspace(root)).glob(['**/Cargo.toml']));
416
+ const identity = createHash('sha256').update(`${RESOLVE_CACHE_SCHEMA}\0${root}\0${manifest}`).digest('hex');
417
+ const directory = join(workspaceDataDirectoryForWorkspace(root), 'cargo-resolve', identity);
418
+ const file = join(directory, 'entry.cache');
419
+ let state = resolves.get(identity);
420
+ if (state === undefined) {
421
+ const created = { ready: Promise.resolve(), cached: null };
422
+ created.ready = loadResolveCache(file).then((cached) => {
423
+ created.cached = cached;
424
+ });
425
+ resolves.set(identity, created);
426
+ state = created;
427
+ try {
428
+ await created.ready;
429
+ }
430
+ catch (error) {
431
+ resolves.delete(identity);
432
+ throw error;
433
+ }
434
+ }
435
+ else
436
+ await state.ready;
437
+ for (let joined = 0; joined <= 3; joined += 1) {
438
+ const key = await resolutionKey(root, manifest, state.cached?.cargo ?? null, index);
439
+ const pending = state.pending;
440
+ if (pending !== undefined) {
441
+ if (joined === 3)
442
+ break;
443
+ if (cargoResolveEvents.hasSubscribers)
444
+ cargoResolveEvents.publish({ phase: 'join', manifest });
445
+ try {
446
+ await pending.promise;
447
+ }
448
+ catch (error) {
449
+ // Sharers of a refused key receive its refusal; a changed key still
450
+ // needs its own resolution after the old flight releases the lock.
451
+ if (pending.key === key)
452
+ throw error;
453
+ }
454
+ // Re-key every joiner with the discovered paths, including an external
455
+ // manifest edited after the flight's last validation, before publication.
456
+ continue;
457
+ }
458
+ if (state.cached?.key === key)
459
+ return state.cached.cargo;
460
+ if (joined === 3)
461
+ break;
462
+ const active = state;
463
+ const promise = resolveAndCache(root, manifest, index, directory, file, active, boundMs);
464
+ active.pending = { key, promise };
465
+ try {
466
+ return await promise;
467
+ }
468
+ finally {
469
+ if (active.pending?.promise === promise)
470
+ delete active.pending;
471
+ }
472
+ }
473
+ throw new Error('Cargo resolution inputs kept changing across three consecutive in-flight queries');
474
+ }
475
+ catch (error) {
476
+ if (error instanceof CargoMetadataError)
477
+ throw error;
478
+ throw new CargoMetadataError(manifest, error);
479
+ }
480
+ }
481
+ async function resolveAndCache(root, manifest, indexed, directory, file, state, boundMs = CARGO_RESOLVE_BOUND_MS) {
482
+ if (IS_WASM)
483
+ throw new Error('Cargo resolution requires the native Nx file lock; a WASM Nx host cannot own Cargo children');
484
+ await mkdir(directory, { recursive: true });
485
+ // A warm cache answers with no lock: reading it and keying it spawns nothing and
486
+ // waits for nobody, so an unchanged workspace never queues behind a foreign flight.
487
+ state.cached = await loadResolveCache(file);
488
+ {
489
+ const key = await resolutionKey(root, manifest, state.cached?.cargo ?? null, indexed);
490
+ if (state.cached?.key === key)
491
+ return state.cached.cargo;
492
+ }
493
+ const lockFile = join(directory, 'resolve.lock');
494
+ const lock = await acquireCargoResolveLock(lockFile, boundMs);
495
+ try {
496
+ // Another worker may have populated it while this worker waited.
497
+ state.cached = await loadResolveCache(file);
498
+ let inputs = state.cached?.cargo ?? null;
499
+ for (let attempt = 0; attempt < 3; attempt += 1) {
500
+ const before = await resolutionKey(root, manifest, inputs, indexed);
501
+ if (state.cached?.key === before)
502
+ return state.cached.cargo;
503
+ const knownFiles = resolutionFiles(root, manifest, inputs, indexed);
504
+ // A filesystem timestamp, not a sandbox's wall clock: a newly
505
+ // discovered external input edited during this flight requires replay.
506
+ await writeFile(lockFile, '');
507
+ const started = (await stat(lockFile)).mtimeMs;
508
+ const metadata = await resolveCargoMetadata(manifest, root, boundMs);
509
+ const cargo = cargoFromMetadata(metadata);
510
+ // Capture the published key before validation. Reading it afterwards
511
+ // could pair a post-edit key with Cargo's pre-edit answer.
512
+ const key = await resolutionKey(root, manifest, cargo, indexed);
513
+ let changed = before !== (await resolutionKey(root, manifest, inputs, indexed));
514
+ for (const added of resolutionFiles(root, manifest, cargo, indexed)) {
515
+ if (knownFiles.has(added))
516
+ continue;
517
+ try {
518
+ if ((await stat(added)).mtimeMs >= started)
519
+ changed = true;
520
+ }
521
+ catch (error) {
522
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
523
+ throw error;
524
+ }
525
+ }
526
+ if (changed) {
527
+ inputs = cargo;
528
+ continue;
529
+ }
530
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
531
+ try {
532
+ await writeFile(temporary, `${key}\n${JSON.stringify(metadata)}\n`);
533
+ await rename(temporary, file);
534
+ }
535
+ finally {
536
+ await rm(temporary, { force: true });
537
+ }
538
+ state.cached = { key, cargo };
539
+ return cargo;
540
+ }
541
+ throw new Error('Cargo resolution inputs kept changing during three consecutive locked offline queries');
542
+ }
543
+ finally {
544
+ await lock.release();
545
+ }
546
+ }
547
+ /** A failed acquisition names the lock, elapsed wait, and the reaped waiter. */
548
+ export class CargoResolveLockError extends Error {
549
+ lockFile;
550
+ boundMs;
551
+ waitedMs;
552
+ waiterPid;
553
+ constructor(lockFile, boundMs, waitedMs, waiterPid) {
554
+ super(`waited ${waitedMs}ms for the Cargo resolve lock ${lockFile} (bound ${boundMs}ms; holder pid unknown); ` +
555
+ `killed and reaped lock waiter pid ${waiterPid ?? 'unavailable'} because an unbounded wait hangs project-graph construction`);
556
+ this.lockFile = lockFile;
557
+ this.boundMs = boundMs;
558
+ this.waitedMs = waitedMs;
559
+ this.waiterPid = waiterPid;
560
+ this.name = 'CargoResolveLockError';
561
+ }
562
+ }
563
+ /**
564
+ * The pinned Nx binding has only blocking acquisition. Isolate that syscall in
565
+ * one child per cold flight so the caller's deadline can kill and reap it.
566
+ * Closing stdin releases a successful lease; warm cache reads spawn no child.
567
+ */
568
+ export function acquireCargoResolveLock(lockFile, boundMs) {
569
+ const nativeModule = createRequire(import.meta.url).resolve('nx/src/native/index.js');
570
+ const program = [
571
+ `const { FileLock } = require(${JSON.stringify(nativeModule)});`,
572
+ `const lock = new FileLock(${JSON.stringify(lockFile)});`,
573
+ 'lock.lock();',
574
+ "process.stdout.write('locked\\n');",
575
+ 'process.stdin.resume();',
576
+ "process.stdin.on('end', () => { lock.unlock(); process.exit(0); });",
577
+ ].join('\n');
578
+ // The public ES2022 library API requires the constructor form, not Promise.withResolvers.
579
+ return new Promise((settle, reject) => {
580
+ const started = performance.now();
581
+ const child = spawn(process.execPath, ['--eval', program], {
582
+ detached: process.platform !== 'win32',
583
+ stdio: ['pipe', 'pipe', 'pipe'],
584
+ });
585
+ let acquired = false;
586
+ let releasing = false;
587
+ let failure;
588
+ let stdout = '';
589
+ let stderr = '';
590
+ const fail = (error) => {
591
+ failure ??= error;
592
+ killCargoChild(child);
593
+ };
594
+ const timer = setTimeout(() => fail(new CargoResolveLockError(lockFile, boundMs, Math.ceil(performance.now() - started), child.pid)), boundMs);
595
+ const closed = new Promise((finish) => {
596
+ child.on('close', (code, signal) => {
597
+ clearTimeout(timer);
598
+ cargoChildren.delete(child);
599
+ if (cargoChildren.size === 0) {
600
+ process.removeListener('exit', killCargoChildren);
601
+ removeCargoSignalHandlers();
602
+ }
603
+ if (failure === undefined && (!releasing || code !== 0)) {
604
+ failure = new Error(`Cargo resolve lock ${lockFile} waiter pid ${child.pid} exited (${signal ?? code}): ${stderr.trim()}`);
605
+ }
606
+ if (!acquired)
607
+ reject(failure);
608
+ finish();
609
+ });
610
+ });
611
+ child.stdout.setEncoding('utf8');
612
+ child.stderr.setEncoding('utf8');
613
+ child.stdout.on('data', (chunk) => {
614
+ stdout += chunk;
615
+ if (failure !== undefined || acquired || stdout !== 'locked\n')
616
+ return;
617
+ const waitedMs = Math.ceil(performance.now() - started);
618
+ if (waitedMs >= boundMs) {
619
+ fail(new CargoResolveLockError(lockFile, boundMs, waitedMs, child.pid));
620
+ return;
621
+ }
622
+ if (child.pid === undefined) {
623
+ fail(new Error(`Cargo resolve lock ${lockFile} acquired without a child pid`));
624
+ return;
625
+ }
626
+ acquired = true;
627
+ clearTimeout(timer);
628
+ settle({
629
+ pid: child.pid,
630
+ release: async () => {
631
+ releasing = true;
632
+ child.stdin.end();
633
+ await closed;
634
+ if (failure !== undefined)
635
+ throw failure;
636
+ },
637
+ });
638
+ });
639
+ child.stderr.on('data', (chunk) => {
640
+ stderr += chunk;
641
+ });
642
+ child.on('error', fail);
643
+ child.stdin.on('error', fail);
644
+ child.stdout.on('error', fail);
645
+ child.stderr.on('error', fail);
646
+ if (cargoChildren.size === 0)
647
+ ownCargoChildren();
648
+ cargoChildren.add(child);
649
+ });
650
+ }
651
+ async function resolveCargoMetadata(manifestPath, cwd, boundMs = CARGO_RESOLVE_BOUND_MS) {
652
+ const stdout = await runCargo(['metadata', '--format-version', '1', '--locked', '--offline', '--manifest-path', manifestPath], cwd, boundMs);
653
+ const metadata = parseCargoMetadata(stdout);
654
+ metadata.workspace_root = await realpath(metadata.workspace_root);
655
+ const members = new Set(metadata.workspace_members);
656
+ // Sequential: the metadata flight owns every Cargo process it starts,
657
+ // including the one-time governing-workspace lookups for path dependencies.
658
+ for (const pkg of metadata.packages) {
659
+ if (pkg.source !== null)
660
+ continue;
661
+ pkg.manifest_path = await realpath(pkg.manifest_path);
662
+ for (const target of pkg.targets)
663
+ target.src_path = await realpath(target.src_path);
664
+ pkg.governing_manifest_path = members.has(pkg.id)
665
+ ? join(metadata.workspace_root, 'Cargo.toml')
666
+ : await realpath((await runCargo(['locate-project', '--workspace', '--manifest-path', pkg.manifest_path, '--message-format', 'plain'], cwd, boundMs)).trim());
667
+ }
668
+ return metadata;
134
669
  }
135
670
  export async function hashCargoPathInputs(manifestPath, workspaceRoot, options) {
136
671
  const root = await realpath(workspaceRoot);
137
672
  const cargo = await readCargoResolve(manifestPath, root);
138
673
  const members = options?.closure === undefined ? undefined : await dependencyClosure(cargo, resolve(options.closure));
139
- const directories = new Set();
140
- const files = new Set();
674
+ const inputKey = (pkg, role, path) => JSON.stringify([pkg.name, pkg.version, role, path.split(sep).join('/')]);
675
+ const directories = new Map();
676
+ const files = new Map();
141
677
  const ancestors = new Set();
142
678
  const links = new Map();
143
679
  const packageSources = [];
144
- for (const pkg of cargo.local) {
680
+ // Read shared bytes once. The smallest declared identity makes multiple owners
681
+ // deterministic without using a consuming checkout's mount path as an input.
682
+ const includeFile = (file, key) => {
683
+ const prior = files.get(file);
684
+ if (prior === undefined || key < prior)
685
+ files.set(file, key);
686
+ };
687
+ const packages = [...cargo.local].sort((left, right) => left.name < right.name
688
+ ? -1
689
+ : left.name > right.name
690
+ ? 1
691
+ : left.version < right.version
692
+ ? -1
693
+ : left.version > right.version
694
+ ? 1
695
+ : 0);
696
+ for (const pkg of packages) {
145
697
  if (members !== undefined && !members.has(pkg.id))
146
698
  continue;
147
699
  const directory = pkg.directory;
@@ -149,38 +701,36 @@ export async function hashCargoPathInputs(manifestPath, workspaceRoot, options)
149
701
  const fromRoot = relative(root, directory);
150
702
  const fromCargo = relative(cargo.root, directory);
151
703
  if (fromRoot !== '..' &&
152
- !fromRoot.startsWith(`..${sep}`) &&
704
+ !fromRoot.startsWith('..' + sep) &&
153
705
  !isAbsolute(fromRoot) &&
154
706
  fromCargo !== '..' &&
155
- !fromCargo.startsWith(`..${sep}`) &&
707
+ !fromCargo.startsWith('..' + sep) &&
156
708
  !isAbsolute(fromCargo) &&
157
709
  !fromRoot.split(sep).includes('node_modules'))
158
710
  continue;
159
711
  }
160
- directories.add(directory);
161
- files.add(pkg.manifest);
162
- files.add(await governingManifest(cargo, pkg, root));
163
- packageSources.push(...pkg.sources);
164
- // A member can inherit edition, lint policy, dependencies and
165
- // profiles from a workspace above its package directory. Those manifests
166
- // are not descendants of the source roots returned by Cargo metadata.
167
- for (let ancestor = dirname(directory); !ancestors.has(ancestor); ancestor = dirname(ancestor)) {
712
+ directories.set(directory, pkg);
713
+ includeFile(pkg.manifest, inputKey(pkg, 'manifest', 'Cargo.toml'));
714
+ includeFile(pkg.governingManifest, inputKey(pkg, 'workspace', 'Cargo.toml'));
715
+ for (const [index, file] of pkg.sources.entries())
716
+ packageSources.push({ file, key: inputKey(pkg, 'target', String(index)) });
717
+ for (let ancestor = dirname(directory), depth = 1; !ancestors.has(ancestor); ancestor = dirname(ancestor), depth += 1) {
168
718
  ancestors.add(ancestor);
169
719
  for (const name of CARGO_ANCESTOR_INPUTS) {
170
720
  const file = join(ancestor, name);
171
- if (statSync(file, { throwIfNoEntry: false })?.isFile())
172
- files.add(await realpath(file));
721
+ if (statSync(file, { throwIfNoEntry: false })?.isFile()) {
722
+ includeFile(await realpath(file), inputKey(pkg, 'ancestor', depth + '/' + name));
723
+ }
173
724
  }
174
725
  }
175
726
  }
176
- const ignored = gitIgnoredBeneath([...directories]);
177
- for (const source of packageSources)
178
- if (!ignored(source))
179
- files.add(source);
727
+ const ignored = gitIgnoredBeneath([...directories.keys()]);
728
+ for (const { file, key } of packageSources)
729
+ if (!ignored(file))
730
+ includeFile(file, key);
180
731
  const skipped = new Set(HASH_SKIPPED_DIRECTORIES);
181
- // Overlapping packages (a facade root plus its child crates) share one walk.
182
732
  const visited = new Set();
183
- async function walk(directory) {
733
+ async function walk(directory, owner, within) {
184
734
  const canonical = await realpath(directory);
185
735
  if (visited.has(canonical))
186
736
  return;
@@ -191,35 +741,43 @@ export async function hashCargoPathInputs(manifestPath, workspaceRoot, options)
191
741
  const path = join(canonical, entry.name);
192
742
  if (ignored(path))
193
743
  continue;
744
+ const localPath = within === '' ? entry.name : within + '/' + entry.name;
194
745
  if (entry.isSymbolicLink())
195
- links.set(path, await readlink(path));
746
+ links.set(path, { key: inputKey(owner, 'link', localPath), target: await readlink(path) });
196
747
  const info = entry.isSymbolicLink() ? await lstat(await realpath(path)) : entry;
197
748
  if (info.isDirectory()) {
198
- await walk(path);
749
+ await walk(path, owner, localPath);
199
750
  }
200
751
  else if (info.isFile() &&
201
752
  (entry.name.endsWith('.rs') ||
202
753
  entry.name === 'Cargo.toml' ||
203
- (canonical.endsWith(`${sep}.cargo`) && (entry.name === 'config' || entry.name === 'config.toml')))) {
204
- files.add(await realpath(path));
754
+ ((within === '.cargo' || within.endsWith('/.cargo')) &&
755
+ (entry.name === 'config' || entry.name === 'config.toml')))) {
756
+ includeFile(await realpath(path), inputKey(owner, 'file', localPath));
757
+ }
758
+ }
759
+ }
760
+ for (const [directory, owner] of directories)
761
+ await walk(directory, owner, '');
762
+ const compiledCache = new Map();
763
+ for (const [directory, owner] of directories) {
764
+ for (const input of compiledInFiles(directory, compiledCache)) {
765
+ if (!ignored(input.file)) {
766
+ includeFile(await realpath(input.file), inputKey(owner, 'include', relative(directory, input.source) + '\0' + input.literal));
205
767
  }
206
768
  }
207
769
  }
208
- for (const directory of directories)
209
- await walk(directory);
210
770
  const hash = createHash('sha256');
211
- hash.update('cargo-path-inputs-v1\0');
212
- for (const [path, target] of [...links].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
213
- hash.update(relative(root, path));
771
+ hash.update('cargo-path-inputs-v2\0');
772
+ for (const { key, target } of [...links.values()].sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0)) {
773
+ hash.update(key);
214
774
  hash.update('\0symlink\0');
215
775
  hash.update(target);
216
776
  hash.update('\0');
217
777
  }
218
- for (const file of [...files].sort()) {
778
+ for (const [file, key] of [...files].sort((left, right) => (left[1] < right[1] ? -1 : left[1] > right[1] ? 1 : 0))) {
219
779
  const bytes = await readFile(file);
220
- // Both names and bytes matter: moving a module can change resolution even
221
- // when its contents are unchanged. Length framing makes boundaries unique.
222
- hash.update(relative(root, file));
780
+ hash.update(key);
223
781
  hash.update('\0');
224
782
  hash.update(String(bytes.length));
225
783
  hash.update('\0');
@@ -279,6 +837,7 @@ function gitIgnoredBeneath(directories) {
279
837
  continue;
280
838
  const installed = [...ignoredRoots].map((member) => join(repository, member));
281
839
  const listing = execFileSync('git', [
840
+ ...ISOLATED_GIT_ARGS,
282
841
  '--literal-pathspecs',
283
842
  '-C',
284
843
  repository,
@@ -290,7 +849,7 @@ function gitIgnoredBeneath(directories) {
290
849
  '--directory',
291
850
  '--',
292
851
  ...sourceRoots,
293
- ], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: CHILD_STDIO });
852
+ ], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: CHILD_STDIO, env: isolatedGitEnv() });
294
853
  for (const entry of listing.split('\0')) {
295
854
  if (entry.length === 0)
296
855
  continue;
@@ -308,10 +867,11 @@ function gitIgnoredBeneath(directories) {
308
867
  }
309
868
  /** The members of `paths` (relative to `repository`) that git ignores, own patterns or an ancestor's. */
310
869
  function gitCheckIgnore(repository, paths) {
311
- const result = spawnSync('git', ['-C', repository, 'check-ignore', '-z', '--stdin'], {
870
+ const result = spawnSync('git', [...ISOLATED_GIT_ARGS, '-C', repository, 'check-ignore', '-z', '--stdin'], {
312
871
  input: `${paths.join('\0')}\0`,
313
872
  encoding: 'utf8',
314
873
  maxBuffer: 64 * 1024 * 1024,
874
+ env: isolatedGitEnv(),
315
875
  });
316
876
  // check-ignore answers 1 when nothing is ignored; only 0 carries a listing.
317
877
  if (result.status === 1)
@@ -325,9 +885,10 @@ function gitCheckIgnore(repository, paths) {
325
885
  function gitRepository(directory) {
326
886
  try {
327
887
  // The walk compares realpaths, so git's answer is canonicalized the same way.
328
- return realpathSync(execFileSync('git', ['-C', directory, 'rev-parse', '--show-toplevel'], {
888
+ return realpathSync(execFileSync('git', [...ISOLATED_GIT_ARGS, '-C', directory, 'rev-parse', '--show-toplevel'], {
329
889
  encoding: 'utf8',
330
890
  stdio: CHILD_STDIO,
891
+ env: isolatedGitEnv(),
331
892
  }).trim());
332
893
  }
333
894
  catch (error) {
@@ -341,3 +902,62 @@ function gitRepository(directory) {
341
902
  throw error;
342
903
  }
343
904
  }
905
+ // A tokenized literal macro, never text inside a comment or another string.
906
+ const INCLUDE_CLOSERS = { '(': ')', '[': ']', '{': '}' };
907
+ const INCLUDE_STRING = /^"([^"\\\r\n]*)"$/u;
908
+ const INCLUDE_RAW_STRING = /^r(#*)"([\s\S]*)"\1$/u;
909
+ /**
910
+ * Existing literal include_str!/include_bytes! files read by this package's Rust sources.
911
+ * One graph owns the memo; runtime hashes use a fresh memo. Nested packages own their
912
+ * sources separately. Computed paths and arbitrary build-script reads remain explicit inputs.
913
+ */
914
+ export function compiledInFiles(root, cache) {
915
+ const cached = cache.get(root);
916
+ if (cached !== undefined)
917
+ return cached;
918
+ const found = new Map();
919
+ const skipped = HASH_SKIPPED_DIRECTORIES;
920
+ const scan = [root];
921
+ while (scan.length > 0) {
922
+ const current = scan.pop();
923
+ if (current === undefined || !existsSync(current))
924
+ continue;
925
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
926
+ const child = join(current, entry.name);
927
+ if (entry.isDirectory()) {
928
+ if (!skipped.includes(entry.name) && !existsSync(join(child, 'Cargo.toml')))
929
+ scan.push(child);
930
+ }
931
+ else if (entry.isFile() && entry.name.endsWith('.rs')) {
932
+ const text = readFileSync(child, 'utf8');
933
+ if (!text.includes('include_'))
934
+ continue;
935
+ const tokens = rustTokens(text);
936
+ for (let index = 0; index < tokens.length; index += 1) {
937
+ if (tokens[index]?.text !== 'include_str' && tokens[index]?.text !== 'include_bytes')
938
+ continue;
939
+ if (tokens[index + 1]?.text !== '!')
940
+ continue;
941
+ const closing = INCLUDE_CLOSERS[tokens[index + 2]?.text ?? ''];
942
+ const end = tokens[index + 4]?.text === ',' ? index + 5 : index + 4;
943
+ if (closing === undefined || tokens[end]?.text !== closing)
944
+ continue;
945
+ const literal = tokens[index + 3]?.text ?? '';
946
+ const path = INCLUDE_STRING.exec(literal)?.[1] ?? INCLUDE_RAW_STRING.exec(literal)?.[2];
947
+ if (path === undefined || path === '')
948
+ continue;
949
+ const file = resolve(current, path);
950
+ if (statSync(file, { throwIfNoEntry: false })?.isFile()) {
951
+ const prior = found.get(file);
952
+ if (prior === undefined || child < prior.source || (child === prior.source && path < prior.literal)) {
953
+ found.set(file, { file, source: child, literal: path });
954
+ }
955
+ }
956
+ }
957
+ }
958
+ }
959
+ }
960
+ const files = [...found.values()].sort((left, right) => left.file < right.file ? -1 : left.file > right.file ? 1 : 0);
961
+ cache.set(root, files);
962
+ return files;
963
+ }