@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
@@ -10,8 +10,10 @@
10
10
  * script runs (measured on Bun 1.4.2), so no lifecycle script ever sees the
11
11
  * link. So each install smoo runs (shell entry's, a CI runner's
12
12
  * frozen-lockfile one, `smoo monorepo update`'s) records these links before
13
- * it installs and puts exactly those back afterwards. A plain `bun install`
14
- * still relinks them: only a wrapper around bun itself could intercept that.
13
+ * it installs and restores manual choices afterwards, except Nx (below).
14
+ * Recorded declarations follow their current target after a successful install.
15
+ * A plain `bun install` still relinks an undeclared link: only a wrapper around
16
+ * bun itself could intercept that. A declared one (below) comes back on its own.
15
17
  *
16
18
  * A developer link is a symlink directly inside a node_modules tree bun
17
19
  * installs (the root's or a workspace member's, scoped names included) whose
@@ -22,11 +24,65 @@
22
24
  * `globalStore`, each .bun entry is itself a link into the shared install
23
25
  * cache, outside every checkout.
24
26
  *
25
- * Nothing is recorded across installs, so the state is the filesystem itself:
26
- * unlinking a package means removing its link, and the next install puts the
27
- * lockfile's version there. A link whose target no longer exists is removed
28
- * before the install, with a warning, so that install puts the lockfile's
29
- * version in its place.
27
+ * Unlinking a package means removing its link, and the next install puts the
28
+ * lockfile's version there. A dangling link is removed before the install,
29
+ * with a warning. Links this owner creates for declarations also have a receipt
30
+ * in node_modules/.smoo-declared-links: their alias, declaration and exact link
31
+ * text. A changed declaration can replace that link only while its text still
32
+ * matches the receipt. Unrecorded links and manual retargets stay the developer's.
33
+ *
34
+ * An install that exists to replace links says which: `{ relink }` names the
35
+ * packages (`name` or `@scope/name`) it is meant to relink, in the root's
36
+ * tree and in every member's. When the install resolves, what it left at
37
+ * those names stays (a `bun link` run against providers a developer
38
+ * registered anew) and every other developer link is put back as before.
39
+ * When it rejects, every link is put back, the named ones included, so a
40
+ * failed relink changes nothing. A named package with no developer link when
41
+ * the install starts has nothing to put back, and a named link that dangled
42
+ * is removed first, as for any install.
43
+ *
44
+ * Nx is the one package every managed install relinks. The lockfile owns Nx, so
45
+ * a developer link to a local Nx checkout is not kept: the managed installs
46
+ * (shell entry's, a CI runner's frozen-lockfile one, `smoo monorepo update`'s)
47
+ * pass `{ relink: ['nx'] }`, and a successful one leaves Nx as Bun installed it.
48
+ * Other manual developer links are still kept. A live Nx link makes the install
49
+ * stamp stale (`hasStaleDeveloperLinks`), so the next managed install replaces
50
+ * it; an ordinary local setup invocation with current bindings then runs no
51
+ * `bun install`.
52
+ *
53
+ * A repository can also DECLARE such links, so every checkout of it on a
54
+ * developer machine gets them without anyone running `bun link`: the root
55
+ * package.json's `smoo.developerLinks` maps a package name to a relative
56
+ * directory. Contained targets belong to this checkout; genuine sibling
57
+ * targets are anchored at the project's main checkout (see `linkAnchor`).
58
+ * `applyDeclaredLinks` makes it so: in every node_modules tree that has the
59
+ * package installed, the entry becomes a link to that directory, unless a
60
+ * developer already pointed it at a checkout of their own. An existing real
61
+ * package payload requires explicit owner relocation, never deletion. A declared
62
+ * directory this machine does not have leaves the installed version, said so.
63
+ * CI never applies them: it builds against the published packages the
64
+ * lockfile names (setup-environment.ts `--links`).
65
+ *
66
+ * A declaration may also ask for a snapshot: `{ "directory": …, "snapshot":
67
+ * { "targets": [...], "artifactModules": [...] } }` binds every alias to a
68
+ * sealed copy of that checkout instead of the live directory, so the
69
+ * provider's own builds, lands and installs never change a file a running
70
+ * consumer task resolves (linked-snapshots.ts). The snapshot is taken here, at
71
+ * the install and shell-entry boundary, and only when the provider's Nx
72
+ * targets vouch for every copied byte; otherwise the refusal is said and the
73
+ * alias keeps its current binding.
74
+ *
75
+ * Declarations are applied at the end of every install. smoo's root script
76
+ * policy makes the root's `postinstall` run this file, and bun runs the
77
+ * root's lifecycle scripts after it has re-pointed the dependencies, an
78
+ * install with nothing to do included. Without it a plain `bun install` left
79
+ * the published package in place until the next shell entry, and a process
80
+ * started in that gap kept what it loaded: an Nx daemon ran the published
81
+ * plugin's sync generator for the rest of its life. Shell entry's `--links`
82
+ * task covers a tree that lost a link without an install, such as a clone
83
+ * made while it was missing. The postinstall takes no install lock: an
84
+ * install smoo runs holds that lock while bun runs the script, so waiting
85
+ * for it there would never end.
30
86
  *
31
87
  * Like secret-references.ts, this is a managed raw script: shell entry imports
32
88
  * it before anything is installed, and `smoo monorepo update` loads the copy
@@ -37,14 +93,22 @@
37
93
  import {
38
94
  type Dirent,
39
95
  existsSync,
96
+ lstatSync,
40
97
  mkdirSync,
98
+ mkdtempSync,
41
99
  readdirSync,
42
100
  readFileSync,
43
101
  readlinkSync,
102
+ realpathSync,
103
+ renameSync,
44
104
  rmSync,
105
+ statSync,
45
106
  symlinkSync,
107
+ writeFileSync,
46
108
  } from 'node:fs';
47
109
  import path from 'node:path';
110
+ import type { KeepDeveloperLinksOptions } from '@smoothbricks/nx-plugin/managed-assets';
111
+ import { type SnapshotDeclaration, snapshotBinding } from './linked-snapshots.ts';
48
112
 
49
113
  interface DeveloperLink {
50
114
  /** Where the link is, relative to the project root. */
@@ -59,25 +123,85 @@ interface DeveloperLinks {
59
123
  readonly dangling: readonly DeveloperLink[];
60
124
  }
61
125
 
126
+ interface DeclaredLinkReceipt extends DeveloperLink {
127
+ readonly declaration: string;
128
+ }
129
+
62
130
  /**
63
- * Runs `install` with every developer link under `root` kept. The links in
64
- * place when it starts are exactly the links in place when it settles,
65
- * whether it resolved or rejected, less those that already dangled. It then
66
- * names them as `reportDeveloperLinks` does.
131
+ * Runs `install` while preserving the developer links captured under `root`.
132
+ * On rejection every captured live link is restored, less links that already
133
+ * dangled; a resolved install keeps its selected `relink` replacements and
134
+ * the lockfile versions replacing undeclared links whose receipts still match.
135
+ * This is not a transaction over new entries created by the install. Relink
136
+ * intent reports the actual final link state on either outcome.
67
137
  */
68
- export async function keepDeveloperLinks<T>(root: string, install: () => Promise<T>): Promise<T> {
138
+ export async function keepDeveloperLinks<T>(
139
+ root: string,
140
+ install: () => Promise<T>,
141
+ options?: KeepDeveloperLinksOptions,
142
+ ): Promise<T> {
69
143
  const { live, dangling } = findDeveloperLinks(root);
144
+ const recorded = readDeclaredRecord(root);
145
+ const undeclared = new Set<string>();
146
+ if (recorded.size > 0) {
147
+ const declared = new Set<string>();
148
+ for (const { name } of readDeclaredLinks(root)) declared.add(name);
149
+ for (const link of live) {
150
+ if (recorded.get(link.path)?.target === link.target && !declared.has(packageName(link))) {
151
+ undeclared.add(link.path);
152
+ }
153
+ }
154
+ }
70
155
  for (const link of dangling) {
71
156
  rmSync(path.join(root, link.path), { force: true });
72
157
  console.error(`! removed developer link ${link.path}: its target ${resolvedTarget(root, link)} no longer exists`);
73
158
  }
159
+ // Only an install that resolved leaves the links it was meant to replace as
160
+ // it made them; a rejected one puts every captured live link back.
161
+ let replaced: readonly string[] | undefined;
162
+ let succeeded = false;
74
163
  try {
75
- return await install();
164
+ for (const entry of undeclared) {
165
+ rmSync(path.join(root, entry));
166
+ console.error(`! removed developer link ${entry}: smoo.developerLinks no longer declares its package`);
167
+ }
168
+ const result = await install();
169
+ replaced = options?.relink;
170
+ succeeded = true;
171
+ return result;
76
172
  } finally {
173
+ const restored = readDeclaredRecord(root);
77
174
  for (const link of live) {
175
+ if (succeeded && undeclared.has(link.path)) {
176
+ restored.delete(link.path);
177
+ continue;
178
+ }
179
+ if (replaced?.includes(packageName(link))) {
180
+ const at = path.join(root, link.path);
181
+ const receipt = restored.get(link.path);
182
+ // Keep the receipt postinstall wrote for the selected replacement,
183
+ // but never retain an old receipt for a different final binding.
184
+ if (!lstatSync(at, { throwIfNoEntry: false })?.isSymbolicLink() || readlinkSync(at) !== receipt?.target) {
185
+ restored.delete(link.path);
186
+ }
187
+ continue;
188
+ }
78
189
  restoreLink(root, link);
190
+ const receipt = recorded.get(link.path);
191
+ // The install's postinstall may have claimed this alias after Bun replaced
192
+ // it. Restoring a manual override must restore its lack of ownership too.
193
+ if (receipt?.target === link.target) restored.set(link.path, receipt);
194
+ else restored.delete(link.path);
195
+ }
196
+ writeDeclaredRecord(root, restored);
197
+ if (succeeded && recorded.size > 0 && process.env.GITHUB_ACTIONS !== 'true') {
198
+ applyDeclaredLinks(root, await planDeclaredLinks(root));
199
+ }
200
+ if (options !== undefined || (succeeded && undeclared.size > 0)) {
201
+ reportDeveloperLinks(root);
202
+ } else {
203
+ describeDeveloperLinks(root, live);
79
204
  }
80
- describeDeveloperLinks(root, live);
81
205
  }
82
206
  }
83
207
 
@@ -93,6 +217,20 @@ export function reportDeveloperLinks(root: string): void {
93
217
  describeDeveloperLinks(root, findDeveloperLinks(root).live);
94
218
  }
95
219
 
220
+ /**
221
+ * A stamped install is stale while a developer link dangles, or while a live one names a package in `relink`: that
222
+ * is a link the install must replace, so a matching stamp is not trusted.
223
+ */
224
+ export function hasStaleDeveloperLinks(root: string, relink: readonly string[] = []): boolean {
225
+ const { live, dangling } = findDeveloperLinks(root);
226
+ return dangling.length > 0 || live.some((link) => relink.includes(packageName(link)));
227
+ }
228
+
229
+ /** The package a link stands for in its tree: `name` or `@scope/name`. */
230
+ function packageName(link: DeveloperLink): string {
231
+ return link.path.slice(link.path.lastIndexOf('node_modules/') + 'node_modules/'.length);
232
+ }
233
+
96
234
  /** A package linked from many members is named once, with its count. */
97
235
  function describeDeveloperLinks(root: string, links: readonly DeveloperLink[]): void {
98
236
  if (links.length === 0) {
@@ -100,8 +238,7 @@ function describeDeveloperLinks(root: string, links: readonly DeveloperLink[]):
100
238
  }
101
239
  const counts = new Map<string, number>();
102
240
  for (const link of links) {
103
- const name = link.path.slice(link.path.lastIndexOf('node_modules/') + 'node_modules/'.length);
104
- const named = `${name} -> ${resolvedTarget(root, link)}`;
241
+ const named = `${packageName(link)} -> ${resolvedTarget(root, link)}`;
105
242
  counts.set(named, (counts.get(named) ?? 0) + 1);
106
243
  }
107
244
  const entries = [...counts].map(([named, count]) => (count === 1 ? named : `${named} (${count} links)`));
@@ -117,7 +254,7 @@ function findDeveloperLinks(root: string): DeveloperLinks {
117
254
  const target = resolvedTarget(root, link);
118
255
  const relative = path.relative(root, target);
119
256
  if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
120
- (existsSync(target) ? live : dangling).push(link);
257
+ (statSync(target, { throwIfNoEntry: false }) === undefined ? dangling : live).push(link);
121
258
  }
122
259
  }
123
260
  }
@@ -199,3 +336,456 @@ function restoreLink(root: string, link: DeveloperLink): void {
199
336
  mkdirSync(path.dirname(at), { recursive: true });
200
337
  symlinkSync(link.target, at);
201
338
  }
339
+
340
+ /** What a declaration binds its aliases to: the checkout it names, or a sealed snapshot of it. */
341
+ export type DeclaredBinding =
342
+ | { readonly kind: 'checkout'; readonly target: string }
343
+ | { readonly kind: 'snapshot'; readonly target: string; readonly id: string };
344
+
345
+ /** One tree entry a declaration wants pointed at its package's local checkout or its snapshot. */
346
+ export interface DeclaredLinkChange {
347
+ /** Where the entry is, relative to the project root. */
348
+ readonly path: string;
349
+ /** The absolute directory it should link to, and what that directory is. */
350
+ readonly binding: DeclaredBinding;
351
+ }
352
+
353
+ /**
354
+ * A declaration this machine cannot honour now: its checkout directory is not there to link to (the installed
355
+ * version stays), no snapshot of it can be made (whatever the alias binds now stays), or an alias still links the
356
+ * live checkout without a receipt, which a declaration never claims retroactively.
357
+ */
358
+ export type UnavailableDeclaredLink =
359
+ | { readonly kind: 'absent'; readonly name: string; readonly target: string; readonly reason: string }
360
+ | { readonly kind: 'snapshot-refused'; readonly name: string; readonly source: string; readonly reason: string }
361
+ | { readonly kind: 'snapshot-unclaimed'; readonly name: string; readonly path: string; readonly source: string };
362
+
363
+ export interface DeclaredLinksPlan {
364
+ readonly changes: readonly DeclaredLinkChange[];
365
+ readonly unavailable: readonly UnavailableDeclaredLink[];
366
+ }
367
+
368
+ /**
369
+ * What `smoo.developerLinks` asks of the trees under `root` that they do not
370
+ * already hold. An entry needs a change when the package is installed there
371
+ * (as the store link or directory bun made) and is not already a link to the
372
+ * declared directory, or for a snapshot declaration to its current snapshot.
373
+ * An entry a developer pointed at another checkout of their own stays theirs,
374
+ * and a tree without the package gains nothing: a declaration links what the
375
+ * manifests depend on, never adds a dependency. An unrecorded alias that links
376
+ * the live checkout a snapshot declaration names is reported, not claimed: an
377
+ * owner relinks it once (remove it, then install) to bind the snapshot.
378
+ * A contained declaration this checkout cannot honour throws rather than keep a
379
+ * binding it inherited from the main checkout, or reach through a redirected or
380
+ * escaping path. Resolving a snapshot may capture one (linked-snapshots.ts),
381
+ * which writes only the snapshot store.
382
+ */
383
+ export async function planDeclaredLinks(root: string): Promise<DeclaredLinksPlan> {
384
+ const declared = readDeclaredLinks(root);
385
+ if (declared.length === 0) {
386
+ return { changes: [], unavailable: [] };
387
+ }
388
+ const anchor = linkAnchor(root);
389
+ const canonicalRoot = realpathSync(root);
390
+ const trees = nodeModulesTrees(root);
391
+ const recorded = readDeclaredRecord(root);
392
+ const changes: DeclaredLinkChange[] = [];
393
+ const unavailable: UnavailableDeclaredLink[] = [];
394
+ for (const { name, directory: relative, snapshot } of declared) {
395
+ const source = declaredTarget(root, anchor, relative);
396
+ const contained = containsPath(path.resolve(root), source);
397
+ if (contained) {
398
+ assertOwnedPath(canonicalRoot, path.resolve(canonicalRoot, path.relative(path.resolve(root), source)));
399
+ }
400
+ const reason = unavailableReason(source);
401
+ if (reason !== null) {
402
+ if (contained) assertNoInheritedBinding(root, anchor, name, relative, source);
403
+ unavailable.push({ kind: 'absent', name, target: source, reason });
404
+ continue;
405
+ }
406
+ let binding: DeclaredBinding = { kind: 'checkout', target: source };
407
+ if (snapshot !== undefined) {
408
+ const outcome = await snapshotBinding(root, name, source, snapshot);
409
+ if (outcome.kind === 'refused') {
410
+ unavailable.push({ kind: 'snapshot-refused', name, source, reason: outcome.reason });
411
+ continue;
412
+ }
413
+ binding = { kind: 'snapshot', target: outcome.directory, id: outcome.id };
414
+ }
415
+ const target = binding.target;
416
+ // The live checkout a snapshot replaces, by physical identity: a link spelled through another path is the same one.
417
+ const sourcePhysical = binding.kind === 'snapshot' ? realpathSync(source) : undefined;
418
+ for (const tree of trees) {
419
+ const entry = path.join(tree, name);
420
+ const at = path.join(root, entry);
421
+ const stats = lstatSync(at, { throwIfNoEntry: false });
422
+ if (stats === undefined) {
423
+ continue;
424
+ }
425
+ if (stats.isSymbolicLink()) {
426
+ const text = readlinkSync(at);
427
+ const current = resolvedTarget(root, { path: entry, target: text });
428
+ const foreign = !containsPath(path.resolve(root), current);
429
+ // Any contained main-project binding inherited by this clone belongs to
430
+ // the declaration, even if the old producer used a different directory.
431
+ // A receipt proves an earlier managed sibling binding; an unrecorded
432
+ // sibling or a manual retarget remains the developer's own choice.
433
+ const inherited = inheritedContainedBinding(anchor, relative, current);
434
+ const managed = recorded.get(entry)?.target === text;
435
+ if (current === target && text === packageAliasTarget(root, at, target)) continue;
436
+ const physical = sourcePhysical === undefined ? undefined : realpathOrNull(current);
437
+ if (binding.kind === 'snapshot' && foreign && !inherited && !managed && physical === sourcePhysical) {
438
+ unavailable.push({ kind: 'snapshot-unclaimed', name, path: entry, source });
439
+ continue;
440
+ }
441
+ if (foreign && !inherited && !managed && current !== target) continue;
442
+ }
443
+ changes.push({ path: entry, binding });
444
+ }
445
+ }
446
+ return { changes, unavailable };
447
+ }
448
+
449
+ /**
450
+ * A contained declaration whose directory is absent here must not keep the binding it inherited from the
451
+ * main checkout: restoring it is this checkout's job, never a borrowed sibling's.
452
+ */
453
+ function assertNoInheritedBinding(root: string, anchor: string, name: string, relative: string, target: string): void {
454
+ for (const tree of nodeModulesTrees(root)) {
455
+ const entry = path.join(tree, name);
456
+ const at = path.join(root, entry);
457
+ if (!lstatSync(at, { throwIfNoEntry: false })?.isSymbolicLink()) continue;
458
+ const current = resolvedTarget(root, { path: entry, target: readlinkSync(at) });
459
+ if (!containsPath(path.resolve(root), current) && inheritedContainedBinding(anchor, relative, current)) {
460
+ throw new Error(
461
+ `contained declared package ${name} is missing at ${target}; restore it in this checkout, never borrow the main checkout's package`,
462
+ );
463
+ }
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Makes `plan`'s changes and says what it linked, once per package, and
469
+ * which declarations this machine cannot honour.
470
+ */
471
+ export function applyDeclaredLinks(root: string, plan: DeclaredLinksPlan): void {
472
+ for (const unavailable of plan.unavailable) {
473
+ switch (unavailable.kind) {
474
+ case 'absent':
475
+ console.error(
476
+ `! smoo.developerLinks ${unavailable.name}: ${unavailable.target} ${unavailable.reason}; the installed version stays`,
477
+ );
478
+ break;
479
+ case 'snapshot-refused':
480
+ console.error(
481
+ `! smoo.developerLinks ${unavailable.name}: no snapshot of ${unavailable.source}: ${unavailable.reason}; its current binding stays`,
482
+ );
483
+ break;
484
+ case 'snapshot-unclaimed':
485
+ console.error(
486
+ `! smoo.developerLinks ${unavailable.name}: ${unavailable.path} links the live checkout ${unavailable.source} without a receipt, so it is not bound to a snapshot; remove that link and run the install once to bind it`,
487
+ );
488
+ break;
489
+ }
490
+ }
491
+ if (plan.changes.length === 0) return;
492
+ const declared = new Map(readDeclaredLinks(root).map((link) => [link.name, link.directory]));
493
+ const recorded = readDeclaredRecord(root);
494
+ const counts = new Map<string, number>();
495
+ for (const change of plan.changes) {
496
+ const name = packageName(change);
497
+ const declaration = declared.get(name);
498
+ if (declaration === undefined) throw new Error(`cannot apply an undeclared developer link: ${name}`);
499
+ const at = path.join(root, change.path);
500
+ replacePackageAlias(root, at, change.binding.target);
501
+ recorded.set(change.path, { path: change.path, declaration, target: readlinkSync(at) });
502
+ writeDeclaredRecord(root, recorded);
503
+ const named =
504
+ change.binding.kind === 'snapshot'
505
+ ? `${name} -> snapshot ${change.binding.id} (${change.binding.target})`
506
+ : `${name} -> ${change.binding.target}`;
507
+ counts.set(named, (counts.get(named) ?? 0) + 1);
508
+ }
509
+ if (counts.size > 0) {
510
+ const entries = [...counts].map(([named, count]) => (count === 1 ? named : `${named} (${count} links)`));
511
+ console.error(`linked declared packages to local checkouts: ${entries.join(', ')}`);
512
+ }
513
+ }
514
+
515
+ /** One stderr line per declaration this machine cannot honour; the installed version stays. */
516
+ export function reportUnavailableDeclaredLinks(unavailable: readonly UnavailableDeclaredLink[]): void {
517
+ for (const { name, target, reason } of unavailable) {
518
+ console.error(`! smoo.developerLinks ${name}: ${target} ${reason}; the installed version stays`);
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Whether `current` is a binding this clone inherited from the main checkout its marker names: the
524
+ * declaration is contained in that checkout and the link's target lies inside it, at whatever relative
525
+ * path the older producer used.
526
+ */
527
+ function inheritedContainedBinding(anchor: string, relative: string, current: string): boolean {
528
+ const shared = path.resolve(anchor, relative);
529
+ const inside = path.relative(anchor, shared);
530
+ if (inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) return false;
531
+ return containsPath(path.resolve(anchor), path.resolve(current));
532
+ }
533
+
534
+ function containsPath(root: string, candidate: string): boolean {
535
+ const relative = path.relative(root, candidate);
536
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
537
+ }
538
+
539
+ /** Existing ancestors must be real owned directories, not redirected namespaces. */
540
+ function assertOwnedPath(root: string, candidate: string): void {
541
+ if (!containsPath(root, candidate)) throw new Error(`owned path escapes its owning checkout: ${candidate}`);
542
+ let existing = candidate;
543
+ while (true) {
544
+ try {
545
+ if (realpathSync(existing) !== existing) throw new Error(`path redirects its owned namespace: ${candidate}`);
546
+ return;
547
+ } catch (error) {
548
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
549
+ if (lstatSync(existing, { throwIfNoEntry: false })?.isSymbolicLink())
550
+ throw new Error(`path has a dangling redirected namespace: ${candidate}`);
551
+ const parent = path.dirname(existing);
552
+ if (parent === existing) throw error;
553
+ existing = parent;
554
+ }
555
+ }
556
+ }
557
+
558
+ function refuseLegacyPackage(alias: string): void {
559
+ const state = lstatSync(alias, { throwIfNoEntry: false });
560
+ if (state !== undefined && !state.isSymbolicLink())
561
+ throw new Error(
562
+ `refuse to replace live non-link package ${alias}; its owning checkout must relocate this legacy directory to a distinct retained path while its CLI/daemon is inactive, then run the developer-links task again`,
563
+ );
564
+ }
565
+
566
+ /** Rename replaces only the owned alias, never either target package. */
567
+ function replacePackageAlias(root: string, alias: string, target: string): void {
568
+ const canonicalRoot = realpathSync(root);
569
+ const ownedAlias = path.resolve(canonicalRoot, path.relative(path.resolve(root), path.resolve(alias)));
570
+ assertOwnedPath(canonicalRoot, path.dirname(ownedAlias));
571
+ refuseLegacyPackage(ownedAlias);
572
+ mkdirSync(path.dirname(ownedAlias), { recursive: true });
573
+ const scratch = mkdtempSync(path.join(path.dirname(ownedAlias), '.activation-'));
574
+ try {
575
+ const temporary = path.join(scratch, 'link');
576
+ symlinkSync(packageAliasTarget(root, alias, target), temporary, 'dir');
577
+ renameSync(temporary, ownedAlias);
578
+ } finally {
579
+ rmSync(scratch, { recursive: true, force: true });
580
+ }
581
+ }
582
+
583
+ /** Owned namespace aliases relocate with a checkout; genuine host/sibling bindings do not. */
584
+ function packageAliasTarget(root: string, alias: string, target: string): string {
585
+ return containsPath(path.resolve(root), path.resolve(target)) ? path.relative(path.dirname(alias), target) : target;
586
+ }
587
+
588
+ /** Why `target` cannot be linked to, or null when it is a package directory this process can reach. */
589
+ function unavailableReason(target: string): string | null {
590
+ try {
591
+ if (!statSync(target).isDirectory()) return 'is not a directory';
592
+ return existsSync(path.join(target, 'package.json')) ? null : 'has no package.json here';
593
+ } catch (error) {
594
+ if (error instanceof Error && 'code' in error) {
595
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
596
+ return 'does not exist on this machine';
597
+ }
598
+ if (error.code === 'EACCES' || error.code === 'EPERM') {
599
+ return 'cannot be read here';
600
+ }
601
+ }
602
+ throw error;
603
+ }
604
+ }
605
+
606
+ /** A package name as npm spells one: `name` or `@scope/name`, one segment each. */
607
+ const PACKAGE_NAME = /^(?:@[A-Za-z0-9_-][A-Za-z0-9._-]*\/)?[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
608
+
609
+ /** An Nx task target as a declaration names one: `project:target`, optionally `:configuration`. */
610
+ const TARGET = /^[^:\s]+:[^:\s]+(?::[^:\s]+)?$/;
611
+
612
+ /** One `smoo.developerLinks` declaration: its package, its checkout directory, and whether aliases bind a snapshot. */
613
+ interface DeclaredLink {
614
+ readonly name: string;
615
+ readonly directory: string;
616
+ readonly snapshot: SnapshotDeclaration | undefined;
617
+ }
618
+
619
+ /**
620
+ * `smoo.developerLinks` from the root manifest: each package name with its
621
+ * checkout directory, relative, given alone or as `{ directory, snapshot }`
622
+ * where `snapshot` names the provider targets that build it and its native
623
+ * artifact modules (linked-snapshots.ts). Hand-validated, like
624
+ * secret-references.ts validates `smoo.secrets`: this runs before anything is
625
+ * installed. The shape is `PackageSmooConfig.developerLinks` in the
626
+ * nx-plugin's workspace-manifest.ts.
627
+ */
628
+ function readDeclaredLinks(root: string): DeclaredLink[] {
629
+ const manifestPath = path.join(root, 'package.json');
630
+ const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf8'));
631
+ const smoo = typeof manifest === 'object' && manifest !== null ? Reflect.get(manifest, 'smoo') : undefined;
632
+ const declared = typeof smoo === 'object' && smoo !== null ? Reflect.get(smoo, 'developerLinks') : undefined;
633
+ if (declared === undefined) {
634
+ return [];
635
+ }
636
+ if (typeof declared !== 'object' || declared === null || Array.isArray(declared)) {
637
+ throw new Error(`${manifestPath}: smoo.developerLinks must map package names to checkout directories`);
638
+ }
639
+ return Object.entries(declared).map(([name, declaration]): DeclaredLink => {
640
+ if (!PACKAGE_NAME.test(name)) {
641
+ throw new Error(`${manifestPath}: smoo.developerLinks key ${JSON.stringify(name)} is not a package name`);
642
+ }
643
+ if (name === 'nx') {
644
+ throw new Error(
645
+ `${manifestPath}: smoo.developerLinks.nx is obsolete: the consumer lockfile and patch own Nx; run smoo monorepo update`,
646
+ );
647
+ }
648
+ const object = typeof declaration === 'object' && declaration !== null && !Array.isArray(declaration);
649
+ const directory: unknown = object ? Reflect.get(declaration, 'directory') : declaration;
650
+ if (typeof directory !== 'string' || directory.length === 0 || path.isAbsolute(directory)) {
651
+ throw new Error(
652
+ `${manifestPath}: smoo.developerLinks ${name} must be a directory relative to the main checkout, not ${JSON.stringify(directory)}`,
653
+ );
654
+ }
655
+ if (!object) return { name, directory, snapshot: undefined };
656
+ const snapshot: unknown = Reflect.get(declaration, 'snapshot');
657
+ const targets: unknown =
658
+ typeof snapshot === 'object' && snapshot !== null ? Reflect.get(snapshot, 'targets') : undefined;
659
+ const artifactModules: unknown =
660
+ typeof snapshot === 'object' && snapshot !== null ? Reflect.get(snapshot, 'artifactModules') : undefined;
661
+ if (
662
+ !Array.isArray(targets) ||
663
+ targets.length === 0 ||
664
+ !targets.every((target): target is string => typeof target === 'string' && TARGET.test(target)) ||
665
+ !Array.isArray(artifactModules) ||
666
+ !artifactModules.every((module): module is string => typeof module === 'string' && module.startsWith(`${name}/`))
667
+ ) {
668
+ throw new Error(
669
+ `${manifestPath}: smoo.developerLinks ${name}.snapshot must name its provider targets ("project:target") and the ${name}/… modules that resolve its native artifacts`,
670
+ );
671
+ }
672
+ return { name, directory, snapshot: { targets, artifactModules } };
673
+ });
674
+ }
675
+
676
+ /** Project-contained declared directories follow their checkout; siblings retain the shared main anchor. */
677
+ function declaredTarget(root: string, anchor: string, relative: string): string {
678
+ const shared = path.resolve(anchor, relative);
679
+ const inside = path.relative(anchor, shared);
680
+ if (inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) return shared;
681
+ const candidate = path.resolve(root, inside);
682
+ const canonicalRoot = realpathSync(root);
683
+ let existing = candidate;
684
+ while (true) {
685
+ try {
686
+ const physical = path.relative(canonicalRoot, realpathSync(existing));
687
+ if (physical === '..' || physical.startsWith(`..${path.sep}`) || path.isAbsolute(physical)) {
688
+ throw new Error(`contained declared directory escapes its owning checkout: ${candidate}`);
689
+ }
690
+ return candidate;
691
+ } catch (error) {
692
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
693
+ const parent = path.dirname(existing);
694
+ if (parent === existing) throw error;
695
+ existing = parent;
696
+ }
697
+ }
698
+ }
699
+
700
+ /**
701
+ * The stable anchor for genuine sibling directories is the project's main checkout.
702
+ * A cowshed marker names it without reading main's tree. Contained declared
703
+ * directories are projected into the current checkout by `declaredTarget`, with
704
+ * physical containment checked against symlink escapes.
705
+ */
706
+ function linkAnchor(root: string): string {
707
+ let marker: unknown;
708
+ try {
709
+ marker = JSON.parse(readFileSync(path.join(root, '.cowshed', 'workspace.json'), 'utf8'));
710
+ } catch (error) {
711
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
712
+ return root;
713
+ }
714
+ throw error;
715
+ }
716
+ const projectRoot = typeof marker === 'object' && marker !== null ? Reflect.get(marker, 'projectRoot') : undefined;
717
+ return typeof projectRoot === 'string' && path.isAbsolute(projectRoot) ? projectRoot : root;
718
+ }
719
+
720
+ /** Ownership is the link text we wrote, not merely an alias path we once used. */
721
+ const DECLARED_RECORD = path.join('node_modules', '.smoo-declared-links');
722
+
723
+ function readDeclaredRecord(root: string): Map<string, DeclaredLinkReceipt> {
724
+ const file = path.join(root, DECLARED_RECORD);
725
+ let input: unknown;
726
+ try {
727
+ input = JSON.parse(readFileSync(file, 'utf8'));
728
+ } catch (error) {
729
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return new Map();
730
+ throw error;
731
+ }
732
+ // This raw bootstrap script runs before packages or Typia transforms exist,
733
+ // like readDeclaredLinks. Malformed ownership is never treated as none.
734
+ if (!Array.isArray(input)) throw new Error(`${file}: expected declared-link receipts`);
735
+ const recorded = new Map<string, DeclaredLinkReceipt>();
736
+ for (const row of input) {
737
+ if (typeof row !== 'object' || row === null) throw new Error(`${file}: invalid declared-link receipt`);
738
+ const entry: unknown = Reflect.get(row, 'path');
739
+ const declaration: unknown = Reflect.get(row, 'declaration');
740
+ const target: unknown = Reflect.get(row, 'target');
741
+ if (typeof entry !== 'string' || typeof declaration !== 'string' || typeof target !== 'string') {
742
+ throw new Error(`${file}: a receipt needs string path, declaration and target fields`);
743
+ }
744
+ if (recorded.has(entry)) throw new Error(`${file}: duplicate declared-link receipt for ${entry}`);
745
+ recorded.set(entry, { path: entry, declaration, target });
746
+ }
747
+ return recorded;
748
+ }
749
+
750
+ /** Stable, atomic receipts relocate with node_modules and leave unchanged trees read-only. */
751
+ function writeDeclaredRecord(root: string, recorded: ReadonlyMap<string, DeclaredLinkReceipt>): void {
752
+ const file = path.join(root, DECLARED_RECORD);
753
+ const content = `${JSON.stringify([...recorded.values()].sort((a, b) => a.path.localeCompare(b.path)))}\n`;
754
+ try {
755
+ if (readFileSync(file, 'utf8') === content) return;
756
+ } catch (error) {
757
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
758
+ if (recorded.size === 0) return;
759
+ }
760
+ const canonicalRoot = realpathSync(root);
761
+ const owned = path.join(canonicalRoot, DECLARED_RECORD);
762
+ assertOwnedPath(canonicalRoot, path.dirname(owned));
763
+ const scratch = mkdtempSync(path.join(path.dirname(owned), '.declared-links-'));
764
+ try {
765
+ const temporary = path.join(scratch, 'record');
766
+ writeFileSync(temporary, content);
767
+ renameSync(temporary, owned);
768
+ } finally {
769
+ rmSync(scratch, { recursive: true, force: true });
770
+ }
771
+ }
772
+
773
+ /**
774
+ * The root package's `postinstall`, `bun tooling/direnv/developer-links.ts`.
775
+ * Bun runs it in the root it installed, so that root is the working
776
+ * directory. A CI runner links nothing, as for setup-environment.ts `--links`.
777
+ */
778
+ if (import.meta.main && process.env.GITHUB_ACTIONS !== 'true') {
779
+ const root = process.cwd();
780
+ applyDeclaredLinks(root, await planDeclaredLinks(root));
781
+ }
782
+
783
+ /** Where `at` physically resolves, or null when nothing is there. */
784
+ function realpathOrNull(at: string): string | null {
785
+ try {
786
+ return realpathSync(at);
787
+ } catch (error) {
788
+ if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return null;
789
+ throw error;
790
+ }
791
+ }