@cnc-tools/storm 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/dist/bin/storm.js +7 -12
  2. package/dist/build-info.js +1 -1
  3. package/dist/chunks/chunk-2NZXL6OH.js +62 -0
  4. package/dist/chunks/{chunk-3ZZVZPMG.js → chunk-43MWZLJR.js} +1 -1
  5. package/dist/chunks/{chunk-NPPJ57W7.js → chunk-5UMJNVKT.js} +498 -215
  6. package/dist/chunks/{chunk-KR7WIYLG.js → chunk-6EQKA7LI.js} +200 -985
  7. package/dist/chunks/{chunk-4EU4AH7E.js → chunk-AX4EQZUS.js} +186 -144
  8. package/dist/chunks/{chunk-ETCZ6WP7.js → chunk-BW2ADH7U.js} +1 -1
  9. package/dist/chunks/chunk-DOFB2ACU.js +49 -0
  10. package/dist/chunks/chunk-EGNP3S6C.js +161 -0
  11. package/dist/chunks/chunk-GQIL3AHY.js +20 -0
  12. package/dist/chunks/{chunk-ICB4BZJX.js → chunk-GSC6SRTW.js} +7 -2
  13. package/dist/chunks/{chunk-OJOKQRM6.js → chunk-IYM44FUX.js} +30 -26
  14. package/dist/chunks/{chunk-GRMD7G4J.js → chunk-LQKNI3EG.js} +6 -5
  15. package/dist/chunks/chunk-N7E6DAUE.js +40 -0
  16. package/dist/chunks/chunk-NMVODY3P.js +19 -0
  17. package/dist/chunks/{chunk-TRFEAYNC.js → chunk-Q4TKRILH.js} +261 -354
  18. package/dist/chunks/{chunk-VZZTHCBW.js → chunk-RTILVSYQ.js} +5 -18
  19. package/dist/chunks/{chunk-L4ZPMSKQ.js → chunk-T6AZIDZD.js} +43 -363
  20. package/dist/chunks/chunk-X4WBJIOF.js +308 -0
  21. package/dist/chunks/chunk-YGS5VRQT.js +794 -0
  22. package/dist/chunks/{chunk-4PRAB24Y.js → chunk-YM6TZV4L.js} +394 -396
  23. package/dist/chunks/{chunk-AMTYHUYB.js → chunk-YT5OROR7.js} +22 -8
  24. package/dist/chunks/{chunk-O4BUT7BE.js → chunk-ZDJLKF2G.js} +1625 -1583
  25. package/dist/chunks/{live-app-LOGYUBKB.js → live-app-QFHS54SX.js} +25 -46
  26. package/dist/command-tree.d.ts +4 -1
  27. package/dist/command-tree.js +4 -1
  28. package/dist/commands/exec/cleanup.js +4 -4
  29. package/dist/commands/exec/command.d.ts +6 -55
  30. package/dist/commands/exec/command.js +51 -46
  31. package/dist/commands/exec/define-run-command.d.ts +664 -0
  32. package/dist/commands/exec/define-run-command.js +58 -0
  33. package/dist/commands/exec/driver-plan.d.ts +30 -0
  34. package/dist/commands/exec/driver-plan.js +44 -0
  35. package/dist/commands/exec/driver-refusals.d.ts +89 -0
  36. package/dist/commands/exec/driver-refusals.js +65 -0
  37. package/dist/commands/exec/exec-words.d.ts +5 -0
  38. package/dist/commands/exec/exec-words.js +31 -0
  39. package/dist/commands/exec/live-view.js +68 -42
  40. package/dist/commands/exec/mint-failed.js +4 -4
  41. package/dist/commands/exec/outcomes.d.ts +6 -48
  42. package/dist/commands/exec/outcomes.js +10 -12
  43. package/dist/commands/exec/plan-run.js +3 -3
  44. package/dist/commands/exec/progress.d.ts +21 -17
  45. package/dist/commands/exec/progress.js +59 -78
  46. package/dist/commands/exec/resource-flags.d.ts +10 -3
  47. package/dist/commands/exec/resource-flags.js +25 -14
  48. package/dist/commands/exec/resource-refusals.d.ts +1 -1
  49. package/dist/commands/exec/resource-refusals.js +9 -9
  50. package/dist/commands/exec/run-bin.d.ts +35 -0
  51. package/dist/commands/exec/run-bin.js +32 -0
  52. package/dist/commands/exec/run-command.d.ts +64 -23
  53. package/dist/commands/exec/run-command.js +35 -94
  54. package/dist/commands/exec/run-metadata.d.ts +25 -19
  55. package/dist/commands/exec/run-metadata.js +34 -18
  56. package/dist/commands/exec/snapshot-text.d.ts +31 -0
  57. package/dist/commands/exec/snapshot-text.js +72 -0
  58. package/dist/commands/exec/test-plan.d.ts +2 -2
  59. package/dist/commands/exec/test-plan.js +11 -8
  60. package/dist/commands/exec/tests-summary.d.ts +21 -12
  61. package/dist/commands/exec/tests-summary.js +67 -39
  62. package/dist/commands/exec/text.d.ts +5 -0
  63. package/dist/commands/exec/text.js +7 -0
  64. package/dist/commands/exec/view.js +12 -13
  65. package/dist/commands/exec/waterfall.js +4 -4
  66. package/dist/commands/exec/worker-chart.d.ts +19 -11
  67. package/dist/commands/exec/worker-chart.js +66 -36
  68. package/dist/commands/playwright/command.d.ts +658 -0
  69. package/dist/commands/playwright/command.js +31 -0
  70. package/dist/commands/playwright/metadata.js +8 -0
  71. package/dist/commands/runs/facts.d.ts +5 -28
  72. package/dist/commands/runs/facts.js +11 -33
  73. package/dist/commands/runs/list/command.d.ts +4 -50
  74. package/dist/commands/runs/list/command.js +15 -11
  75. package/dist/commands/runs/list/outcomes.d.ts +2 -25
  76. package/dist/commands/runs/logs/command.js +13 -9
  77. package/dist/commands/runs/logs/outcomes.js +1 -1
  78. package/dist/commands/runs/show/command.d.ts +6 -50
  79. package/dist/commands/runs/show/command.js +37 -47
  80. package/dist/commands/runs/show/metadata.js +1 -1
  81. package/dist/commands/runs/show/outcomes.d.ts +3 -25
  82. package/dist/commands/runs/show/outcomes.js +18 -31
  83. package/dist/commands/snapshots/build/command.d.ts +501 -0
  84. package/dist/commands/snapshots/build/command.js +336 -0
  85. package/dist/commands/snapshots/build/metadata.d.ts +28 -0
  86. package/dist/commands/snapshots/build/metadata.js +37 -0
  87. package/dist/commands/snapshots/build/outcomes.d.ts +254 -0
  88. package/dist/commands/snapshots/build/outcomes.js +155 -0
  89. package/dist/commands/snapshots/list/command.d.ts +238 -0
  90. package/dist/commands/snapshots/list/command.js +269 -0
  91. package/dist/commands/snapshots/list/metadata.d.ts +16 -0
  92. package/dist/commands/snapshots/list/metadata.js +24 -0
  93. package/dist/commands/snapshots/list/outcomes.d.ts +148 -0
  94. package/dist/commands/snapshots/list/outcomes.js +217 -0
  95. package/dist/commands/snapshots/metadata.d.ts +3 -0
  96. package/dist/commands/snapshots/metadata.js +7 -0
  97. package/dist/commands/vitest/command.d.ts +185 -304
  98. package/dist/commands/vitest/command.js +23 -181
  99. package/dist/commands/vitest/metadata.js +1 -1
  100. package/dist/config-file/define.d.ts +1 -1
  101. package/dist/context.d.ts +32 -30
  102. package/dist/context.js +13 -17
  103. package/dist/core/before-run.d.ts +5 -5
  104. package/dist/core/before-run.js +8 -8
  105. package/dist/core/definition-lookup.d.ts +5 -5
  106. package/dist/core/definition-lookup.js +13 -12
  107. package/dist/core/drivers-of.d.ts +23 -0
  108. package/dist/core/drivers-of.js +13 -0
  109. package/dist/core/events.d.ts +6 -9
  110. package/dist/core/gateways.d.ts +32 -24
  111. package/dist/core/index.d.ts +7 -5
  112. package/dist/core/index.js +9 -6
  113. package/dist/core/launcher-context.d.ts +11 -0
  114. package/dist/core/launcher-context.js +31 -0
  115. package/dist/core/live/package-bin-gateway.d.ts +6 -0
  116. package/dist/core/live/package-bin-gateway.js +24 -0
  117. package/dist/core/package-bin.d.ts +7 -0
  118. package/dist/core/package-bin.js +30 -0
  119. package/dist/core/presentations.d.ts +1 -1
  120. package/dist/core/presentations.js +6 -5
  121. package/dist/core/{resource-registry.d.ts → resource-definition-set.d.ts} +15 -14
  122. package/dist/core/resource-definition-set.js +31 -0
  123. package/dist/core/resource-reports.d.ts +1 -1
  124. package/dist/core/resource-reports.js +16 -15
  125. package/dist/core/resource.d.ts +4 -4
  126. package/dist/core/resources.d.ts +6 -6
  127. package/dist/core/resources.js +11 -11
  128. package/dist/core/run-state.d.ts +20 -31
  129. package/dist/core/run-state.js +34 -25
  130. package/dist/core/run.d.ts +30 -32
  131. package/dist/core/run.js +33 -39
  132. package/dist/core/setup-phases.d.ts +14 -0
  133. package/dist/core/setup-phases.js +24 -0
  134. package/dist/core/state-directory.d.ts +2 -2
  135. package/dist/core/state-directory.js +3 -3
  136. package/dist/core/timeline.d.ts +4 -2
  137. package/dist/core/timeline.js +11 -5
  138. package/dist/extension-commands.js +6 -10
  139. package/dist/extensions/github/{world.d.ts → context.d.ts} +1 -1
  140. package/dist/extensions/github/context.js +3 -0
  141. package/dist/extensions/github/definition.d.ts +1 -1
  142. package/dist/extensions/github/definition.js +3 -3
  143. package/dist/extensions/github/extension.d.ts +1 -1
  144. package/dist/extensions/github/index.d.ts +2 -2
  145. package/dist/extensions/github/index.js +4 -4
  146. package/dist/extensions/github/lifecycle.d.ts +3 -3
  147. package/dist/extensions/github/lifecycle.js +14 -14
  148. package/dist/extensions/github/live/context.d.ts +6 -0
  149. package/dist/extensions/github/live/context.js +16 -0
  150. package/dist/extensions/github/resource.d.ts +1 -1
  151. package/dist/extensions/playwright/driver.d.ts +8 -0
  152. package/dist/extensions/playwright/driver.js +60 -0
  153. package/dist/extensions/playwright/extension.d.ts +2 -0
  154. package/dist/extensions/playwright/extension.js +12 -0
  155. package/dist/extensions/playwright/plan/gateways.d.ts +62 -0
  156. package/dist/extensions/playwright/plan/gateways.js +4 -0
  157. package/dist/extensions/playwright/plan/list-output.d.ts +26 -0
  158. package/dist/extensions/playwright/plan/list-output.js +101 -0
  159. package/dist/extensions/playwright/plan/live/list-gateway.d.ts +15 -0
  160. package/dist/extensions/playwright/plan/live/list-gateway.js +100 -0
  161. package/dist/extensions/playwright/plan/plan.d.ts +44 -0
  162. package/dist/extensions/playwright/plan/plan.js +53 -0
  163. package/dist/extensions/testserver/command-tree.d.ts +1 -1
  164. package/dist/extensions/testserver/command-tree.js +2 -2
  165. package/dist/extensions/testserver/commands/app.d.ts +7 -7
  166. package/dist/extensions/testserver/commands/pool/create/command.d.ts +5 -5
  167. package/dist/extensions/testserver/commands/pool/create/command.js +12 -13
  168. package/dist/extensions/testserver/commands/pool/list/command.js +5 -6
  169. package/dist/extensions/testserver/{world.d.ts → context.d.ts} +1 -1
  170. package/dist/extensions/testserver/context.js +4 -0
  171. package/dist/extensions/testserver/definition.d.ts +2 -2
  172. package/dist/extensions/testserver/definition.js +8 -7
  173. package/dist/extensions/testserver/events.d.ts +1 -1
  174. package/dist/extensions/testserver/extension.d.ts +4 -3
  175. package/dist/extensions/testserver/extension.js +33 -20
  176. package/dist/extensions/testserver/index.d.ts +2 -2
  177. package/dist/extensions/testserver/index.js +2 -2
  178. package/dist/extensions/testserver/lifecycle.d.ts +6 -5
  179. package/dist/extensions/testserver/lifecycle.js +9 -8
  180. package/dist/extensions/testserver/live/context.d.ts +8 -0
  181. package/dist/extensions/testserver/live/{world.js → context.js} +6 -7
  182. package/dist/extensions/testserver/options/rules.d.ts +3 -3
  183. package/dist/extensions/testserver/options/rules.js +5 -4
  184. package/dist/extensions/testserver/options/sandboxes.d.ts +3 -2
  185. package/dist/extensions/testserver/options/sandboxes.js +3 -2
  186. package/dist/extensions/testserver/playwright/index.d.ts +33 -0
  187. package/dist/extensions/testserver/playwright/index.js +43 -0
  188. package/dist/extensions/testserver/presentation.d.ts +4 -4
  189. package/dist/extensions/testserver/presentation.js +7 -7
  190. package/dist/extensions/testserver/progress.d.ts +3 -3
  191. package/dist/extensions/testserver/progress.js +3 -3
  192. package/dist/extensions/testserver/provision.d.ts +2 -2
  193. package/dist/extensions/testserver/provision.js +10 -10
  194. package/dist/extensions/testserver/resource.d.ts +2 -2
  195. package/dist/extensions/testserver/result.d.ts +2 -2
  196. package/dist/extensions/testserver/result.js +1 -1
  197. package/dist/extensions/testserver/run/connection.d.ts +1 -1
  198. package/dist/extensions/testserver/run/connection.js +3 -3
  199. package/dist/extensions/testserver/run/sandbox.d.ts +31 -0
  200. package/dist/extensions/testserver/run/sandbox.js +58 -0
  201. package/dist/extensions/testserver/run-sandbox.d.ts +2 -2
  202. package/dist/extensions/testserver/run-sandbox.js +3 -3
  203. package/dist/extensions/testserver/vercel-cli/arguments.d.ts +2 -2
  204. package/dist/extensions/testserver/vercel-cli/arguments.js +6 -6
  205. package/dist/extensions/testserver/vercel-cli/auth-config.d.ts +7 -7
  206. package/dist/extensions/testserver/vercel-cli/auth-config.js +4 -4
  207. package/dist/extensions/testserver/vercel-cli/clock.js +1 -1
  208. package/dist/extensions/testserver/vercel-cli/config-files.js +1 -1
  209. package/dist/extensions/testserver/vercel-cli/context.d.ts +1 -1
  210. package/dist/extensions/testserver/vercel-cli/context.js +2 -2
  211. package/dist/extensions/testserver/vercel-cli/entry.d.ts +1 -1
  212. package/dist/extensions/testserver/vercel-cli/entry.js +1 -1
  213. package/dist/extensions/testserver/vercel-cli/environment.d.ts +5 -5
  214. package/dist/extensions/testserver/vercel-cli/environment.js +6 -6
  215. package/dist/extensions/testserver/vercel-cli/gateways.d.ts +1 -1
  216. package/dist/extensions/testserver/vercel-cli/gateways.js +3 -3
  217. package/dist/extensions/testserver/vercel-cli/index.d.ts +1 -1
  218. package/dist/extensions/testserver/vercel-cli/index.js +8 -9
  219. package/dist/extensions/testserver/vercel-cli/invocation.d.ts +13 -12
  220. package/dist/extensions/testserver/vercel-cli/invocation.js +1 -1
  221. package/dist/extensions/testserver/vercel-cli/{driver.d.ts → invoker.d.ts} +18 -17
  222. package/dist/extensions/testserver/vercel-cli/{driver.js → invoker.js} +8 -8
  223. package/dist/extensions/testserver/vercel-cli/live/config-files.d.ts +2 -2
  224. package/dist/extensions/testserver/vercel-cli/live/config-files.js +2 -2
  225. package/dist/extensions/testserver/vercel-cli/live/process-gateway.js +1 -1
  226. package/dist/extensions/testserver/vercel-cli/report.js +2 -2
  227. package/dist/extensions/testserver/vercel-cli/verbose.js +1 -1
  228. package/dist/extensions/testserver/vitest/config.d.ts +3 -3
  229. package/dist/extensions/testserver/vitest/config.js +5 -13
  230. package/dist/extensions/testserver/vitest/container-scope.d.ts +11 -11
  231. package/dist/extensions/testserver/vitest/container-scope.js +9 -9
  232. package/dist/extensions/testserver/vitest/container-start.d.ts +6 -6
  233. package/dist/extensions/testserver/vitest/container-start.js +14 -11
  234. package/dist/extensions/testserver/vitest/diagnostics.d.ts +1 -1
  235. package/dist/extensions/testserver/vitest/fixtures.d.ts +11 -11
  236. package/dist/extensions/testserver/vitest/fixtures.js +14 -23
  237. package/dist/extensions/testserver/vitest/index.d.ts +1 -1
  238. package/dist/extensions/testserver/vitest/index.js +4 -4
  239. package/dist/extensions/testserver/vitest/types.d.ts +16 -18
  240. package/dist/extensions/testserver/vitest/types.js +2 -2
  241. package/dist/extensions/testserver/vitest/worker-sandbox.d.ts +8 -0
  242. package/dist/extensions/testserver/vitest/worker-sandbox.js +17 -0
  243. package/dist/extensions/vitest/driver.d.ts +8 -0
  244. package/dist/extensions/vitest/driver.js +62 -0
  245. package/dist/extensions/vitest/extension.d.ts +2 -0
  246. package/dist/extensions/vitest/extension.js +8 -0
  247. package/dist/{vitest → extensions/vitest/plan}/gateways.d.ts +1 -26
  248. package/dist/extensions/vitest/plan/gateways.js +3 -0
  249. package/dist/{vitest → extensions/vitest/plan}/live/list-gateway.d.ts +1 -2
  250. package/dist/{vitest → extensions/vitest/plan}/live/list-gateway.js +1 -20
  251. package/dist/extensions/vitest/plan/plan-over.d.ts +38 -0
  252. package/dist/extensions/vitest/plan/plan-over.js +31 -0
  253. package/dist/extensions/vitest/plan/plan.d.ts +24 -0
  254. package/dist/{vitest → extensions/vitest/plan}/plan.js +11 -26
  255. package/dist/extensions.d.ts +40 -18
  256. package/dist/extensions.js +49 -22
  257. package/dist/forward-sigterm.js +1 -1
  258. package/dist/launcher-resolvers/index.d.ts +1 -1
  259. package/dist/launcher-resolvers/local-services.d.ts +9 -44
  260. package/dist/launcher-resolvers/local-services.js +4 -5
  261. package/dist/live-app.js +7 -6
  262. package/dist/local-services.d.ts +7 -15
  263. package/dist/local-services.js +8 -29
  264. package/dist/playwright/index.d.ts +1 -0
  265. package/dist/playwright/index.js +4 -0
  266. package/dist/playwright/reporter.d.ts +96 -0
  267. package/dist/playwright/reporter.js +162 -0
  268. package/dist/playwright/worker-index.d.ts +7 -0
  269. package/dist/playwright/worker-index.js +20 -0
  270. package/dist/run-directory/index.d.ts +1 -1
  271. package/dist/run-directory/index.js +2 -3
  272. package/dist/run-directory/plan.d.ts +3 -3
  273. package/dist/run-directory/plan.js +5 -5
  274. package/dist/run-directory/reader.js +2 -2
  275. package/dist/run-directory/recording.d.ts +8 -5
  276. package/dist/run-directory/recording.js +6 -6
  277. package/dist/run-directory/run-collector.d.ts +5 -5
  278. package/dist/run-directory/run-collector.js +5 -5
  279. package/dist/run-directory/run-record.d.ts +17 -90
  280. package/dist/run-directory/run-record.js +15 -55
  281. package/dist/run-directory/timeline-facts.d.ts +2 -1
  282. package/dist/run-directory/timeline-facts.js +4 -2
  283. package/dist/runner/build-snapshots.d.ts +115 -0
  284. package/dist/runner/build-snapshots.js +146 -0
  285. package/dist/runner/context.js +2 -1
  286. package/dist/runner/events.d.ts +24 -69
  287. package/dist/runner/gateways.d.ts +20 -18
  288. package/dist/runner/index.d.ts +8 -7
  289. package/dist/runner/index.js +5 -3
  290. package/dist/runner/live/checkout-gateway.js +15 -7
  291. package/dist/runner/live/snapshot-records.js +7 -17
  292. package/dist/runner/prepare.d.ts +17 -50
  293. package/dist/runner/prepare.js +21 -25
  294. package/dist/runner/ready.d.ts +15 -11
  295. package/dist/runner/ready.js +32 -40
  296. package/dist/runner/recipe.d.ts +4 -18
  297. package/dist/runner/recipe.js +1 -13
  298. package/dist/runner/scope.d.ts +8 -32
  299. package/dist/runner/scope.js +4 -12
  300. package/dist/runner/secrets.d.ts +6 -0
  301. package/dist/runner/secrets.js +10 -0
  302. package/dist/runner/session.d.ts +19 -38
  303. package/dist/runner/session.js +16 -55
  304. package/dist/runner/snapshot-build.d.ts +21 -11
  305. package/dist/runner/snapshot-build.js +11 -16
  306. package/dist/runner/snapshot-cache.d.ts +98 -72
  307. package/dist/runner/snapshot-cache.js +69 -118
  308. package/dist/runner/snapshot-inspect.d.ts +85 -0
  309. package/dist/runner/snapshot-inspect.js +164 -0
  310. package/dist/runner/snapshot-key.d.ts +13 -15
  311. package/dist/runner/snapshot-key.js +15 -22
  312. package/dist/sdk/extension/commands.d.ts +35 -17
  313. package/dist/sdk/extension/commands.js +13 -11
  314. package/dist/sdk/extension/driver.d.ts +143 -0
  315. package/dist/sdk/extension/driver.js +28 -0
  316. package/dist/sdk/extension/index.d.ts +2 -1
  317. package/dist/sdk/extension/index.js +15 -9
  318. package/dist/sdk/extension/{launcher-supplies.d.ts → launcher-context.d.ts} +3 -3
  319. package/dist/sdk/extension/launcher-context.js +5 -0
  320. package/dist/sdk/extension/lifecycle.d.ts +6 -5
  321. package/dist/sdk/extension/lifecycle.js +2 -2
  322. package/dist/sdk/extension/resource-definition.d.ts +13 -13
  323. package/dist/sdk/extension/resource-definition.js +2 -2
  324. package/dist/sdk/extension/resource.d.ts +13 -13
  325. package/dist/sdk/extension/resource.js +11 -11
  326. package/dist/sdk/extension/time.js +2 -2
  327. package/dist/sdk/index.d.ts +2 -0
  328. package/dist/sdk/index.js +3 -1
  329. package/dist/sdk/run/launcher.d.ts +1 -1
  330. package/dist/sdk/run/launcher.js +4 -3
  331. package/dist/sdk/run/payload.js +1 -1
  332. package/dist/sdk/run/test-events.d.ts +24 -18
  333. package/dist/sdk/run/test-events.js +5 -4
  334. package/dist/sdk/run/test-result-writer.d.ts +77 -0
  335. package/dist/sdk/run/test-result-writer.js +143 -0
  336. package/dist/sdk/run/worker-test-event-writer.d.ts +13 -0
  337. package/dist/sdk/run/worker-test-event-writer.js +31 -0
  338. package/dist/vendor/testserver-sdk/container/container.d.ts +1 -6
  339. package/dist/vendor/testserver-sdk/container/container.js +1 -5
  340. package/dist/vendor/testserver-sdk/factories/build.d.ts +12 -40
  341. package/dist/vendor/testserver-sdk/factories/build.js +15 -66
  342. package/dist/vendor/testserver-sdk/factories/gateways.d.ts +1 -2
  343. package/dist/vendor/testserver-sdk/factories/index.d.ts +1 -3
  344. package/dist/vendor/testserver-sdk/factories/index.js +3 -5
  345. package/dist/vendor/testserver-sdk/index.d.ts +1 -2
  346. package/dist/vendor/testserver-sdk/index.js +5 -6
  347. package/dist/vendor/testserver-sdk/records/body.d.ts +1 -1
  348. package/dist/vendor/testserver-sdk/records/body.js +1 -1
  349. package/dist/vitest/index.d.ts +2 -1
  350. package/dist/vitest/index.js +6 -4
  351. package/dist/vitest/test-events.d.ts +6 -16
  352. package/dist/vitest/test-events.js +15 -40
  353. package/dist/vitest/test-results.d.ts +9 -31
  354. package/dist/vitest/test-results.js +34 -105
  355. package/dist/vitest/worker-index.d.ts +6 -0
  356. package/dist/vitest/worker-index.js +17 -0
  357. package/package.json +23 -9
  358. package/skills/overview.md +6 -8
  359. package/skills/read-run-output.md +21 -7
  360. package/dist/chunks/chunk-FVMQKYTT.js +0 -10
  361. package/dist/chunks/chunk-SLNKW4ZM.js +0 -40
  362. package/dist/chunks/chunk-WNIQA5J6.js +0 -19
  363. package/dist/chunks/chunk-WSIF7SR6.js +0 -10
  364. package/dist/commands/vitest/outcomes.d.ts +0 -379
  365. package/dist/commands/vitest/outcomes.js +0 -70
  366. package/dist/core/launcher-supplies.d.ts +0 -11
  367. package/dist/core/launcher-supplies.js +0 -28
  368. package/dist/core/live/terminal-command-gateway.d.ts +0 -8
  369. package/dist/core/live/terminal-command-gateway.js +0 -49
  370. package/dist/core/resource-registry.js +0 -30
  371. package/dist/extensions/github/live/world.d.ts +0 -6
  372. package/dist/extensions/github/live/world.js +0 -16
  373. package/dist/extensions/github/world.js +0 -3
  374. package/dist/extensions/story/command-tree.d.ts +0 -6
  375. package/dist/extensions/story/command-tree.js +0 -21
  376. package/dist/extensions/story/commands/app.d.ts +0 -23
  377. package/dist/extensions/story/commands/app.js +0 -5
  378. package/dist/extensions/story/commands/run/command.d.ts +0 -211
  379. package/dist/extensions/story/commands/run/command.js +0 -259
  380. package/dist/extensions/story/commands/run/metadata.js +0 -8
  381. package/dist/extensions/story/commands/run/outcomes.d.ts +0 -101
  382. package/dist/extensions/story/commands/run/outcomes.js +0 -73
  383. package/dist/extensions/story/commands/tree.d.ts +0 -2
  384. package/dist/extensions/story/commands/tree.js +0 -6
  385. package/dist/extensions/story/extension.d.ts +0 -2
  386. package/dist/extensions/story/extension.js +0 -8
  387. package/dist/extensions/testserver/live/world.d.ts +0 -8
  388. package/dist/extensions/testserver/vitest/sandbox.d.ts +0 -25
  389. package/dist/extensions/testserver/vitest/sandbox.js +0 -43
  390. package/dist/extensions/testserver/world.js +0 -4
  391. package/dist/runner/snapshot-save.d.ts +0 -56
  392. package/dist/runner/snapshot-save.js +0 -151
  393. package/dist/sdk/extension/launcher-supplies.js +0 -3
  394. package/dist/story/align.d.ts +0 -37
  395. package/dist/story/align.js +0 -39
  396. package/dist/story/command-line.d.ts +0 -24
  397. package/dist/story/command-line.js +0 -88
  398. package/dist/story/definition.d.ts +0 -59
  399. package/dist/story/definition.js +0 -9
  400. package/dist/story/diff.d.ts +0 -9
  401. package/dist/story/diff.js +0 -97
  402. package/dist/story/errors.d.ts +0 -14
  403. package/dist/story/errors.js +0 -21
  404. package/dist/story/gateways.d.ts +0 -94
  405. package/dist/story/gateways.js +0 -3
  406. package/dist/story/host.d.ts +0 -30
  407. package/dist/story/host.js +0 -97
  408. package/dist/story/index.d.ts +0 -8
  409. package/dist/story/index.js +0 -11
  410. package/dist/story/json.d.ts +0 -16
  411. package/dist/story/json.js +0 -59
  412. package/dist/story/launch.d.ts +0 -70
  413. package/dist/story/launch.js +0 -77
  414. package/dist/story/live/recording-gateway.d.ts +0 -2
  415. package/dist/story/live/recording-gateway.js +0 -103
  416. package/dist/story/orphans.d.ts +0 -35
  417. package/dist/story/orphans.js +0 -51
  418. package/dist/story/recording.d.ts +0 -62
  419. package/dist/story/recording.js +0 -97
  420. package/dist/story/report.d.ts +0 -42
  421. package/dist/story/report.js +0 -129
  422. package/dist/story/sequence.d.ts +0 -30
  423. package/dist/story/sequence.js +0 -74
  424. package/dist/story/settle.d.ts +0 -96
  425. package/dist/story/settle.js +0 -71
  426. package/dist/story/start.d.ts +0 -50
  427. package/dist/story/start.js +0 -183
  428. package/dist/vendor/testserver-sdk/factories/definition.d.ts +0 -39
  429. package/dist/vendor/testserver-sdk/factories/definition.js +0 -16
  430. package/dist/vendor/testserver-sdk/factories/definitions.d.ts +0 -169
  431. package/dist/vendor/testserver-sdk/factories/definitions.js +0 -245
  432. package/dist/vendor/testserver-sdk/seed/index.d.ts +0 -1
  433. package/dist/vendor/testserver-sdk/seed/index.js +0 -3
  434. package/dist/vendor/testserver-sdk/seed/seed.d.ts +0 -221
  435. package/dist/vendor/testserver-sdk/seed/seed.js +0 -171
  436. package/dist/vitest/find-vitest.d.ts +0 -7
  437. package/dist/vitest/find-vitest.js +0 -28
  438. package/dist/vitest/gateways.js +0 -4
  439. package/dist/vitest/plan.d.ts +0 -51
  440. /package/dist/{extensions/story/commands/run → commands/playwright}/metadata.d.ts +0 -0
  441. /package/dist/{vitest → extensions/vitest/plan}/list-output.d.ts +0 -0
  442. /package/dist/{vitest → extensions/vitest/plan}/list-output.js +0 -0
@@ -9,281 +9,316 @@ import {
9
9
  resourceCall,
10
10
  tokenRequestFailureFacts,
11
11
  tokenRequestFailureShape
12
- } from "./chunk-AMTYHUYB.js";
12
+ } from "./chunk-YT5OROR7.js";
13
13
  import {
14
14
  defineErrors,
15
15
  refused
16
- } from "./chunk-4PRAB24Y.js";
16
+ } from "./chunk-YM6TZV4L.js";
17
17
 
18
- // src/runner/live/user.ts
19
- import { userInfo } from "node:os";
20
- function localUserName() {
21
- try {
22
- return userInfo().username;
23
- } catch {
24
- return "unknown";
18
+ // src/config/credential-settle.ts
19
+ import { z } from "zod";
20
+ var credentialErrors = defineErrors({
21
+ missingTarget: {
22
+ exitCode: 2,
23
+ description: "The command may mint a credential, and neither a flag nor storm.config.ts names the control plane team or project.",
24
+ schema: z.object({
25
+ /** The settings no flag or config file gave. */
26
+ missing: z.array(z.enum(["scope", "project"]))
27
+ }),
28
+ render: ({ missing }) => ({
29
+ message: `No control plane ${missing.map((key) => key === "scope" ? "team" : "project").join(" or ")} to mint a credential for.`,
30
+ next: [
31
+ {
32
+ type: "text",
33
+ text: `Give ${missing.map((key) => `--${key}`).join(" and ")}, or set ${missing.join(" and ")} in storm.config.ts.`
34
+ }
35
+ ]
36
+ })
25
37
  }
38
+ });
39
+ function requireTarget(scope, project) {
40
+ if (scope === void 0 || project === void 0)
41
+ return refused(
42
+ credentialErrors.missingTarget({
43
+ missing: [
44
+ ...scope === void 0 ? ["scope"] : [],
45
+ ...project === void 0 ? ["project"] : []
46
+ ]
47
+ })
48
+ );
49
+ return { ok: true, target: { team: scope.value, project: project.value } };
26
50
  }
27
-
28
- // src/runner/events.ts
29
- function progressQueue(progress) {
30
- let pending = Promise.resolve();
31
- return {
32
- add(event) {
33
- pending = pending.then(() => progress.emit(event));
34
- },
35
- flush: () => pending
36
- };
51
+ function settleCredential(source, scope, project) {
52
+ if (source === "github-actions") return { ok: true, credential: { source } };
53
+ const required = requireTarget(scope, project);
54
+ if (!required.ok) return required;
55
+ return { ok: true, credential: { source, target: required.target } };
37
56
  }
38
57
 
39
- // src/runner/live/checkout-gateway.ts
40
- import { execFile, spawn } from "node:child_process";
41
-
42
- // src/runner/live/git-output.ts
43
- function splitNul(output) {
44
- const text = typeof output === "string" ? output : Buffer.from(output).toString("utf8");
45
- return text.split("\0").filter((entry) => entry.length > 0);
58
+ // src/runner/secrets.ts
59
+ var RUNNER_SECRET_MIN_LENGTH = 8;
60
+ function stepSecrets(values, names) {
61
+ return Object.fromEntries(
62
+ names.map((name) => {
63
+ const value = ownValue(values, name);
64
+ if (value === void 0) throw new Error(`stepSecrets: no value for runner secret ${name}`);
65
+ return [name, value];
66
+ })
67
+ );
46
68
  }
47
- function submodulePaths(entries) {
48
- return entries.filter((entry) => entry.startsWith("160000 ")).map((entry) => entry.slice(entry.indexOf(" ") + 1));
69
+ function declaredSecretValues(recipe, env) {
70
+ return (recipe?.secrets ?? []).map((name) => ownValue(env, name)).filter((value) => value !== void 0 && value !== "");
49
71
  }
50
- function partitionUntracked(entries) {
51
- const files = [];
52
- const nestedRepositories = [];
53
- for (const entry of entries) {
54
- if (entry.endsWith("/")) nestedRepositories.push(entry.slice(0, -1));
55
- else files.push(entry);
72
+ function readRunnerSecrets(recipe, env) {
73
+ const values = [];
74
+ const variables = [];
75
+ for (const name of recipe.secrets) {
76
+ const value = ownValue(env, name);
77
+ if (value === void 0 || value === "") variables.push({ name, problem: "missing" });
78
+ else if (/[\r\n]/.test(value)) variables.push({ name, problem: "multiline" });
79
+ else if (value.length < RUNNER_SECRET_MIN_LENGTH) variables.push({ name, problem: "short" });
80
+ else values.push([name, value]);
56
81
  }
57
- return { files, nestedRepositories };
58
- }
59
- function displayCommand(command, args) {
60
- return [command, ...args].map(shellQuote).join(" ");
82
+ return variables.length === 0 ? { ok: true, values: Object.fromEntries(values) } : { ok: false, variables };
61
83
  }
62
- function shellQuote(argument) {
63
- return /^[\w@%+=:,./^{}-]+$/.test(argument) ? argument : `'${argument.replaceAll("'", `'\\''`)}'`;
84
+ function ownValue(map, name) {
85
+ return Object.hasOwn(map, name) ? map[name] : void 0;
64
86
  }
65
87
 
66
- // src/runner/live/checkout-gateway.ts
67
- var GIT_MAX_BUFFER = 1024 * 1024 * 1024;
68
- var DIFF_OPTIONS = [
69
- "--no-color",
70
- "--no-ext-diff",
71
- "--no-textconv",
72
- "--no-renames",
73
- "--no-relative",
74
- "--ignore-submodules"
75
- ];
76
- function liveCheckoutGateway() {
88
+ // src/runner/base.ts
89
+ async function resolveBase(checkout, request2) {
90
+ const { repoRoot } = request2;
91
+ const refused2 = [];
92
+ let best;
93
+ for (const ref of request2.baseRefs) {
94
+ const candidate = await checkout.baseCandidate({ repoRoot, ref });
95
+ if (candidate.kind === "failed") return candidate;
96
+ if (candidate.kind === "missing-ref") {
97
+ refused2.push({ ref, reason: "missing" });
98
+ continue;
99
+ }
100
+ if (candidate.kind === "unrelated") {
101
+ refused2.push({ ref, reason: "unrelated" });
102
+ continue;
103
+ }
104
+ if (best === void 0) {
105
+ best = { base: candidate.base, ref };
106
+ continue;
107
+ }
108
+ if (candidate.base === best.base) continue;
109
+ const newer = await checkout.contains({ repoRoot, ancestor: best.base, descendant: candidate.base });
110
+ if (!newer.ok) return { kind: "failed", failure: newer.failure };
111
+ if (newer.value) best = { base: candidate.base, ref };
112
+ }
113
+ return best === void 0 ? { kind: "no-base-ref", refs: refused2 } : { kind: "resolved", ...best };
114
+ }
115
+ function baseStepContext(checkout, request2) {
116
+ const { repoRoot, base } = request2;
77
117
  return {
78
- repositoryRoot: ({ cwd }) => repositoryRoot(cwd),
79
- head: ({ repoRoot }) => head(repoRoot),
80
- baseCandidate: ({ repoRoot, ref }) => baseCandidate(repoRoot, ref),
81
- contains: ({ repoRoot, ancestor, descendant }) => contains(repoRoot, ancestor, descendant),
82
- commitTime: ({ repoRoot, commit }) => commitTime(repoRoot, commit),
83
- readFileAt: ({ repoRoot, commit, path }) => readFileAt(repoRoot, commit, path),
84
- submodules: ({ repoRoot }) => submodules(repoRoot),
85
- assembleUpload: ({ repoRoot, base }) => assembleUpload(repoRoot, base),
86
- baseArchive: ({ repoRoot, base }) => baseArchive(repoRoot, base)
118
+ base,
119
+ readBaseFile: async (path) => {
120
+ const file = await checkout.readFileAt({ repoRoot, commit: base, path });
121
+ if (file.kind === "found") return file.text;
122
+ if (file.kind === "missing") throw new Error(`${path} doesn't exist at ${base.slice(0, 12)}`);
123
+ throw new Error(`can't read ${path} at ${base.slice(0, 12)}: ${file.failure.message}`);
124
+ }
87
125
  };
88
126
  }
89
- async function repositoryRoot(cwd) {
90
- const run = await git(cwd, ["rev-parse", "--show-toplevel"]);
91
- return run.ok ? { ok: true, value: run.stdout.toString("utf8").trim() } : run;
92
- }
93
- async function head(repoRoot) {
94
- const [commit, branch, status] = await Promise.all([
95
- git(repoRoot, ["rev-parse", "--verify", "HEAD"]),
96
- git(repoRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
97
- git(repoRoot, ["status", "--porcelain", "-z", "--untracked-files=normal"])
98
- ]);
99
- if (!commit.ok) return commit;
100
- if (!branch.ok && branch.exitCode !== 1) return branch;
101
- if (!status.ok) return status;
127
+
128
+ // src/runner/scope.ts
129
+ var CREATE_SETTLE_MS = 2e4;
130
+ var SNAPSHOT_SETTLE_MS = 2 * 6e4;
131
+ function runnerSandboxScope(context, progress, keep) {
132
+ const { runnerSandboxes: sandboxes, timer, clock } = context;
133
+ const live = /* @__PURE__ */ new Set();
134
+ const creating = /* @__PURE__ */ new Set();
135
+ const saving = /* @__PURE__ */ new Set();
136
+ const notStopped = [];
137
+ const notDeleted = [];
138
+ let kept = null;
139
+ let notKept = null;
140
+ let closing;
141
+ const track = (set, task) => {
142
+ set.add(task);
143
+ const forget = () => set.delete(task);
144
+ void task.then(forget, forget);
145
+ return task;
146
+ };
147
+ const remove = async (sandbox) => {
148
+ const deleted = await sandboxes.delete(sandbox);
149
+ if (!deleted.ok)
150
+ notDeleted.push({ name: sandbox.name, role: sandbox.role, message: failureMessage(deleted.failure) });
151
+ };
152
+ const stopAndRemove = async (sandbox) => {
153
+ const stopped = await sandboxes.stop(sandbox);
154
+ if (!stopped.ok) {
155
+ notStopped.push({
156
+ name: sandbox.name,
157
+ role: sandbox.role,
158
+ timeoutMinutes: Math.round(sandbox.timeoutMs / 6e4),
159
+ message: failureMessage(stopped.failure)
160
+ });
161
+ return;
162
+ }
163
+ await remove(sandbox);
164
+ };
165
+ const keepOrRemove = async (sandbox) => {
166
+ const keepMs = sandbox.role === "runner" ? keep.keepMs : 0;
167
+ if (keepMs <= 0) return await stopAndRemove(sandbox);
168
+ const keeping = await sandboxes.keepRunning(sandbox, { until: new Date(clock.now().getTime() + keepMs) });
169
+ if (!keeping.ok) {
170
+ notKept = { name: sandbox.name, message: failureMessage(keeping.failure) };
171
+ return await stopAndRemove(sandbox);
172
+ }
173
+ kept = { name: sandbox.name, stopsAt: keeping.value.stopsAt.toISOString() };
174
+ await progress.emit({ kind: "sandbox-kept", ...kept });
175
+ };
176
+ const owned = (start) => {
177
+ if (closing !== void 0) return Promise.resolve({ ok: false, failure: { kind: "aborted" } });
178
+ return track(
179
+ creating,
180
+ (async () => {
181
+ const started = await start();
182
+ if (!started.ok) return started;
183
+ if (closing !== void 0) {
184
+ await stopAndRemove(started.value);
185
+ return { ok: false, failure: { kind: "aborted" } };
186
+ }
187
+ live.add(started.value);
188
+ return started;
189
+ })()
190
+ );
191
+ };
102
192
  return {
103
- ok: true,
104
- value: {
105
- branch: branch.ok ? branch.stdout.toString("utf8").trim() : null,
106
- commit: commit.stdout.toString("utf8").trim(),
107
- dirty: status.stdout.length > 0
193
+ startBuildSandbox: (access, request2) => owned(() => sandboxes.startBuildSandbox(access, request2)),
194
+ startRunnerSandbox: (access, request2) => owned(() => sandboxes.startRunnerSandbox(access, request2)),
195
+ saveSnapshot: (sandbox, request2) => track(
196
+ saving,
197
+ (async () => {
198
+ const saved = await sandboxes.saveSnapshot(sandbox, request2);
199
+ if (saved.ok && live.delete(sandbox)) await remove(sandbox);
200
+ return saved;
201
+ })()
202
+ ),
203
+ close() {
204
+ closing ??= (async () => {
205
+ if (saving.size > 0) await progress.emit({ kind: "waiting-for-snapshot", settleMs: SNAPSHOT_SETTLE_MS });
206
+ await Promise.all([
207
+ settleWithin(timer, creating, CREATE_SETTLE_MS),
208
+ settleWithin(timer, saving, SNAPSHOT_SETTLE_MS)
209
+ ]);
210
+ const held = [...live];
211
+ live.clear();
212
+ await Promise.all(held.map(keepOrRemove));
213
+ return { kept, notKept, notStopped: [...notStopped], notDeleted: [...notDeleted] };
214
+ })();
215
+ return closing;
108
216
  }
109
217
  };
110
218
  }
111
- async function baseCandidate(repoRoot, ref) {
112
- const exists = await git(repoRoot, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
113
- if (!exists.ok) return exists.exitCode === 1 ? { kind: "missing-ref" } : { kind: "failed", failure: exists.failure };
114
- const mergeBase = await git(repoRoot, ["merge-base", "HEAD", ref]);
115
- if (!mergeBase.ok)
116
- return mergeBase.exitCode === 1 ? { kind: "unrelated" } : { kind: "failed", failure: mergeBase.failure };
117
- return { kind: "merge-base", base: mergeBase.stdout.toString("utf8").trim() };
118
- }
119
- async function contains(repoRoot, ancestor, descendant) {
120
- const present = await git(repoRoot, ["cat-file", "-e", `${ancestor}^{commit}`]);
121
- if (!present.ok) return { ok: true, value: false };
122
- const run = await git(repoRoot, ["merge-base", "--is-ancestor", ancestor, descendant]);
123
- if (run.ok) return { ok: true, value: true };
124
- return run.exitCode === 1 ? { ok: true, value: false } : run;
219
+ async function settleWithin(timer, tasks, ms) {
220
+ if (tasks.size === 0) return;
221
+ const done = new AbortController();
222
+ await Promise.race([Promise.allSettled(tasks), timer.sleep(ms, done.signal)]);
223
+ done.abort();
125
224
  }
126
- async function commitTime(repoRoot, commit) {
127
- const run = await git(repoRoot, ["show", "-s", "--format=%ct", `${commit}^{commit}`]);
128
- if (!run.ok) return run;
129
- const seconds = Number(run.stdout.toString("utf8").trim());
130
- return Number.isSafeInteger(seconds) ? { ok: true, value: seconds * 1e3 } : { ok: false, failure: { message: `git show printed no commit time for ${commit}` } };
225
+ function failureMessage(failure) {
226
+ return failure.message ?? failure.kind;
131
227
  }
132
- async function readFileAt(repoRoot, commit, path) {
133
- const object = `${commit}:${path}`;
134
- const type = await git(repoRoot, ["cat-file", "-t", object]);
135
- if (!type.ok || type.stdout.toString("utf8").trim() !== "blob") return { kind: "missing" };
136
- const run = await git(repoRoot, ["cat-file", "blob", object]);
137
- return run.ok ? { kind: "found", text: run.stdout.toString("utf8") } : { kind: "failed", failure: run.failure };
228
+
229
+ // src/runner/context.ts
230
+ function runnerPurpose(recipeName) {
231
+ return `storm-runner-${recipeName}`;
138
232
  }
139
- async function submodules(repoRoot) {
140
- const run = await git(repoRoot, ["ls-files", "--stage", "-z"]);
141
- return run.ok ? { ok: true, value: submodulePaths(splitNul(run.stdout)) } : run;
233
+ function runnerTags(recipeName, role, user) {
234
+ return { purpose: runnerPurpose(recipeName), user, role };
142
235
  }
143
- async function assembleUpload(repoRoot, base) {
144
- const [patch, others] = await Promise.all([
145
- git(repoRoot, [
146
- "diff",
147
- "--binary",
148
- // A user's `diff.context=0` makes patches that need special flags to apply.
149
- "--unified=3",
150
- ...DIFF_OPTIONS,
151
- "--src-prefix=a/",
152
- "--dst-prefix=b/",
153
- base
154
- ]),
155
- git(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"])
156
- ]);
157
- if (!patch.ok) return patch;
158
- if (!others.ok) return others;
159
- const { files, nestedRepositories } = partitionUntracked(splitNul(others.stdout));
160
- let untrackedTarball;
161
- if (files.length > 0) {
162
- const tarball = await createTarball(repoRoot, files);
163
- if (!tarball.ok) return tarball;
164
- untrackedTarball = tarball.value;
165
- }
166
- return { ok: true, value: { patch: patch.stdout, untracked: files, untrackedTarball, nestedRepositories } };
236
+
237
+ // src/runner/snapshot-cache.ts
238
+ import { createHash } from "node:crypto";
239
+ var RUNNER_SNAPSHOTS_SUBPATH = ["runner", "snapshots"];
240
+ var SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1e3;
241
+ var SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1e3;
242
+ function snapshotEntryIdentity(entry) {
243
+ return createHash("sha256").update(
244
+ [
245
+ entry.teamId,
246
+ entry.projectId,
247
+ entry.region,
248
+ entry.runtime,
249
+ entry.recipeName,
250
+ entry.snapshotKey,
251
+ entry.base
252
+ ].join("\0")
253
+ ).digest("hex").slice(0, 32);
167
254
  }
168
- async function baseArchive(repoRoot, base) {
169
- const [tarball, fileList] = await Promise.all([
170
- // LF line endings, as the patch has them: with `core.autocrlf=true`, the Git for Windows default, `git archive`
171
- // writes CRLF files the patch doesn't apply to.
172
- git(repoRoot, ["-c", "core.autocrlf=false", "-c", "core.eol=lf", "archive", "--format=tar.gz", base]),
173
- git(repoRoot, ["ls-tree", "-r", "--name-only", "-z", "--full-tree", base])
174
- ]);
175
- if (!tarball.ok) return tarball;
176
- if (!fileList.ok) return fileList;
177
- return {
178
- ok: true,
179
- value: { tarball: tarball.stdout, fileList: fileList.stdout, files: splitNul(fileList.stdout).length }
180
- };
255
+ function snapshotEntryFileName(entry) {
256
+ return `${snapshotEntryIdentity(entry)}.json`;
181
257
  }
182
- function git(repoRoot, args) {
183
- const argv = ["-C", repoRoot, ...args];
184
- return new Promise((resolve) => {
185
- execFile(
186
- "git",
187
- argv,
188
- { encoding: "buffer", maxBuffer: GIT_MAX_BUFFER, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } },
189
- (error, stdout, stderr) => {
190
- if (error === null) {
191
- resolve({ ok: true, stdout });
192
- return;
193
- }
194
- const subcommand = args.find((arg, index) => arg !== "-c" && args[index - 1] !== "-c") ?? "";
195
- const detail = stderr.toString("utf8").trim() || error.message;
196
- resolve({
197
- ok: false,
198
- exitCode: typeof error.code === "number" ? error.code : void 0,
199
- failure: { message: `git ${subcommand} failed: ${detail}`, displayCommand: displayCommand("git", argv) }
200
- });
201
- }
202
- );
203
- });
258
+ function isExpiredEntry(entry, now) {
259
+ return Date.parse(entry.expiresAt) <= now.getTime();
204
260
  }
205
- function createTarball(repoRoot, paths) {
206
- const args = ["--null", "-czf", "-", "-C", repoRoot, "-T", "-"];
207
- const command = displayCommand("tar", args);
208
- return new Promise((resolve) => {
209
- const child = spawn("tar", args, {
210
- stdio: ["pipe", "pipe", "pipe"],
211
- env: { ...process.env, COPYFILE_DISABLE: "1" }
212
- });
213
- const chunks = [];
214
- const errors = [];
215
- let stdinError;
216
- let spawnError;
217
- child.stdout.on("data", (chunk) => chunks.push(chunk));
218
- child.stderr.on("data", (chunk) => errors.push(chunk));
219
- child.stdin.on("error", (error) => {
220
- stdinError = error;
221
- });
222
- child.once("error", (error) => {
223
- spawnError = error;
224
- });
225
- child.once("close", (code) => {
226
- const stderr = Buffer.concat(errors).toString("utf8").trim();
227
- if (spawnError !== void 0)
228
- resolve({ ok: false, failure: { message: `tar failed: ${spawnError.message}`, displayCommand: command } });
229
- else if (code !== 0)
230
- resolve({
231
- ok: false,
232
- failure: { message: `tar failed (exit ${code ?? "none"}): ${stderr}`, displayCommand: command }
233
- });
234
- else if (stdinError !== void 0)
235
- resolve({
236
- ok: false,
237
- failure: { message: `tar didn't read the whole path list: ${stdinError.message}`, displayCommand: command }
238
- });
239
- else resolve({ ok: true, value: Buffer.concat(chunks) });
240
- });
241
- child.stdin.end(paths.map((path) => `${path}\0`).join(""));
242
- });
261
+ function hasTimeLeft(entry, now) {
262
+ return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
243
263
  }
244
-
245
- // src/runner/snapshot-key.ts
246
- import { createHash } from "node:crypto";
247
-
248
- // src/runner/base.ts
249
- async function resolveBase(checkout, request2) {
250
- const { repoRoot } = request2;
251
- const refused2 = [];
252
- let best;
253
- for (const ref of request2.baseRefs) {
254
- const candidate = await checkout.baseCandidate({ repoRoot, ref });
255
- if (candidate.kind === "failed") return candidate;
256
- if (candidate.kind === "missing-ref") {
257
- refused2.push({ ref, reason: "missing" });
264
+ async function removeExpiredEntries(context) {
265
+ const { runnerSnapshots } = context;
266
+ const listed = await runnerSnapshots.listEntries();
267
+ if (!listed.ok) return { entries: [], notes: [{ kind: "cache-unreadable", failure: listed.failure }] };
268
+ const now = context.clock.now();
269
+ const entries = [];
270
+ const notes = [];
271
+ for (const entry of listed.value.entries) {
272
+ if (!isExpiredEntry(entry, now)) {
273
+ entries.push(entry);
258
274
  continue;
259
275
  }
260
- if (candidate.kind === "unrelated") {
261
- refused2.push({ ref, reason: "unrelated" });
276
+ const removed = await runnerSnapshots.removeEntry(entry);
277
+ if (!removed.ok) notes.push({ kind: "expired-entry-not-removed", entry, failure: removed.failure });
278
+ }
279
+ return { entries, notes };
280
+ }
281
+ function classifySnapshotEntries(context, request2) {
282
+ const { entries, recipe, base, snapshotKey: snapshotKey2, commitsAfterBase } = request2;
283
+ const now = context.clock.now();
284
+ const candidates = [];
285
+ const rejected = [];
286
+ const verdicts = [];
287
+ const reject = (entry, reason) => {
288
+ const rejection = { entry, reason };
289
+ rejected.push(rejection);
290
+ verdicts.push({ kind: "rejected", entry, rejection });
291
+ };
292
+ for (const entry of entries) {
293
+ if (entry.region !== recipe.region || entry.runtime !== recipe.runtime || entry.recipeName !== recipe.name) {
294
+ verdicts.push({ kind: "other-recipe", entry });
262
295
  continue;
263
296
  }
264
- if (best === void 0) {
265
- best = { base: candidate.base, ref };
266
- continue;
297
+ if (isExpiredEntry(entry, now)) reject(entry, "expired");
298
+ else if (!hasTimeLeft(entry, now)) reject(entry, "expires-soon");
299
+ else if (entry.base !== base) reject(entry, "other-base");
300
+ else if (entry.snapshotKey !== snapshotKey2) reject(entry, "steps-changed");
301
+ else {
302
+ const candidate = { entry, builtBehind: commitsAfterBase };
303
+ candidates.push(candidate);
304
+ verdicts.push({ kind: "candidate", entry, candidate });
267
305
  }
268
- if (candidate.base === best.base) continue;
269
- const newer = await checkout.contains({ repoRoot, ancestor: best.base, descendant: candidate.base });
270
- if (!newer.ok) return { kind: "failed", failure: newer.failure };
271
- if (newer.value) best = { base: candidate.base, ref };
272
306
  }
273
- return best === void 0 ? { kind: "no-base-ref", refs: refused2 } : { kind: "resolved", ...best };
307
+ return { candidates, rejected, verdicts };
274
308
  }
275
- function baseStepContext(checkout, request2) {
276
- const { repoRoot, base } = request2;
277
- return {
278
- base,
279
- readBaseFile: async (path) => {
280
- const file = await checkout.readFileAt({ repoRoot, commit: base, path });
281
- if (file.kind === "found") return file.text;
282
- if (file.kind === "missing") throw new Error(`${path} doesn't exist at ${base.slice(0, 12)}`);
283
- throw new Error(`can't read ${path} at ${base.slice(0, 12)}: ${file.failure.message}`);
284
- }
285
- };
309
+ function snapshotRejections(read, owner) {
310
+ const owned = (entry) => entry.teamId === owner.teamId && entry.projectId === owner.projectId;
311
+ return [
312
+ ...read.candidates.map(({ entry }) => ({ entry, reason: "other-owner" })),
313
+ ...read.rejected.map(({ entry, reason }) => ({ entry, reason: owned(entry) ? reason : "other-owner" }))
314
+ ];
286
315
  }
316
+ function pickSnapshot(candidates, owner) {
317
+ return candidates.find(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId);
318
+ }
319
+
320
+ // src/runner/snapshot-key.ts
321
+ import { createHash as createHash2 } from "node:crypto";
287
322
 
288
323
  // src/time/duration.ts
289
324
  var MIN_TTL_MINUTES = 10;
@@ -326,58 +361,59 @@ var systemClock = {
326
361
  };
327
362
 
328
363
  // src/sdk/run/payload.ts
329
- import { z } from "zod";
364
+ import { z as z2 } from "zod";
330
365
  var RUN_PAYLOAD_VARIABLE = "STORM_RUN";
331
366
  var RUN_PAYLOAD_VERSION = 3;
332
- var runPayloadSchema = z.object({
333
- version: z.literal(RUN_PAYLOAD_VERSION),
334
- resources: z.record(z.string(), z.object({ definition: z.string().min(1), payload: z.unknown() })),
335
- testEvents: z.string().min(1).optional(),
336
- verbose: z.literal(true).optional()
367
+ var runPayloadSchema = z2.object({
368
+ version: z2.literal(RUN_PAYLOAD_VERSION),
369
+ resources: z2.record(z2.string(), z2.object({ definition: z2.string().min(1), payload: z2.unknown() })),
370
+ testEvents: z2.string().min(1).optional(),
371
+ verbose: z2.literal(true).optional()
337
372
  });
338
373
 
339
374
  // src/sdk/run/test-events.ts
340
- import { z as z2 } from "zod";
341
- var where = { file: z2.string(), worker: z2.number().int().positive(), at: z2.number() };
342
- var state = z2.enum(["pass", "fail", "skip"]);
343
- var testEventSchema = z2.discriminatedUnion("kind", [
344
- z2.object({ kind: z2.literal("file-started"), ...where }),
345
- z2.object({ kind: z2.literal("file-finished"), ...where }),
346
- z2.object({ kind: z2.literal("test-started"), ...where, test: z2.string(), fileTests: z2.number().int().nonnegative() }),
347
- z2.object({
348
- kind: z2.literal("test-attempt-finished"),
375
+ import { z as z3 } from "zod";
376
+ var where = { file: z3.string(), worker: z3.number().int().nonnegative(), at: z3.number() };
377
+ var setup = { label: z3.string().min(1), resource: z3.string().min(1) };
378
+ var state = z3.enum(["pass", "fail", "skip"]);
379
+ var testEventSchema = z3.discriminatedUnion("kind", [
380
+ z3.object({ kind: z3.literal("file-started"), ...where }),
381
+ z3.object({ kind: z3.literal("file-finished"), ...where }),
382
+ z3.object({ kind: z3.literal("test-started"), ...where, test: z3.string(), fileTests: z3.number().int().nonnegative() }),
383
+ z3.object({
384
+ kind: z3.literal("test-attempt-finished"),
349
385
  ...where,
350
- test: z2.string(),
386
+ test: z3.string(),
351
387
  state,
352
- ms: z2.number().nonnegative()
388
+ ms: z3.number().nonnegative()
353
389
  }),
354
- z2.object({ kind: z2.literal("container-starting"), ...where }),
355
- z2.object({
356
- kind: z2.literal("container-started"),
390
+ z3.object({ kind: z3.literal("setup-started"), ...where, ...setup }),
391
+ z3.object({
392
+ kind: z3.literal("setup-finished"),
357
393
  ...where,
358
- ms: z2.number().nonnegative(),
359
- ok: z2.boolean(),
360
- warmupMs: z2.number().nonnegative().exactOptional(),
361
- warmupFailed: z2.number().int().nonnegative().exactOptional()
394
+ ...setup,
395
+ ms: z3.number().nonnegative(),
396
+ ok: z3.boolean(),
397
+ warmupMs: z3.number().nonnegative().exactOptional()
362
398
  }),
363
- z2.object({
364
- kind: z2.literal("test-result"),
365
- id: z2.string().min(1),
366
- file: z2.string(),
367
- test: z2.string(),
399
+ z3.object({
400
+ kind: z3.literal("test-result"),
401
+ id: z3.string().min(1),
402
+ file: z3.string(),
403
+ test: z3.string(),
368
404
  state,
369
- retryCount: z2.number().int().nonnegative(),
370
- flaky: z2.boolean(),
371
- at: z2.number(),
372
- errors: z2.array(
373
- z2.object({
374
- name: z2.string(),
375
- message: z2.string(),
376
- stack: z2.string().exactOptional(),
377
- diff: z2.string().exactOptional()
405
+ retryCount: z3.number().int().nonnegative(),
406
+ flaky: z3.boolean(),
407
+ at: z3.number(),
408
+ errors: z3.array(
409
+ z3.object({
410
+ name: z3.string(),
411
+ message: z3.string(),
412
+ stack: z3.string().exactOptional(),
413
+ diff: z3.string().exactOptional()
378
414
  })
379
415
  ).exactOptional(),
380
- output: z2.object({ text: z2.string(), droppedChars: z2.number().int().nonnegative() }).exactOptional()
416
+ output: z3.object({ text: z3.string(), droppedChars: z3.number().int().nonnegative() }).exactOptional()
381
417
  })
382
418
  ]);
383
419
  function testEventLine(event) {
@@ -401,6 +437,17 @@ function redactSecrets(text, secrets) {
401
437
  return ordered.reduce((redacted, secret) => redacted.split(secret).join(REDACTED), text);
402
438
  }
403
439
 
440
+ // src/runner/events.ts
441
+ function progressQueue(progress) {
442
+ let pending = Promise.resolve();
443
+ return {
444
+ add(event) {
445
+ pending = pending.then(() => progress.emit(event));
446
+ },
447
+ flush: () => pending
448
+ };
449
+ }
450
+
404
451
  // src/runner/output.ts
405
452
  var OUTPUT_TAIL_LINES = 40;
406
453
  function lineSplitter() {
@@ -490,9 +537,6 @@ function sandboxStop(operation, failure) {
490
537
  }
491
538
 
492
539
  // src/runner/recipe.ts
493
- function runStepTakesSecret(recipe) {
494
- return recipe.run.install.secrets.length > 0 || recipe.run.build.secrets.length > 0;
495
- }
496
540
  var RECIPE_DEFAULTS = {
497
541
  cwd: ".",
498
542
  timeout: "60m",
@@ -510,7 +554,6 @@ var RECIPE_KEYS = /* @__PURE__ */ new Set([
510
554
  "secrets",
511
555
  "timeout",
512
556
  "keepSandbox",
513
- "saveSnapshot",
514
557
  "baseRefs",
515
558
  "region",
516
559
  "runtime"
@@ -573,9 +616,6 @@ function checkRecipe(value) {
573
616
  ["keepSandbox"],
574
617
  `must be 0, or a whole number of minutes or hours up to 5h, not ${describeRecipeValue(keepSandbox)}`
575
618
  );
576
- const saveSnapshot = value["saveSnapshot"];
577
- if (saveSnapshot !== void 0 && typeof saveSnapshot !== "boolean")
578
- report(["saveSnapshot"], `must be true or false, not ${describeRecipeValue(saveSnapshot)}`);
579
619
  const baseRefs = checkBaseRefs(value["baseRefs"], report);
580
620
  const region = orDefault(value["region"], RECIPE_DEFAULTS.region);
581
621
  if (!isNonEmptyString(region)) report(["region"], `must be a non-empty string, not ${describeRecipeValue(region)}`);
@@ -597,7 +637,6 @@ function checkRecipe(value) {
597
637
  timeout,
598
638
  timeoutMinutes,
599
639
  keepSandboxMinutes,
600
- ...typeof saveSnapshot === "boolean" ? { saveSnapshot } : {},
601
640
  baseRefs,
602
641
  region,
603
642
  runtime
@@ -613,7 +652,7 @@ function checkSnapshot(value, declared, report) {
613
652
  if (!isRecord(value)) {
614
653
  report(
615
654
  ["snapshot"],
616
- `must be an object of vcpus, toolchains, prebuild and an optional summary, not ${describeRecipeValue(value)}`
655
+ `must be an object of vcpus, toolchains, prebuild, and an optional summary, not ${describeRecipeValue(value)}`
617
656
  );
618
657
  return void 0;
619
658
  }
@@ -858,7 +897,7 @@ function isRelativePath(value) {
858
897
  }
859
898
 
860
899
  // src/runner/snapshot-key.ts
861
- var SNAPSHOT_FORMAT = 2;
900
+ var SNAPSHOT_FORMAT = 3;
862
901
  var SANDBOX_ROOT = "/vercel/sandbox";
863
902
  var STAGED_FILES = {
864
903
  baseTarball: "base.tgz",
@@ -868,13 +907,8 @@ var STAGED_FILES = {
868
907
  untrackedFileList: "untracked-files"
869
908
  };
870
909
  var GIT_IDENTITY = "-c user.email=storm-runner@vercel.invalid -c user.name='storm runner' -c commit.gpgsign=false";
871
- var RESET_TO_BASE = [
872
- "root=$(git rev-list --max-parents=0 HEAD)",
873
- 'git reset -q --hard "$root"',
874
- "git clean -ffdq"
875
- ];
876
- function bashScript(lines) {
877
- return ["set -euo pipefail", `cd ${SANDBOX_ROOT}`, ...lines].join("\n");
910
+ function bashScript(lines, root = SANDBOX_ROOT) {
911
+ return ["set -euo pipefail", `cd ${root}`, ...lines].join("\n");
878
912
  }
879
913
  function baseIndexScript(base, staging) {
880
914
  const tarball = `${staging}/${STAGED_FILES.baseTarball}`;
@@ -888,26 +922,31 @@ function baseIndexScript(base, staging) {
888
922
  `git ${GIT_IDENTITY} commit -q --no-verify -m 'base ${base}'`
889
923
  ]);
890
924
  }
891
- function applyScript(staging) {
925
+ function applyScript(staging, root = SANDBOX_ROOT) {
892
926
  const patch = `${staging}/${STAGED_FILES.patch}`;
893
927
  const tarball = `${staging}/${STAGED_FILES.untrackedTarball}`;
894
928
  const fileList = `${staging}/${STAGED_FILES.untrackedFileList}`;
895
- return bashScript([
896
- ...RESET_TO_BASE,
897
- // A build may have rewritten tracked files with the same content.
898
- "git update-index -q --refresh || true",
899
- `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
900
- `if [ -s ${tarball} ]; then`,
901
- ` tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
902
- ` git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
903
- "fi",
904
- `git ${GIT_IDENTITY} commit -q --no-verify --allow-empty -m run`,
905
- `rm -f ${patch} ${tarball} ${fileList}`
906
- ]);
929
+ return bashScript(
930
+ [
931
+ "root=$(git rev-list --max-parents=0 HEAD)",
932
+ 'git reset -q --hard "$root"',
933
+ "git clean -ffdq",
934
+ // A build may have rewritten tracked files with the same content.
935
+ "git update-index -q --refresh || true",
936
+ `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
937
+ `if [ -s ${tarball} ]; then`,
938
+ ` tar --warning=no-unknown-keyword -xzf ${tarball} -C ${root}`,
939
+ ` git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
940
+ "fi",
941
+ `git ${GIT_IDENTITY} commit -q --no-verify --allow-empty -m run`,
942
+ `rm -f ${patch} ${tarball} ${fileList}`
943
+ ],
944
+ root
945
+ );
907
946
  }
908
947
  function snapshotKey(steps) {
909
948
  const text = (list) => list.flatMap(({ label, script, secrets }) => [label, script, `secrets=${(secrets ?? []).toSorted().join(",")}`]);
910
- return createHash("sha256").update(
949
+ return createHash2("sha256").update(
911
950
  [
912
951
  `format=${SNAPSHOT_FORMAT}`,
913
952
  ...text(steps.toolchains),
@@ -931,29 +970,589 @@ async function snapshotStepsAt(checkout, request2) {
931
970
  };
932
971
  }
933
972
 
934
- // src/runner/live/sandbox-errors.ts
935
- function apiStatus(error) {
936
- if (typeof error !== "object" || error === null) return void 0;
937
- const response = error.response;
938
- if (typeof response !== "object" || response === null) return void 0;
939
- const status = response.status;
940
- return typeof status === "number" ? status : void 0;
941
- }
942
- function isAbortError(error) {
943
- return typeof error === "object" && error !== null && error.name === "AbortError";
944
- }
945
- function sandboxFailure(error, signal) {
946
- if (signal?.aborted === true || isAbortError(error)) return { kind: "aborted" };
947
- return { kind: "api", status: apiStatus(error), message: error instanceof Error ? error.message : String(error) };
948
- }
949
-
950
- // src/runner/live/sandbox-gateway.ts
951
- var TERMINATE_GRACE_MS = 1e4;
952
- var KILL_GRACE_MS = 5e3;
953
- var STDERR_MESSAGE_CHARS = 1e3;
954
- var SNAPSHOT_GONE_STATUS = 410;
955
- function liveRunnerSandboxGateway() {
956
- let loading;
973
+ // src/runner/snapshot-build.ts
974
+ var BUILD_SANDBOX_TIMEOUT_MS = 30 * 6e4;
975
+ var BASE_INDEX_LABEL = "Committing the base's files";
976
+ async function buildSnapshot(context, request2, control, progress) {
977
+ const { prepared, access } = request2;
978
+ const { recipe, repoRoot, base } = prepared;
979
+ const { scope, signal } = control;
980
+ const now = () => context.clock.now().getTime();
981
+ const startedAt = now();
982
+ await progress.emit({
983
+ kind: "snapshot-build-started",
984
+ base,
985
+ why: request2.why,
986
+ summary: recipe.snapshot.summary ?? [...prepared.toolchains, ...prepared.prebuild].map(({ label }) => label).join(", ")
987
+ });
988
+ const [started, archive] = await Promise.all([
989
+ scope.startBuildSandbox(access, {
990
+ region: recipe.region,
991
+ runtime: recipe.runtime,
992
+ vcpus: recipe.snapshot.vcpus,
993
+ timeoutMs: BUILD_SANDBOX_TIMEOUT_MS,
994
+ tags: runnerTags(recipe.name, "snapshot-build", request2.user)
995
+ }),
996
+ context.checkout.baseArchive({ repoRoot, base })
997
+ ]);
998
+ if (!started.ok) return sandboxStop("start-build-sandbox", started.failure);
999
+ const sandbox = started.value;
1000
+ await progress.emit({
1001
+ kind: "sandbox-started",
1002
+ role: "snapshot-build",
1003
+ name: sandbox.name,
1004
+ region: recipe.region,
1005
+ vcpus: recipe.snapshot.vcpus,
1006
+ ms: now() - startedAt
1007
+ });
1008
+ if (!archive.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: archive.failure } };
1009
+ const staged = await context.runnerSandboxes.upload(
1010
+ sandbox,
1011
+ [
1012
+ { name: STAGED_FILES.baseTarball, content: archive.value.tarball },
1013
+ { name: STAGED_FILES.baseFileList, content: archive.value.fileList }
1014
+ ],
1015
+ signal
1016
+ );
1017
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
1018
+ const recipeStep = ({ label, script, secrets }) => ({
1019
+ label,
1020
+ script,
1021
+ secrets: stepSecrets(request2.secrets, secrets)
1022
+ });
1023
+ const steps = [
1024
+ ...prepared.toolchains.map(recipeStep),
1025
+ { label: BASE_INDEX_LABEL, script: baseIndexScript(base, staged.value.directory) },
1026
+ ...prepared.prebuild.map(recipeStep)
1027
+ ];
1028
+ await progress.emit({ kind: "output-started", section: "snapshot", sandbox: sandbox.name, region: recipe.region });
1029
+ for (const step of steps) {
1030
+ const ran = await runStep(context, { sandbox, phase: "snapshot", ...step }, progress, signal);
1031
+ if (ran.kind === "succeeded") continue;
1032
+ const stop = ran.kind === "exited" ? {
1033
+ kind: "failed",
1034
+ failure: { kind: "snapshot-build-step-failed", label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1035
+ } : sandboxStop("run-script", ran.failure);
1036
+ await progress.emit({
1037
+ kind: "output-ended",
1038
+ section: "snapshot",
1039
+ outcome: stop.kind === "aborted" ? "stopped" : "failed"
1040
+ });
1041
+ return stop;
1042
+ }
1043
+ await progress.emit({ kind: "output-ended", section: "snapshot", outcome: "finished" });
1044
+ if (signal.aborted) return { kind: "aborted" };
1045
+ await progress.emit({ kind: "snapshot-saving" });
1046
+ const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
1047
+ if (!saved.ok) return sandboxStop("save-snapshot", saved.failure);
1048
+ const savedAt = context.clock.now();
1049
+ const entry = {
1050
+ teamId: access.teamId,
1051
+ projectId: access.projectId,
1052
+ region: recipe.region,
1053
+ runtime: recipe.runtime,
1054
+ recipeName: recipe.name,
1055
+ snapshotKey: prepared.snapshotKey,
1056
+ base,
1057
+ snapshotId: saved.value.snapshotId,
1058
+ createdAt: savedAt.toISOString(),
1059
+ expiresAt: saved.value.expiresAt ?? new Date(savedAt.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1060
+ };
1061
+ const written = await context.runnerSnapshots.writeEntry(entry);
1062
+ if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
1063
+ const ms = now() - startedAt;
1064
+ await progress.emit({
1065
+ kind: "snapshot-built",
1066
+ snapshotId: entry.snapshotId,
1067
+ base,
1068
+ ms,
1069
+ sizeBytes: saved.value.sizeBytes,
1070
+ builtBehind: prepared.commitsAfterBase
1071
+ });
1072
+ return {
1073
+ kind: "ok",
1074
+ value: { entry, ms, sizeBytes: saved.value.sizeBytes, cacheFailure: written.ok ? null : written.failure }
1075
+ };
1076
+ }
1077
+
1078
+ // src/runner/build-snapshots.ts
1079
+ async function prepareSnapshotBuild(context, request2) {
1080
+ const { checkout } = context;
1081
+ const { recipe, ref } = request2;
1082
+ const root = await checkout.repositoryRoot({ cwd: request2.cwd });
1083
+ if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
1084
+ const repoRoot = root.value;
1085
+ const head2 = await checkout.head({ repoRoot });
1086
+ if (!head2.ok) return { kind: "checkout-failed", failure: head2.failure };
1087
+ const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1088
+ if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1089
+ const mergeBase = resolved.kind === "resolved" ? { commit: resolved.base, ref: resolved.ref } : null;
1090
+ const submodules2 = await checkout.submodules({ repoRoot });
1091
+ if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
1092
+ if (submodules2.value.length > 0) return { kind: "submodules", paths: [...submodules2.value] };
1093
+ let base;
1094
+ if (ref === void 0) {
1095
+ if (resolved.kind !== "resolved") return resolved;
1096
+ base = resolved.base;
1097
+ } else {
1098
+ const commit = await checkout.resolveCommit({ repoRoot, ref });
1099
+ if (!commit.ok) return { kind: "checkout-failed", failure: commit.failure };
1100
+ if (commit.value === null) return { kind: "ref-not-found", ref };
1101
+ base = commit.value;
1102
+ }
1103
+ const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
1104
+ if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1105
+ const listed = await context.runnerSnapshots.listEntries();
1106
+ const now = context.clock.now();
1107
+ const cached = (listed.ok ? listed.value.entries : []).filter(
1108
+ (entry) => entry.base === base && entry.recipeName === recipe.name && entry.region === recipe.region && entry.runtime === recipe.runtime && entry.snapshotKey === steps.key && hasTimeLeft(entry, now)
1109
+ );
1110
+ const atMergeBase = base === mergeBase?.commit;
1111
+ let commitsAfterBase = null;
1112
+ if (atMergeBase) {
1113
+ const counted = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
1114
+ if (!counted.ok) return { kind: "checkout-failed", failure: counted.failure };
1115
+ commitsAfterBase = counted.value;
1116
+ }
1117
+ return {
1118
+ kind: "ok",
1119
+ build: {
1120
+ plan: {
1121
+ recipe,
1122
+ repoRoot,
1123
+ base,
1124
+ toolchains: steps.toolchains,
1125
+ prebuild: steps.prebuild,
1126
+ snapshotKey: steps.key,
1127
+ commitsAfterBase
1128
+ },
1129
+ head: head2.value,
1130
+ ref: ref ?? null,
1131
+ mergeBase,
1132
+ atMergeBase,
1133
+ cached,
1134
+ full: request2.full
1135
+ }
1136
+ };
1137
+ }
1138
+ async function buildSnapshots(context, request2, control, progress) {
1139
+ const { signal } = control;
1140
+ const scope = runnerSandboxScope(context, progress, { keepMs: 0 });
1141
+ const stop = () => {
1142
+ void progress.emit({ kind: "stopping", commandRunning: false, keepMs: 0 }).catch(() => void 0);
1143
+ void scope.close().catch(() => void 0);
1144
+ };
1145
+ if (signal.aborted) stop();
1146
+ else signal.addEventListener("abort", stop, { once: true });
1147
+ try {
1148
+ const ended = await buildIn(context, request2, { scope, signal }, progress);
1149
+ signal.removeEventListener("abort", stop);
1150
+ return { ...ended, cleanup: await scope.close() };
1151
+ } catch (error) {
1152
+ signal.removeEventListener("abort", stop);
1153
+ await scope.close();
1154
+ throw error;
1155
+ }
1156
+ }
1157
+ async function buildIn(context, request2, control, progress) {
1158
+ const { build, access, user, secrets } = request2;
1159
+ const { signal } = control;
1160
+ if (signal.aborted) return { kind: "aborted", snapshot: null };
1161
+ const cached = build.cached.find((entry2) => entry2.teamId === access.teamId && entry2.projectId === access.projectId);
1162
+ if (!build.full && cached !== void 0) return { kind: "up-to-date", snapshot: cached };
1163
+ const why = build.full ? "full" : build.ref === null ? "no-snapshot" : "base";
1164
+ const built = await buildSnapshot(
1165
+ context,
1166
+ {
1167
+ prepared: build.plan,
1168
+ access,
1169
+ user,
1170
+ secrets,
1171
+ why: why === "no-snapshot" ? { kind: why, rejected: [] } : { kind: why }
1172
+ },
1173
+ control,
1174
+ progress
1175
+ );
1176
+ if (built.kind === "aborted") return { kind: "aborted", snapshot: null };
1177
+ if (built.kind !== "ok") return built;
1178
+ const { entry, cacheFailure, ms, sizeBytes } = built.value;
1179
+ if (signal.aborted) return { kind: "aborted", snapshot: { entry, cached: cacheFailure === null } };
1180
+ return cacheFailure === null ? { kind: "built", snapshot: entry, ms, sizeBytes } : { kind: "not-cached", snapshot: entry, failure: cacheFailure };
1181
+ }
1182
+
1183
+ // src/runner/live/user.ts
1184
+ import { userInfo } from "node:os";
1185
+ function localUserName() {
1186
+ try {
1187
+ return userInfo().username;
1188
+ } catch {
1189
+ return "unknown";
1190
+ }
1191
+ }
1192
+
1193
+ // src/runner/snapshot-inspect.ts
1194
+ async function inspectSnapshotCache(context, request2) {
1195
+ const { checkout, runnerSnapshots } = context;
1196
+ const { recipe } = request2;
1197
+ const listed = await runnerSnapshots.listEntries();
1198
+ if (!listed.ok) return { kind: "cache-unreadable", ...listed.failure };
1199
+ const { directory, entries, unreadable } = listed.value;
1200
+ const now = context.clock.now();
1201
+ const ofRecipe = (entry) => recipe !== void 0 && entry.recipeName === recipe.name && entry.region === recipe.region && entry.runtime === recipe.runtime;
1202
+ const shows = (entry) => request2.all || recipe === void 0 || ofRecipe(entry);
1203
+ const shown = entries.filter(shows);
1204
+ const root = await checkout.repositoryRoot({ cwd: request2.cwd });
1205
+ const head2 = root.ok ? await checkout.head({ repoRoot: root.value }) : void 0;
1206
+ if (!root.ok || head2 === void 0 || !head2.ok) {
1207
+ return {
1208
+ kind: "ok",
1209
+ inspection: {
1210
+ directory,
1211
+ checkout: null,
1212
+ picking: { kind: "none", why: "no-checkout" },
1213
+ snapshots: shown.map((entry) => unchecked(entry, now)),
1214
+ unreadable
1215
+ }
1216
+ };
1217
+ }
1218
+ const repoRoot = root.value;
1219
+ const resolved = recipe === void 0 ? void 0 : await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1220
+ if (resolved?.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1221
+ if (recipe === void 0 || resolved === void 0 || resolved.kind !== "resolved") {
1222
+ return {
1223
+ kind: "ok",
1224
+ inspection: {
1225
+ directory,
1226
+ checkout: { repoRoot, head: head2.value, mergeBase: null },
1227
+ picking: { kind: "none", why: recipe === void 0 ? "no-recipe" : "no-base" },
1228
+ snapshots: shown.map((entry) => unchecked(entry, now)),
1229
+ unreadable
1230
+ }
1231
+ };
1232
+ }
1233
+ const mergeBase = resolved.base;
1234
+ const steps = await snapshotStepsAt(checkout, { repoRoot, base: mergeBase, recipe });
1235
+ if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1236
+ const afterBase = await checkout.commitCount({ repoRoot, from: mergeBase, to: "HEAD" });
1237
+ if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
1238
+ const read = classifySnapshotEntries(context, {
1239
+ entries,
1240
+ recipe,
1241
+ base: mergeBase,
1242
+ snapshotKey: steps.key,
1243
+ commitsAfterBase: afterBase.value
1244
+ });
1245
+ const owners = new Map(read.candidates.map(({ entry }) => [`${entry.teamId}\0${entry.projectId}`, entry]));
1246
+ const picked = /* @__PURE__ */ new Set();
1247
+ for (const owner of owners.values()) {
1248
+ const pick = pickSnapshot(read.candidates, owner);
1249
+ if (pick !== void 0) picked.add(pick);
1250
+ }
1251
+ const place = historyPlacer(context, { repoRoot, mergeBase, commitsAfterBase: afterBase.value });
1252
+ const snapshots = [];
1253
+ for (const verdict of read.verdicts) {
1254
+ const { entry } = verdict;
1255
+ if (!shows(entry)) continue;
1256
+ const expired = isExpiredEntry(entry, now);
1257
+ if (verdict.kind === "candidate") {
1258
+ const { candidate } = verdict;
1259
+ snapshots.push({
1260
+ entry,
1261
+ inHistory: true,
1262
+ builtBehind: candidate.builtBehind,
1263
+ expired,
1264
+ picked: picked.has(candidate),
1265
+ reason: null
1266
+ });
1267
+ continue;
1268
+ }
1269
+ const placed = await place(entry.base);
1270
+ if (!placed.ok) return { kind: "checkout-failed", failure: placed.failure };
1271
+ snapshots.push({
1272
+ entry,
1273
+ ...placed.value,
1274
+ expired,
1275
+ picked: false,
1276
+ reason: verdict.kind === "rejected" ? verdict.rejection.reason : "other-recipe"
1277
+ });
1278
+ }
1279
+ return {
1280
+ kind: "ok",
1281
+ inspection: {
1282
+ directory,
1283
+ checkout: { repoRoot, head: head2.value, mergeBase: { commit: mergeBase, ref: resolved.ref } },
1284
+ picking: { kind: "recipe", recipe: recipe.name },
1285
+ snapshots,
1286
+ unreadable
1287
+ }
1288
+ };
1289
+ }
1290
+ function unchecked(entry, now) {
1291
+ return {
1292
+ entry,
1293
+ inHistory: null,
1294
+ builtBehind: null,
1295
+ expired: isExpiredEntry(entry, now),
1296
+ picked: false,
1297
+ reason: null
1298
+ };
1299
+ }
1300
+ function historyPlacer(context, request2) {
1301
+ const { repoRoot } = request2;
1302
+ const known = /* @__PURE__ */ new Map([
1303
+ [request2.mergeBase, { inHistory: true, builtBehind: request2.commitsAfterBase }]
1304
+ ]);
1305
+ return async (base) => {
1306
+ const answer = known.get(base);
1307
+ if (answer !== void 0) return { ok: true, value: answer };
1308
+ const contained = await context.checkout.contains({ repoRoot, ancestor: base, descendant: "HEAD" });
1309
+ if (!contained.ok) return contained;
1310
+ let placed = { inHistory: false, builtBehind: null };
1311
+ if (contained.value) {
1312
+ const counted = await context.checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
1313
+ if (!counted.ok) return counted;
1314
+ placed = { inHistory: true, builtBehind: counted.value };
1315
+ }
1316
+ known.set(base, placed);
1317
+ return { ok: true, value: placed };
1318
+ };
1319
+ }
1320
+
1321
+ // src/runner/live/checkout-gateway.ts
1322
+ import { execFile, spawn } from "node:child_process";
1323
+
1324
+ // src/runner/live/git-output.ts
1325
+ function splitNul(output) {
1326
+ const text = typeof output === "string" ? output : Buffer.from(output).toString("utf8");
1327
+ return text.split("\0").filter((entry) => entry.length > 0);
1328
+ }
1329
+ function submodulePaths(entries) {
1330
+ return entries.filter((entry) => entry.startsWith("160000 ")).map((entry) => entry.slice(entry.indexOf(" ") + 1));
1331
+ }
1332
+ function partitionUntracked(entries) {
1333
+ const files = [];
1334
+ const nestedRepositories = [];
1335
+ for (const entry of entries) {
1336
+ if (entry.endsWith("/")) nestedRepositories.push(entry.slice(0, -1));
1337
+ else files.push(entry);
1338
+ }
1339
+ return { files, nestedRepositories };
1340
+ }
1341
+ function displayCommand(command, args) {
1342
+ return [command, ...args].map(shellQuote).join(" ");
1343
+ }
1344
+ function shellQuote(argument) {
1345
+ return /^[\w@%+=:,./^{}-]+$/.test(argument) ? argument : `'${argument.replaceAll("'", `'\\''`)}'`;
1346
+ }
1347
+
1348
+ // src/runner/live/checkout-gateway.ts
1349
+ var GIT_MAX_BUFFER = 1024 * 1024 * 1024;
1350
+ var DIFF_OPTIONS = [
1351
+ "--no-color",
1352
+ "--no-ext-diff",
1353
+ "--no-textconv",
1354
+ "--no-renames",
1355
+ "--no-relative",
1356
+ "--ignore-submodules"
1357
+ ];
1358
+ function liveCheckoutGateway() {
1359
+ return {
1360
+ repositoryRoot: ({ cwd }) => repositoryRoot(cwd),
1361
+ head: ({ repoRoot }) => head(repoRoot),
1362
+ baseCandidate: ({ repoRoot, ref }) => baseCandidate(repoRoot, ref),
1363
+ resolveCommit: ({ repoRoot, ref }) => resolveCommit(repoRoot, ref),
1364
+ contains: ({ repoRoot, ancestor, descendant }) => contains(repoRoot, ancestor, descendant),
1365
+ commitCount: ({ repoRoot, from, to }) => commitCount(repoRoot, from, to),
1366
+ readFileAt: ({ repoRoot, commit, path }) => readFileAt(repoRoot, commit, path),
1367
+ submodules: ({ repoRoot }) => submodules(repoRoot),
1368
+ assembleUpload: ({ repoRoot, base }) => assembleUpload(repoRoot, base),
1369
+ baseArchive: ({ repoRoot, base }) => baseArchive(repoRoot, base)
1370
+ };
1371
+ }
1372
+ async function repositoryRoot(cwd) {
1373
+ const run = await git(cwd, ["rev-parse", "--show-toplevel"]);
1374
+ return run.ok ? { ok: true, value: run.stdout.toString("utf8").trim() } : run;
1375
+ }
1376
+ async function head(repoRoot) {
1377
+ const [commit, branch, status] = await Promise.all([
1378
+ git(repoRoot, ["rev-parse", "--verify", "HEAD"]),
1379
+ git(repoRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
1380
+ git(repoRoot, ["status", "--porcelain", "-z", "--untracked-files=normal"])
1381
+ ]);
1382
+ if (!commit.ok) return commit;
1383
+ if (!branch.ok && branch.exitCode !== 1) return branch;
1384
+ if (!status.ok) return status;
1385
+ return {
1386
+ ok: true,
1387
+ value: {
1388
+ branch: branch.ok ? branch.stdout.toString("utf8").trim() : null,
1389
+ commit: commit.stdout.toString("utf8").trim(),
1390
+ dirty: status.stdout.length > 0
1391
+ }
1392
+ };
1393
+ }
1394
+ async function baseCandidate(repoRoot, ref) {
1395
+ const exists = await git(repoRoot, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
1396
+ if (!exists.ok) return exists.exitCode === 1 ? { kind: "missing-ref" } : { kind: "failed", failure: exists.failure };
1397
+ const mergeBase = await git(repoRoot, ["merge-base", "HEAD", ref]);
1398
+ if (!mergeBase.ok)
1399
+ return mergeBase.exitCode === 1 ? { kind: "unrelated" } : { kind: "failed", failure: mergeBase.failure };
1400
+ return { kind: "merge-base", base: mergeBase.stdout.toString("utf8").trim() };
1401
+ }
1402
+ async function resolveCommit(repoRoot, ref) {
1403
+ const run = await git(repoRoot, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`]);
1404
+ if (!run.ok) return run.exitCode === 1 ? { ok: true, value: null } : run;
1405
+ return { ok: true, value: run.stdout.toString("utf8").trim() };
1406
+ }
1407
+ async function contains(repoRoot, ancestor, descendant) {
1408
+ const present = await git(repoRoot, ["cat-file", "-e", `${ancestor}^{commit}`]);
1409
+ if (!present.ok) return { ok: true, value: false };
1410
+ const run = await git(repoRoot, ["merge-base", "--is-ancestor", ancestor, descendant]);
1411
+ if (run.ok) return { ok: true, value: true };
1412
+ return run.exitCode === 1 ? { ok: true, value: false } : run;
1413
+ }
1414
+ async function commitCount(repoRoot, from, to) {
1415
+ const run = await git(repoRoot, ["rev-list", "--count", `${from}..${to}`]);
1416
+ if (!run.ok) return run;
1417
+ const count = Number(run.stdout.toString("utf8").trim());
1418
+ return Number.isSafeInteger(count) ? { ok: true, value: count } : { ok: false, failure: { message: `git rev-list printed no count for ${from}..${to}` } };
1419
+ }
1420
+ async function readFileAt(repoRoot, commit, path) {
1421
+ const object = `${commit}:${path}`;
1422
+ const type = await git(repoRoot, ["cat-file", "-t", object]);
1423
+ if (!type.ok || type.stdout.toString("utf8").trim() !== "blob") return { kind: "missing" };
1424
+ const run = await git(repoRoot, ["cat-file", "blob", object]);
1425
+ return run.ok ? { kind: "found", text: run.stdout.toString("utf8") } : { kind: "failed", failure: run.failure };
1426
+ }
1427
+ async function submodules(repoRoot) {
1428
+ const run = await git(repoRoot, ["ls-files", "--stage", "-z"]);
1429
+ return run.ok ? { ok: true, value: submodulePaths(splitNul(run.stdout)) } : run;
1430
+ }
1431
+ async function assembleUpload(repoRoot, base) {
1432
+ const [patch, others] = await Promise.all([
1433
+ git(repoRoot, [
1434
+ "diff",
1435
+ "--binary",
1436
+ // A user's `diff.context=0` makes patches that need special flags to apply.
1437
+ "--unified=3",
1438
+ ...DIFF_OPTIONS,
1439
+ "--src-prefix=a/",
1440
+ "--dst-prefix=b/",
1441
+ base
1442
+ ]),
1443
+ git(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"])
1444
+ ]);
1445
+ if (!patch.ok) return patch;
1446
+ if (!others.ok) return others;
1447
+ const { files, nestedRepositories } = partitionUntracked(splitNul(others.stdout));
1448
+ let untrackedTarball;
1449
+ if (files.length > 0) {
1450
+ const tarball = await createTarball(repoRoot, files);
1451
+ if (!tarball.ok) return tarball;
1452
+ untrackedTarball = tarball.value;
1453
+ }
1454
+ return { ok: true, value: { patch: patch.stdout, untracked: files, untrackedTarball, nestedRepositories } };
1455
+ }
1456
+ async function baseArchive(repoRoot, base) {
1457
+ const [tarball, fileList] = await Promise.all([
1458
+ // LF line endings, as the patch has them: with `core.autocrlf=true`, the Git for Windows default, `git archive`
1459
+ // writes CRLF files the patch doesn't apply to.
1460
+ git(repoRoot, ["-c", "core.autocrlf=false", "-c", "core.eol=lf", "archive", "--format=tar.gz", base]),
1461
+ git(repoRoot, ["ls-tree", "-r", "--name-only", "-z", "--full-tree", base])
1462
+ ]);
1463
+ if (!tarball.ok) return tarball;
1464
+ if (!fileList.ok) return fileList;
1465
+ return {
1466
+ ok: true,
1467
+ value: { tarball: tarball.stdout, fileList: fileList.stdout, files: splitNul(fileList.stdout).length }
1468
+ };
1469
+ }
1470
+ function git(repoRoot, args) {
1471
+ const argv = ["-C", repoRoot, ...args];
1472
+ return new Promise((resolve) => {
1473
+ execFile(
1474
+ "git",
1475
+ argv,
1476
+ { encoding: "buffer", maxBuffer: GIT_MAX_BUFFER, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } },
1477
+ (error, stdout, stderr) => {
1478
+ if (error === null) {
1479
+ resolve({ ok: true, stdout });
1480
+ return;
1481
+ }
1482
+ const subcommand = args.find((arg, index) => arg !== "-c" && args[index - 1] !== "-c") ?? "";
1483
+ const detail = stderr.toString("utf8").trim() || error.message;
1484
+ resolve({
1485
+ ok: false,
1486
+ exitCode: typeof error.code === "number" ? error.code : void 0,
1487
+ failure: { message: `git ${subcommand} failed: ${detail}`, displayCommand: displayCommand("git", argv) }
1488
+ });
1489
+ }
1490
+ );
1491
+ });
1492
+ }
1493
+ function createTarball(repoRoot, paths) {
1494
+ const args = ["--null", "-czf", "-", "-C", repoRoot, "-T", "-"];
1495
+ const command = displayCommand("tar", args);
1496
+ return new Promise((resolve) => {
1497
+ const child = spawn("tar", args, {
1498
+ stdio: ["pipe", "pipe", "pipe"],
1499
+ env: { ...process.env, COPYFILE_DISABLE: "1" }
1500
+ });
1501
+ const chunks = [];
1502
+ const errors = [];
1503
+ let stdinError;
1504
+ let spawnError;
1505
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
1506
+ child.stderr.on("data", (chunk) => errors.push(chunk));
1507
+ child.stdin.on("error", (error) => {
1508
+ stdinError = error;
1509
+ });
1510
+ child.once("error", (error) => {
1511
+ spawnError = error;
1512
+ });
1513
+ child.once("close", (code) => {
1514
+ const stderr = Buffer.concat(errors).toString("utf8").trim();
1515
+ if (spawnError !== void 0)
1516
+ resolve({ ok: false, failure: { message: `tar failed: ${spawnError.message}`, displayCommand: command } });
1517
+ else if (code !== 0)
1518
+ resolve({
1519
+ ok: false,
1520
+ failure: { message: `tar failed (exit ${code ?? "none"}): ${stderr}`, displayCommand: command }
1521
+ });
1522
+ else if (stdinError !== void 0)
1523
+ resolve({
1524
+ ok: false,
1525
+ failure: { message: `tar didn't read the whole path list: ${stdinError.message}`, displayCommand: command }
1526
+ });
1527
+ else resolve({ ok: true, value: Buffer.concat(chunks) });
1528
+ });
1529
+ child.stdin.end(paths.map((path) => `${path}\0`).join(""));
1530
+ });
1531
+ }
1532
+
1533
+ // src/runner/live/sandbox-errors.ts
1534
+ function apiStatus(error) {
1535
+ if (typeof error !== "object" || error === null) return void 0;
1536
+ const response = error.response;
1537
+ if (typeof response !== "object" || response === null) return void 0;
1538
+ const status = response.status;
1539
+ return typeof status === "number" ? status : void 0;
1540
+ }
1541
+ function isAbortError(error) {
1542
+ return typeof error === "object" && error !== null && error.name === "AbortError";
1543
+ }
1544
+ function sandboxFailure(error, signal) {
1545
+ if (signal?.aborted === true || isAbortError(error)) return { kind: "aborted" };
1546
+ return { kind: "api", status: apiStatus(error), message: error instanceof Error ? error.message : String(error) };
1547
+ }
1548
+
1549
+ // src/runner/live/sandbox-gateway.ts
1550
+ var TERMINATE_GRACE_MS = 1e4;
1551
+ var KILL_GRACE_MS = 5e3;
1552
+ var STDERR_MESSAGE_CHARS = 1e3;
1553
+ var SNAPSHOT_GONE_STATUS = 410;
1554
+ function liveRunnerSandboxGateway() {
1555
+ let loading;
957
1556
  const sdk = () => loading ??= import("@vercel/sandbox");
958
1557
  const held = /* @__PURE__ */ new WeakMap();
959
1558
  const holding = (sandbox) => {
@@ -1302,165 +1901,52 @@ async function endsWithin(command, ms) {
1302
1901
  return false;
1303
1902
  } finally {
1304
1903
  clearTimeout(timer);
1305
- }
1306
- }
1307
- function isAborted(signal) {
1308
- return signal?.aborted === true;
1309
- }
1310
-
1311
- // src/runner/live/terminal.ts
1312
- function liveRunnerTerminal(options) {
1313
- const stdout = options.stdout ?? process.stdout;
1314
- const stderr = options.stderr ?? process.stderr;
1315
- let failed = false;
1316
- let listening = false;
1317
- const fail = () => {
1318
- failed = true;
1319
- };
1320
- const write = (stream, text) => {
1321
- if (failed) return;
1322
- if (!listening) {
1323
- stdout.on("error", fail);
1324
- stderr.on("error", fail);
1325
- listening = true;
1326
- }
1327
- try {
1328
- stream.write(text);
1329
- } catch {
1330
- fail();
1331
- }
1332
- };
1333
- return {
1334
- color: stdout.isTTY === true && options.env["NO_COLOR"] === void 0,
1335
- writeStdout: (text) => write(stdout, text),
1336
- writeStderr: (text) => write(stderr, text)
1337
- };
1338
- }
1339
-
1340
- // src/runner/live/snapshot-cache-gateway.ts
1341
- import { randomBytes } from "node:crypto";
1342
- import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
1343
- import { join } from "node:path";
1344
-
1345
- // src/runner/snapshot-cache.ts
1346
- import { createHash as createHash2 } from "node:crypto";
1347
- var RUNNER_SNAPSHOTS_SUBPATH = ["runner", "snapshots"];
1348
- var SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1e3;
1349
- var SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1e3;
1350
- function snapshotEntryIdentity(entry) {
1351
- return createHash2("sha256").update(
1352
- [
1353
- entry.teamId,
1354
- entry.projectId,
1355
- entry.region,
1356
- entry.runtime,
1357
- entry.recipeName,
1358
- entry.snapshotKey,
1359
- entry.base,
1360
- ...isBranchEntry(entry) ? [entry.branch, entry.repoRoot] : []
1361
- ].join("\0")
1362
- ).digest("hex").slice(0, 32);
1363
- }
1364
- function isBranchEntry(entry) {
1365
- return entry.branch !== void 0 && entry.head !== void 0 && entry.repoRoot !== void 0;
1366
- }
1367
- function snapshotEntryFileName(entry) {
1368
- return `${snapshotEntryIdentity(entry)}.json`;
1369
- }
1370
- function isExpiredEntry(entry, now) {
1371
- return Date.parse(entry.expiresAt) <= now.getTime();
1372
- }
1373
- function hasTimeLeft(entry, now) {
1374
- return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
1375
- }
1376
- async function findSnapshotCandidates(context, request2) {
1377
- const { checkout, runnerSnapshots } = context;
1378
- const { repoRoot, recipe, branch } = request2;
1379
- const notes = [];
1380
- const listed = await runnerSnapshots.listEntries();
1381
- if (!listed.ok) return { candidates: [], notes: [{ kind: "cache-unreadable", failure: listed.failure }] };
1382
- const now = context.clock.now();
1383
- const live = [];
1384
- for (const entry of listed.value.entries) {
1385
- if (isExpiredEntry(entry, now)) {
1386
- const removed = await runnerSnapshots.removeEntry(entry);
1387
- if (!removed.ok) notes.push({ kind: "expired-entry-not-removed", entry, failure: removed.failure });
1388
- continue;
1389
- }
1390
- if (entry.region === recipe.region && entry.runtime === recipe.runtime && entry.recipeName === recipe.name && (isBranchEntry(entry) ? entry.branch === branch && entry.repoRoot === repoRoot : entry.branch === void 0) && hasTimeLeft(entry, now))
1391
- live.push(entry);
1392
- }
1393
- const keysByBase = /* @__PURE__ */ new Map();
1394
- for (const base of new Set(live.map((entry) => entry.base))) {
1395
- const contained = await checkout.contains({ repoRoot, ancestor: base, descendant: "HEAD" });
1396
- if (!contained.ok) {
1397
- notes.push({ kind: "candidate-check-failed", base, failure: contained.failure });
1398
- continue;
1399
- }
1400
- if (!contained.value) continue;
1401
- const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
1402
- if (!steps.ok) {
1403
- notes.push({ kind: "candidate-steps-failed", base, path: steps.path, problem: steps.problem });
1404
- continue;
1904
+ }
1905
+ }
1906
+ function isAborted(signal) {
1907
+ return signal?.aborted === true;
1908
+ }
1909
+
1910
+ // src/runner/live/terminal.ts
1911
+ function liveRunnerTerminal(options) {
1912
+ const stdout = options.stdout ?? process.stdout;
1913
+ const stderr = options.stderr ?? process.stderr;
1914
+ let failed = false;
1915
+ let listening = false;
1916
+ const fail = () => {
1917
+ failed = true;
1918
+ };
1919
+ const write = (stream, text) => {
1920
+ if (failed) return;
1921
+ if (!listening) {
1922
+ stdout.on("error", fail);
1923
+ stderr.on("error", fail);
1924
+ listening = true;
1405
1925
  }
1406
- keysByBase.set(base, steps.key);
1407
- }
1408
- const matching = live.filter((entry) => keysByBase.get(entry.base) === entry.snapshotKey);
1409
- const commitTimes = /* @__PURE__ */ new Map();
1410
- for (const base of new Set(matching.map((entry) => entry.base))) {
1411
- const time = await checkout.commitTime({ repoRoot, commit: base });
1412
- if (time.ok) commitTimes.set(base, time.value);
1413
- else notes.push({ kind: "candidate-check-failed", base, failure: time.failure });
1414
- }
1415
- const bases = [...commitTimes.keys()];
1416
- const ancestors = new Map(bases.map((base) => [base, []]));
1417
- for (const ancestor of bases)
1418
- for (const descendant of bases) {
1419
- if (ancestor === descendant) continue;
1420
- const contained = await checkout.contains({ repoRoot, ancestor, descendant });
1421
- if (!contained.ok) notes.push({ kind: "candidate-check-failed", base: ancestor, failure: contained.failure });
1422
- else if (contained.value) ancestors.get(descendant)?.push(ancestor);
1926
+ try {
1927
+ stream.write(text);
1928
+ } catch {
1929
+ fail();
1423
1930
  }
1424
- const candidates = matching.flatMap((entry) => {
1425
- const commitTime2 = commitTimes.get(entry.base);
1426
- return commitTime2 === void 0 ? [] : [{ entry, commitTime: commitTime2, ancestorBases: [...ancestors.get(entry.base) ?? []] }];
1427
- });
1428
- return { candidates, notes };
1429
- }
1430
- function pickSnapshot(candidates, owner) {
1431
- const owned = candidates.filter(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId).toSorted((a, b) => b.commitTime - a.commitTime || Date.parse(b.entry.expiresAt) - Date.parse(a.entry.expiresAt));
1432
- const nearest = owned.find(
1433
- (candidate) => owned.every(
1434
- (other) => other.entry.base === candidate.entry.base || candidate.ancestorBases.includes(other.entry.base)
1435
- )
1436
- ) ?? owned[0];
1437
- if (nearest === void 0) return void 0;
1438
- return owned.filter(({ entry }) => entry.base === nearest.entry.base).toSorted(
1439
- (a, b) => Number(isBranchEntry(b.entry)) - Number(isBranchEntry(a.entry)) || Date.parse(b.entry.expiresAt) - Date.parse(a.entry.expiresAt)
1440
- )[0];
1441
- }
1442
- async function dropBranchSnapshots(runnerSnapshots, request2) {
1443
- const { branch, repoRoot, owner, recipe } = request2;
1444
- const listed = await runnerSnapshots.listEntries();
1445
- if (!listed.ok) return { snapshotIds: [], failures: [listed.failure] };
1446
- const snapshotIds = [];
1447
- const failures = [];
1448
- for (const entry of listed.value.entries) {
1449
- if (!isBranchEntry(entry) || entry.branch !== branch || entry.repoRoot !== repoRoot || entry.teamId !== owner.teamId || entry.projectId !== owner.projectId || entry.region !== recipe.region || entry.runtime !== recipe.runtime || entry.recipeName !== recipe.name)
1450
- continue;
1451
- const removed = await runnerSnapshots.removeEntry(entry);
1452
- if (removed.ok) snapshotIds.push(entry.snapshotId);
1453
- else failures.push(removed.failure);
1454
- }
1455
- return { snapshotIds, failures };
1931
+ };
1932
+ return {
1933
+ color: stdout.isTTY === true && options.env["NO_COLOR"] === void 0,
1934
+ writeStdout: (text) => write(stdout, text),
1935
+ writeStderr: (text) => write(stderr, text)
1936
+ };
1456
1937
  }
1457
1938
 
1939
+ // src/runner/live/snapshot-cache-gateway.ts
1940
+ import { randomBytes } from "node:crypto";
1941
+ import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
1942
+ import { join } from "node:path";
1943
+
1458
1944
  // src/runner/live/snapshot-records.ts
1459
- import { z as z3 } from "zod";
1460
- var isoTime = z3.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "not a time" });
1461
- var nonEmpty = z3.string().min(1);
1462
- var entrySchema = z3.object({
1463
- version: z3.literal(1),
1945
+ import { z as z4 } from "zod";
1946
+ var isoTime = z4.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "not a time" });
1947
+ var nonEmpty = z4.string().min(1);
1948
+ var entrySchema = z4.object({
1949
+ version: z4.literal(1),
1464
1950
  teamId: nonEmpty,
1465
1951
  projectId: nonEmpty,
1466
1952
  region: nonEmpty,
@@ -1468,19 +1954,10 @@ var entrySchema = z3.object({
1468
1954
  recipeName: nonEmpty,
1469
1955
  snapshotKey: nonEmpty,
1470
1956
  base: nonEmpty,
1471
- branch: nonEmpty.exactOptional(),
1472
- head: nonEmpty.exactOptional(),
1473
- repoRoot: nonEmpty.exactOptional(),
1474
1957
  snapshotId: nonEmpty,
1475
1958
  createdAt: isoTime,
1476
1959
  expiresAt: isoTime
1477
- }).refine(
1478
- (entry) => {
1479
- const present = [entry.branch, entry.head, entry.repoRoot].filter((value) => value !== void 0).length;
1480
- return present === 0 || present === 3;
1481
- },
1482
- { message: "has some of branch, head and repoRoot without the others" }
1483
- );
1960
+ });
1484
1961
  function parseSnapshotEntry(text) {
1485
1962
  let json;
1486
1963
  try {
@@ -1500,7 +1977,7 @@ function parseSnapshotEntry(text) {
1500
1977
  return { ok: true, value: entry };
1501
1978
  }
1502
1979
  function snapshotEntryText(entry) {
1503
- const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base, branch, head: head2, repoRoot } = entry;
1980
+ const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base } = entry;
1504
1981
  const { snapshotId, createdAt, expiresAt } = entry;
1505
1982
  const record = {
1506
1983
  version: 1,
@@ -1511,9 +1988,6 @@ function snapshotEntryText(entry) {
1511
1988
  recipeName,
1512
1989
  snapshotKey: snapshotKey2,
1513
1990
  base,
1514
- ...branch === void 0 ? {} : { branch },
1515
- ...head2 === void 0 ? {} : { head: head2 },
1516
- ...repoRoot === void 0 ? {} : { repoRoot },
1517
1991
  snapshotId,
1518
1992
  createdAt,
1519
1993
  expiresAt
@@ -1611,8 +2085,6 @@ async function prepareRunner(context, request2) {
1611
2085
  const root = await checkout.repositoryRoot({ cwd: request2.cwd });
1612
2086
  if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
1613
2087
  const repoRoot = root.value;
1614
- const head2 = await checkout.head({ repoRoot });
1615
- if (!head2.ok) return { kind: "checkout-failed", failure: head2.failure };
1616
2088
  const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1617
2089
  if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1618
2090
  if (resolved.kind === "no-base-ref") return resolved;
@@ -1626,14 +2098,21 @@ async function prepareRunner(context, request2) {
1626
2098
  if (!vcpus.ok) return { kind: "invalid-recipe", path: ["vcpus"], problem: vcpus.problem };
1627
2099
  const upload = await checkout.assembleUpload({ repoRoot, base });
1628
2100
  if (!upload.ok) return { kind: "checkout-failed", failure: upload.failure };
1629
- const reuseBranch = request2.trustBranchSnapshots || !runStepTakesSecret(recipe);
1630
- const cache = request2.rebuild ? { candidates: [], notes: [] } : await findSnapshotCandidates(context, { repoRoot, recipe, branch: reuseBranch ? head2.value.branch : null });
2101
+ const afterBase = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
2102
+ if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
2103
+ const listing = await removeExpiredEntries(context);
2104
+ const cache = classifySnapshotEntries(context, {
2105
+ entries: listing.entries,
2106
+ recipe,
2107
+ base,
2108
+ snapshotKey: steps.key,
2109
+ commitsAfterBase: afterBase.value
2110
+ });
1631
2111
  return {
1632
2112
  kind: "ok",
1633
2113
  prepared: {
1634
2114
  recipe,
1635
2115
  repoRoot,
1636
- head: head2.value,
1637
2116
  base,
1638
2117
  baseRef: resolved.ref,
1639
2118
  toolchains: steps.toolchains,
@@ -1642,17 +2121,12 @@ async function prepareRunner(context, request2) {
1642
2121
  vcpus: vcpus.vcpus,
1643
2122
  upload: upload.value,
1644
2123
  candidates: cache.candidates,
1645
- rebuild: request2.rebuild,
1646
- notes: cache.notes,
1647
- save: plannedSave(request2.save, head2.value.branch)
2124
+ rejected: cache.rejected,
2125
+ commitsAfterBase: afterBase.value,
2126
+ notes: listing.notes
1648
2127
  }
1649
2128
  };
1650
2129
  }
1651
- function plannedSave(mode, branch) {
1652
- if (mode === "never") return null;
1653
- if (branch !== null) return { kind: "branch", branch, always: mode === "always" };
1654
- return mode === "always" ? { kind: "skipped", reason: "detached-head" } : null;
1655
- }
1656
2130
 
1657
2131
  // src/runner/sandboxed-command.ts
1658
2132
  import { posix } from "node:path";
@@ -1678,234 +2152,88 @@ async function runCommandInSandbox(context, request2, control, progress) {
1678
2152
  const { runner } = request2;
1679
2153
  const terminal = context.runnerTerminal;
1680
2154
  const command = sandboxedCommand({ argv: request2.argv, repoRoot: runner.repoRoot, cwd: runner.cwd });
1681
- const env = sandboxEnvironment({
1682
- cwd: runner.cwd,
1683
- loginPath: runner.loginPath,
1684
- color: terminal.color,
1685
- env: runner.env,
1686
- runPayload: request2.runPayload
1687
- });
1688
- await progress.emit({ kind: "command-output-started", sandbox: runner.sandbox.name, region: runner.region });
1689
- const startedAt = context.clock.now().getTime();
1690
- const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
1691
- const write = (stream, text) => {
1692
- if (text === "") return;
1693
- const local = rewritePaths(text, SANDBOX_ROOT, runner.repoRoot);
1694
- if (stream === "stdout") terminal.writeStdout(local);
1695
- else terminal.writeStderr(local);
1696
- };
1697
- const following = followTestEvents(context, runner, request2.testEvents, control.kill);
1698
- const ran = await context.runnerSandboxes.runCommand(
1699
- runner.sandbox,
1700
- { cmd: command.cmd, args: command.args, cwd: runner.cwd, env },
1701
- ({ stream, data }) => write(stream, splitters[stream].push(data)),
1702
- control.kill
1703
- );
1704
- const ms = context.clock.now().getTime() - startedAt;
1705
- write("stdout", splitters.stdout.flush());
1706
- write("stderr", splitters.stderr.flush());
1707
- await following?.end(ran.ok && !control.kill.aborted);
1708
- if (!ran.ok) {
1709
- if (ran.failure.kind !== "aborted")
1710
- return { kind: "failed", failure: sandboxApiFailure("run-command", ran.failure) };
1711
- await progress.emit({ kind: "command-stopped", command: posix.basename(command.cmd) });
1712
- return { kind: "killed" };
1713
- }
1714
- return { kind: "exited", exitCode: ran.value.exitCode, ms };
1715
- }
1716
- function followTestEvents(context, runner, testEvents, kill) {
1717
- if (testEvents === void 0) return void 0;
1718
- const stop = new AbortController();
1719
- const splitter = lineSplitter();
1720
- let handed = 0;
1721
- const hand = (lines) => {
1722
- for (const line of lines) {
1723
- handed += 1;
1724
- testEvents.onLine(line);
1725
- }
1726
- };
1727
- const followed = context.runnerSandboxes.followTestEvents(
1728
- runner.sandbox,
1729
- { path: SANDBOX_TEST_EVENTS_PATH },
1730
- ({ data }) => hand(splitLines(splitter.push(data))),
1731
- stop.signal
1732
- );
1733
- return {
1734
- async end(complete) {
1735
- stop.abort();
1736
- await followed;
1737
- if (!complete) {
1738
- hand(splitLines(splitter.flush()));
1739
- return;
1740
- }
1741
- const reader = lineSplitter();
1742
- let read = false;
1743
- const result = await context.runnerSandboxes.readTestEvents(
1744
- runner.sandbox,
1745
- { path: SANDBOX_TEST_EVENTS_PATH, fromLine: handed + 1 },
1746
- ({ data }) => {
1747
- if (!read) {
1748
- splitter.flush();
1749
- read = true;
1750
- }
1751
- hand(splitLines(reader.push(data)));
1752
- },
1753
- kill
1754
- );
1755
- hand(splitLines(read ? reader.flush() : splitter.flush()));
1756
- if (!result.ok && result.failure.kind === "api") testEvents.onIncomplete(result.failure.message);
1757
- }
1758
- };
1759
- }
1760
-
1761
- // src/runner/secrets.ts
1762
- var RUNNER_SECRET_MIN_LENGTH = 8;
1763
- function stepSecrets(values, names) {
1764
- return Object.fromEntries(
1765
- names.map((name) => {
1766
- const value = ownValue(values, name);
1767
- if (value === void 0) throw new Error(`stepSecrets: no value for runner secret ${name}`);
1768
- return [name, value];
1769
- })
1770
- );
1771
- }
1772
- function readRunnerSecrets(recipe, env) {
1773
- const values = [];
1774
- const variables = [];
1775
- for (const name of recipe.secrets) {
1776
- const value = ownValue(env, name);
1777
- if (value === void 0 || value === "") variables.push({ name, problem: "missing" });
1778
- else if (/[\r\n]/.test(value)) variables.push({ name, problem: "multiline" });
1779
- else if (value.length < RUNNER_SECRET_MIN_LENGTH) variables.push({ name, problem: "short" });
1780
- else values.push([name, value]);
1781
- }
1782
- return variables.length === 0 ? { ok: true, values: Object.fromEntries(values) } : { ok: false, variables };
1783
- }
1784
- function ownValue(map, name) {
1785
- return Object.hasOwn(map, name) ? map[name] : void 0;
1786
- }
1787
-
1788
- // src/runner/ready.ts
1789
- import { posix as posix2 } from "node:path";
1790
-
1791
- // src/runner/context.ts
1792
- function runnerPurpose(recipeName) {
1793
- return `storm-runner-${recipeName}`;
1794
- }
1795
- function runnerTags(recipeName, role, user) {
1796
- return { purpose: runnerPurpose(recipeName), user, role };
1797
- }
1798
-
1799
- // src/runner/snapshot-build.ts
1800
- var BUILD_SANDBOX_TIMEOUT_MS = 30 * 6e4;
1801
- var BASE_INDEX_LABEL = "Committing the base's files";
1802
- async function buildSnapshot(context, request2, control, progress) {
1803
- const { prepared, access } = request2;
1804
- const { recipe, repoRoot, base } = prepared;
1805
- const { scope, signal } = control;
1806
- const now = () => context.clock.now().getTime();
1807
- const startedAt = now();
1808
- await progress.emit({
1809
- kind: "snapshot-build-started",
1810
- base,
1811
- reason: request2.reason,
1812
- summary: recipe.snapshot.summary ?? [...prepared.toolchains, ...prepared.prebuild].map(({ label }) => label).join(", ")
1813
- });
1814
- const [started, archive] = await Promise.all([
1815
- scope.startBuildSandbox(access, {
1816
- region: recipe.region,
1817
- runtime: recipe.runtime,
1818
- vcpus: recipe.snapshot.vcpus,
1819
- timeoutMs: BUILD_SANDBOX_TIMEOUT_MS,
1820
- tags: runnerTags(recipe.name, "snapshot-build", request2.user)
1821
- }),
1822
- context.checkout.baseArchive({ repoRoot, base })
1823
- ]);
1824
- if (!started.ok) return sandboxStop("start-build-sandbox", started.failure);
1825
- const sandbox = started.value;
1826
- await progress.emit({
1827
- kind: "sandbox-started",
1828
- role: "snapshot-build",
1829
- name: sandbox.name,
1830
- region: recipe.region,
1831
- vcpus: recipe.snapshot.vcpus,
1832
- ms: now() - startedAt
1833
- });
1834
- if (!archive.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: archive.failure } };
1835
- const staged = await context.runnerSandboxes.upload(
1836
- sandbox,
1837
- [
1838
- { name: STAGED_FILES.baseTarball, content: archive.value.tarball },
1839
- { name: STAGED_FILES.baseFileList, content: archive.value.fileList }
1840
- ],
1841
- signal
1842
- );
1843
- if (!staged.ok) return sandboxStop("upload", staged.failure);
1844
- const recipeStep = ({ label, script, secrets }) => ({
1845
- label,
1846
- script,
1847
- secrets: stepSecrets(request2.secrets, secrets)
1848
- });
1849
- const steps = [
1850
- ...prepared.toolchains.map(recipeStep),
1851
- { label: BASE_INDEX_LABEL, script: baseIndexScript(base, staged.value.directory) },
1852
- ...prepared.prebuild.map(recipeStep)
1853
- ];
1854
- await progress.emit({ kind: "output-started", section: "snapshot", sandbox: sandbox.name, region: recipe.region });
1855
- for (const step of steps) {
1856
- const ran = await runStep(context, { sandbox, phase: "snapshot", ...step }, progress, signal);
1857
- if (ran.kind === "succeeded") continue;
1858
- const stop = ran.kind === "exited" ? {
1859
- kind: "failed",
1860
- failure: { kind: "snapshot-build-step-failed", label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1861
- } : sandboxStop("run-script", ran.failure);
1862
- await progress.emit({
1863
- kind: "output-ended",
1864
- section: "snapshot",
1865
- outcome: stop.kind === "aborted" ? "stopped" : "failed"
1866
- });
1867
- return stop;
1868
- }
1869
- await progress.emit({ kind: "output-ended", section: "snapshot", outcome: "finished" });
1870
- if (signal.aborted) return { kind: "aborted" };
1871
- await progress.emit({ kind: "snapshot-saving" });
1872
- const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
1873
- if (!saved.ok) return sandboxStop("save-snapshot", saved.failure);
1874
- const savedAt2 = context.clock.now();
1875
- const entry = {
1876
- teamId: access.teamId,
1877
- projectId: access.projectId,
1878
- region: recipe.region,
1879
- runtime: recipe.runtime,
1880
- recipeName: recipe.name,
1881
- snapshotKey: prepared.snapshotKey,
1882
- base,
1883
- snapshotId: saved.value.snapshotId,
1884
- createdAt: savedAt2.toISOString(),
1885
- expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
2155
+ const env = sandboxEnvironment({
2156
+ cwd: runner.cwd,
2157
+ loginPath: runner.loginPath,
2158
+ color: terminal.color,
2159
+ env: runner.env,
2160
+ runPayload: request2.runPayload
2161
+ });
2162
+ await progress.emit({ kind: "command-output-started", sandbox: runner.sandbox.name, region: runner.region });
2163
+ const startedAt = context.clock.now().getTime();
2164
+ const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
2165
+ const write = (stream, text) => {
2166
+ if (text === "") return;
2167
+ const local = rewritePaths(text, SANDBOX_ROOT, runner.repoRoot);
2168
+ if (stream === "stdout") terminal.writeStdout(local);
2169
+ else terminal.writeStderr(local);
1886
2170
  };
1887
- const written = await context.runnerSnapshots.writeEntry(entry);
1888
- if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
1889
- const { branch } = prepared.head;
1890
- if (request2.reason === "rebuild" && branch !== null) {
1891
- const dropped = await dropBranchSnapshots(context.runnerSnapshots, { branch, repoRoot, owner: access, recipe });
1892
- if (dropped.snapshotIds.length > 0)
1893
- await progress.emit({ kind: "branch-snapshots-dropped", branch, snapshotIds: dropped.snapshotIds });
1894
- for (const failure of dropped.failures)
1895
- await progress.emit({ kind: "branch-snapshots-not-dropped", branch, failure });
2171
+ const following = followTestEvents(context, runner, request2.testEvents, control.kill);
2172
+ const ran = await context.runnerSandboxes.runCommand(
2173
+ runner.sandbox,
2174
+ { cmd: command.cmd, args: command.args, cwd: runner.cwd, env },
2175
+ ({ stream, data }) => write(stream, splitters[stream].push(data)),
2176
+ control.kill
2177
+ );
2178
+ const ms = context.clock.now().getTime() - startedAt;
2179
+ write("stdout", splitters.stdout.flush());
2180
+ write("stderr", splitters.stderr.flush());
2181
+ await following?.end(ran.ok && !control.kill.aborted);
2182
+ if (!ran.ok) {
2183
+ if (ran.failure.kind !== "aborted")
2184
+ return { kind: "failed", failure: sandboxApiFailure("run-command", ran.failure) };
2185
+ await progress.emit({ kind: "command-stopped", command: posix.basename(command.cmd) });
2186
+ return { kind: "killed" };
1896
2187
  }
1897
- const ms = now() - startedAt;
1898
- await progress.emit({
1899
- kind: "snapshot-built",
1900
- snapshotId: entry.snapshotId,
1901
- base,
1902
- ms,
1903
- sizeBytes: saved.value.sizeBytes
1904
- });
1905
- return { kind: "ok", value: { entry, ms, sizeBytes: saved.value.sizeBytes } };
2188
+ return { kind: "exited", exitCode: ran.value.exitCode, ms };
2189
+ }
2190
+ function followTestEvents(context, runner, testEvents, kill) {
2191
+ if (testEvents === void 0) return void 0;
2192
+ const stop = new AbortController();
2193
+ const splitter = lineSplitter();
2194
+ let handed = 0;
2195
+ const hand = (lines) => {
2196
+ for (const line of lines) {
2197
+ handed += 1;
2198
+ testEvents.onLine(line);
2199
+ }
2200
+ };
2201
+ const followed = context.runnerSandboxes.followTestEvents(
2202
+ runner.sandbox,
2203
+ { path: SANDBOX_TEST_EVENTS_PATH },
2204
+ ({ data }) => hand(splitLines(splitter.push(data))),
2205
+ stop.signal
2206
+ );
2207
+ return {
2208
+ async end(complete) {
2209
+ stop.abort();
2210
+ await followed;
2211
+ if (!complete) {
2212
+ hand(splitLines(splitter.flush()));
2213
+ return;
2214
+ }
2215
+ const reader = lineSplitter();
2216
+ let read = false;
2217
+ const result = await context.runnerSandboxes.readTestEvents(
2218
+ runner.sandbox,
2219
+ { path: SANDBOX_TEST_EVENTS_PATH, fromLine: handed + 1 },
2220
+ ({ data }) => {
2221
+ if (!read) {
2222
+ splitter.flush();
2223
+ read = true;
2224
+ }
2225
+ hand(splitLines(reader.push(data)));
2226
+ },
2227
+ kill
2228
+ );
2229
+ hand(splitLines(read ? reader.flush() : splitter.flush()));
2230
+ if (!result.ok && result.failure.kind === "api") testEvents.onIncomplete(result.failure.message);
2231
+ }
2232
+ };
1906
2233
  }
1907
2234
 
1908
2235
  // src/runner/ready.ts
2236
+ import { posix as posix2 } from "node:path";
1909
2237
  var APPLY_LABEL = "Applying your changes";
1910
2238
  async function readyRunner(context, request2, control, progress) {
1911
2239
  const { prepared, access } = request2;
@@ -1913,33 +2241,28 @@ async function readyRunner(context, request2, control, progress) {
1913
2241
  const { scope, signal } = control;
1914
2242
  const now = () => context.clock.now().getTime();
1915
2243
  if (signal.aborted) return { kind: "aborted" };
1916
- const picked = prepared.rebuild ? void 0 : pickSnapshot(prepared.candidates, access);
2244
+ const pick = pickSnapshot(prepared.candidates, access);
1917
2245
  let entry;
1918
- if (picked !== void 0) {
1919
- entry = picked.entry;
2246
+ if (pick !== void 0) {
2247
+ ({ entry } = pick);
1920
2248
  await progress.emit({
1921
2249
  kind: "snapshot-reused",
1922
2250
  snapshotId: entry.snapshotId,
1923
2251
  base: entry.base,
1924
- branch: entry.branch ?? null,
1925
- head: entry.head ?? null
2252
+ builtBehind: pick.builtBehind
1926
2253
  });
1927
2254
  } else {
1928
- const built2 = await buildSnapshot(
2255
+ const why = { kind: "no-snapshot", rejected: snapshotRejections(prepared, access) };
2256
+ const building = await buildSnapshot(
1929
2257
  context,
1930
- {
1931
- prepared,
1932
- access,
1933
- user: request2.user,
1934
- secrets: request2.secrets,
1935
- reason: prepared.rebuild ? "rebuild" : "no-snapshot"
1936
- },
2258
+ { prepared, access, user: request2.user, secrets: request2.secrets, why },
1937
2259
  control,
1938
2260
  progress
1939
2261
  );
1940
- if (built2.kind !== "ok") return built2;
1941
- entry = built2.value.entry;
2262
+ if (building.kind !== "ok") return building;
2263
+ ({ entry } = building.value);
1942
2264
  }
2265
+ const built = pick === void 0;
1943
2266
  if (signal.aborted) return { kind: "aborted" };
1944
2267
  await progress.emit({ kind: "runner-sandbox-starting", snapshotId: entry.snapshotId });
1945
2268
  const startedAt = now();
@@ -1966,7 +2289,7 @@ async function readyRunner(context, request2, control, progress) {
1966
2289
  vcpus: prepared.vcpus,
1967
2290
  ms: now() - startedAt
1968
2291
  });
1969
- const changes = await uploadChanges(context, { prepared, sandbox, base: entry.base }, signal, progress);
2292
+ const changes = await uploadChanges(context, { prepared, sandbox }, signal, progress);
1970
2293
  if (changes.kind !== "ok") return changes;
1971
2294
  const applied = await stage(
1972
2295
  context,
@@ -1995,7 +2318,7 @@ async function readyRunner(context, request2, control, progress) {
1995
2318
  progress
1996
2319
  );
1997
2320
  if (installed.kind !== "ok") return installed;
1998
- const built = await stage(
2321
+ const builtOutputs = await stage(
1999
2322
  context,
2000
2323
  {
2001
2324
  sandbox,
@@ -2007,14 +2330,17 @@ async function readyRunner(context, request2, control, progress) {
2007
2330
  signal,
2008
2331
  progress
2009
2332
  );
2010
- if (built.kind !== "ok") return built;
2333
+ if (builtOutputs.kind !== "ok") return builtOutputs;
2011
2334
  return {
2012
2335
  kind: "ready",
2013
2336
  runner: {
2014
2337
  sandbox,
2015
- startedFrom: entry,
2016
- built: picked === void 0,
2017
- buildMs: built.value,
2338
+ snapshotId: entry.snapshotId,
2339
+ base: entry.base,
2340
+ built,
2341
+ builtBehind: prepared.commitsAfterBase,
2342
+ uploadBytes: changes.value.bytes,
2343
+ buildMs: builtOutputs.value,
2018
2344
  vcpus: prepared.vcpus,
2019
2345
  region: recipe.region,
2020
2346
  runtime: recipe.runtime,
@@ -2026,21 +2352,14 @@ async function readyRunner(context, request2, control, progress) {
2026
2352
  };
2027
2353
  }
2028
2354
  async function uploadChanges(context, request2, signal, progress) {
2029
- const { prepared } = request2;
2030
2355
  await progress.emit({ kind: "uploading" });
2031
2356
  const startedAt = context.clock.now().getTime();
2032
- let upload = prepared.upload;
2033
- if (request2.base !== prepared.base) {
2034
- const assembled = await context.checkout.assembleUpload({ repoRoot: prepared.repoRoot, base: request2.base });
2035
- if (!assembled.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: assembled.failure } };
2036
- upload = assembled.value;
2037
- }
2038
- const files = stagedChanges(upload);
2357
+ const files = stagedChanges(request2.prepared.upload);
2039
2358
  const staged = await context.runnerSandboxes.upload(request2.sandbox, files, signal);
2040
2359
  if (!staged.ok) return sandboxStop("upload", staged.failure);
2041
2360
  const bytes = files.reduce((sum, file) => sum + file.content.byteLength, 0);
2042
2361
  await progress.emit({ kind: "uploaded", bytes, ms: context.clock.now().getTime() - startedAt });
2043
- return { kind: "ok", value: { directory: staged.value.directory } };
2362
+ return { kind: "ok", value: { directory: staged.value.directory, bytes } };
2044
2363
  }
2045
2364
  function stagedChanges(upload) {
2046
2365
  const encoder = new TextEncoder();
@@ -2075,484 +2394,538 @@ async function stage(context, request2, signal, progress) {
2075
2394
  if (section !== void 0) await progress.emit({ kind: "output-ended", section, outcome: "finished" });
2076
2395
  return { kind: "ok", value: ran.ms };
2077
2396
  }
2078
- const stop = ran.kind === "exited" ? {
2079
- kind: "failed",
2080
- failure: { kind: `${phase}-failed`, label: step.label, exitCode: ran.exitCode, tail: ran.tail }
2081
- } : sandboxStop("run-script", ran.failure);
2082
- if (section !== void 0)
2083
- await progress.emit({ kind: "output-ended", section, outcome: stop.kind === "aborted" ? "stopped" : "failed" });
2084
- return stop;
2397
+ const stop = ran.kind === "exited" ? {
2398
+ kind: "failed",
2399
+ failure: { kind: `${phase}-failed`, label: step.label, exitCode: ran.exitCode, tail: ran.tail }
2400
+ } : sandboxStop("run-script", ran.failure);
2401
+ if (section !== void 0)
2402
+ await progress.emit({ kind: "output-ended", section, outcome: stop.kind === "aborted" ? "stopped" : "failed" });
2403
+ return stop;
2404
+ }
2405
+
2406
+ // src/runner/session.ts
2407
+ function openRunnerSession(context, request2, control, progress) {
2408
+ const { signal, cleanup } = control;
2409
+ const scope = runnerSandboxScope(context, progress, { keepMs: request2.keepMs });
2410
+ const closeScope = async () => ({ ...await scope.close(), target: request2.target });
2411
+ let readying = false;
2412
+ let readied;
2413
+ let commandRunning = false;
2414
+ const stop = () => {
2415
+ void progress.emit({ kind: "stopping", commandRunning, keepMs: request2.keepMs }).catch(() => void 0);
2416
+ void scope.close().catch(() => void 0);
2417
+ };
2418
+ if (signal.aborted) stop();
2419
+ else signal.addEventListener("abort", stop, { once: true });
2420
+ return {
2421
+ async ready(access, laneSignal) {
2422
+ if (readying) throw new Error("the runner session readies its runner sandbox once");
2423
+ readying = true;
2424
+ const { prepared, user, secrets } = request2;
2425
+ const outcome = await readyRunner(
2426
+ context,
2427
+ { prepared, access, user, secrets },
2428
+ { scope, signal: laneSignal },
2429
+ progress
2430
+ );
2431
+ if (outcome.kind === "ready") readied = outcome.runner;
2432
+ return outcome;
2433
+ },
2434
+ async runCommand(command) {
2435
+ if (readied === void 0) throw new Error("the runner session's runner sandbox isn't ready");
2436
+ commandRunning = true;
2437
+ return await runCommandInSandbox(
2438
+ context,
2439
+ {
2440
+ runner: readied,
2441
+ argv: command.argv,
2442
+ runPayload: command.runPayload,
2443
+ ...command.testEvents === void 0 ? {} : { testEvents: command.testEvents }
2444
+ },
2445
+ { kill: signal },
2446
+ progress
2447
+ );
2448
+ },
2449
+ async finish() {
2450
+ commandRunning = false;
2451
+ await cleanup.startCleanup();
2452
+ const facts = await closeScope();
2453
+ signal.removeEventListener("abort", stop);
2454
+ await cleanup.release();
2455
+ return facts;
2456
+ },
2457
+ async close() {
2458
+ signal.removeEventListener("abort", stop);
2459
+ try {
2460
+ return await closeScope();
2461
+ } finally {
2462
+ await cleanup.release();
2463
+ }
2464
+ }
2465
+ };
2466
+ }
2467
+
2468
+ // src/config/load.ts
2469
+ import { dirname, join as join2 } from "node:path";
2470
+
2471
+ // src/config/schema.ts
2472
+ var CONFIG_FILE_NAME = "storm.config.ts";
2473
+ function checkWith(schema, value) {
2474
+ const parsed = schema.safeParse(value);
2475
+ if (parsed.success) return { ok: true, value: parsed.data };
2476
+ return {
2477
+ ok: false,
2478
+ problems: parsed.error.issues.map(({ path, message }) => ({ path: path.map(String), problem: message }))
2479
+ };
2480
+ }
2481
+ var SETTING_CHECKS = {
2482
+ scope: (value) => checkWith(nonEmptyString, value),
2483
+ project: (value) => checkWith(nonEmptyString, value),
2484
+ runner: checkRecipe
2485
+ };
2486
+ function isConfigSettingKey(key) {
2487
+ return Object.hasOwn(SETTING_CHECKS, key);
2488
+ }
2489
+ function checkSettingValue(key, value) {
2490
+ return SETTING_CHECKS[key](value);
2491
+ }
2492
+
2493
+ // src/config/load.ts
2494
+ async function findConfigFile(gateway, startDirectory) {
2495
+ if (await gateway.hasConfigFile(startDirectory)) return join2(startDirectory, CONFIG_FILE_NAME);
2496
+ const root = await worktreeRoot(gateway, startDirectory);
2497
+ if (root === void 0) return void 0;
2498
+ for (let directory = startDirectory; directory !== root; ) {
2499
+ directory = dirname(directory);
2500
+ if (await gateway.hasConfigFile(directory)) return join2(directory, CONFIG_FILE_NAME);
2501
+ }
2502
+ return void 0;
2503
+ }
2504
+ async function worktreeRoot(gateway, directory) {
2505
+ for (let current = directory; ; current = dirname(current)) {
2506
+ if (await gateway.isWorktreeRoot(current)) return current;
2507
+ if (dirname(current) === current) return void 0;
2508
+ }
2509
+ }
2510
+ async function loadConfig(gateway, startDirectory, definitions) {
2511
+ const path = await findConfigFile(gateway, startDirectory);
2512
+ if (path === void 0) return { kind: "none" };
2513
+ const imported = await gateway.importConfig(path);
2514
+ switch (imported.kind) {
2515
+ case "import-failed":
2516
+ return {
2517
+ kind: "invalid",
2518
+ path,
2519
+ problems: [{ key: null, location: imported.location ?? null, problem: imported.message }]
2520
+ };
2521
+ case "no-default-export":
2522
+ return {
2523
+ kind: "invalid",
2524
+ path,
2525
+ problems: [fileProblem("has no default export; export default defineConfig({ \u2026 })")]
2526
+ };
2527
+ case "default-export":
2528
+ return checkFile(path, imported.value, definitions);
2529
+ }
2530
+ }
2531
+ function checkFile(path, value, definitions) {
2532
+ if (!isRecord2(value))
2533
+ return {
2534
+ kind: "invalid",
2535
+ path,
2536
+ problems: [fileProblem(`must default-export an object, not ${describeValue(value)}`)]
2537
+ };
2538
+ const settings = {};
2539
+ const problems = [];
2540
+ let resources = {};
2541
+ for (const [key, keyValue] of Object.entries(value)) {
2542
+ if (key === "resources") resources = checkResources(keyValue, definitions, problems);
2543
+ else if (isConfigSettingKey(key)) {
2544
+ if (keyValue !== void 0) checkSetting(key, keyValue, settings, problems);
2545
+ } else problems.push({ key, location: null, problem: `is not a ${CONFIG_FILE_NAME} key` });
2546
+ }
2547
+ if (problems.length > 0) return { kind: "invalid", path, problems };
2548
+ return { kind: "loaded", path, values: { settings, resources } };
2549
+ }
2550
+ function checkSetting(key, value, settings, problems) {
2551
+ const checked = checkSettingValue(key, value);
2552
+ if (checked.ok) Object.assign(settings, { [key]: checked.value });
2553
+ else
2554
+ for (const { path: inside, problem } of checked.problems)
2555
+ problems.push({ key: [key, ...inside].join("."), location: null, problem });
2556
+ }
2557
+ function checkResources(value, definitions, problems) {
2558
+ if (value === void 0) return {};
2559
+ if (!isRecord2(value)) {
2560
+ problems.push({ key: "resources", location: null, problem: `must be an object, not ${describeValue(value)}` });
2561
+ return {};
2562
+ }
2563
+ const byName = new Map(definitions.map((definition) => [definition.name, definition]));
2564
+ const holds = definitions.length === 0 ? "none" : definitions.map((each) => each.name).join(", ");
2565
+ const found = {};
2566
+ for (const [key, resource] of Object.entries(value)) {
2567
+ const named = entryName(resource);
2568
+ const definition = byName.get(named !== void 0 && byName.has(named) ? named : key);
2569
+ if (named !== void 0 && definition !== void 0 && key !== defaultResourceKey(definition)) {
2570
+ problems.push({
2571
+ key: `resources.${key}`,
2572
+ location: null,
2573
+ problem: `holds a ${named} resource; for now a resource's key must be its definition's name: name its key ${defaultResourceKey(definition)}`
2574
+ });
2575
+ continue;
2576
+ }
2577
+ if (definition === void 0) {
2578
+ problems.push({
2579
+ key: `resources.${key}`,
2580
+ location: null,
2581
+ problem: `is not a resource; resources holds ${holds}`
2582
+ });
2583
+ continue;
2584
+ }
2585
+ if (resource === void 0) continue;
2586
+ const options = checkResource(definition, key, resource, problems);
2587
+ if (options !== void 0) found[key] = { definition: definition.name, options };
2588
+ }
2589
+ return found;
2085
2590
  }
2086
-
2087
- // src/runner/scope.ts
2088
- var CREATE_SETTLE_MS = 2e4;
2089
- var SNAPSHOT_SETTLE_MS = 2 * 6e4;
2090
- function unsavedKeepMs(plan) {
2091
- return plan.kind === "keep" ? plan.ms : plan.otherwiseKeepMs;
2591
+ function entryName(value) {
2592
+ return isRecord2(value) && typeof value["name"] === "string" ? value["name"] : void 0;
2092
2593
  }
2093
- function runnerSandboxScope(context, progress, keep) {
2094
- const { runnerSandboxes: sandboxes, timer, clock } = context;
2095
- const live = /* @__PURE__ */ new Set();
2096
- const creating = /* @__PURE__ */ new Set();
2097
- const saving = /* @__PURE__ */ new Set();
2098
- const notStopped = [];
2099
- const notDeleted = [];
2100
- let kept = null;
2101
- let notKept = null;
2102
- let closing;
2103
- const track = (set, task) => {
2104
- set.add(task);
2105
- const forget = () => set.delete(task);
2106
- void task.then(forget, forget);
2107
- return task;
2108
- };
2109
- const remove = async (sandbox) => {
2110
- const deleted = await sandboxes.delete(sandbox);
2111
- if (!deleted.ok)
2112
- notDeleted.push({ name: sandbox.name, role: sandbox.role, message: failureMessage(deleted.failure) });
2113
- };
2114
- const stopAndRemove = async (sandbox) => {
2115
- const stopped = await sandboxes.stop(sandbox);
2116
- if (!stopped.ok) {
2117
- notStopped.push({
2118
- name: sandbox.name,
2119
- role: sandbox.role,
2120
- timeoutMinutes: Math.round(sandbox.timeoutMs / 6e4),
2121
- message: failureMessage(stopped.failure)
2122
- });
2123
- return;
2124
- }
2125
- await remove(sandbox);
2126
- };
2127
- const keepOrRemove = async (sandbox) => {
2128
- const keepMs = sandbox.role === "runner" ? keep.keepMs() : 0;
2129
- if (keepMs <= 0) return await stopAndRemove(sandbox);
2130
- const keeping = await sandboxes.keepRunning(sandbox, { until: new Date(clock.now().getTime() + keepMs) });
2131
- if (!keeping.ok) {
2132
- notKept = { name: sandbox.name, message: failureMessage(keeping.failure) };
2133
- return await stopAndRemove(sandbox);
2594
+ function checkResource(definition, key, value, problems) {
2595
+ const { name } = definition;
2596
+ const options = isRecord2(value) && value["name"] === name ? value["options"] : void 0;
2597
+ if (!isRecord2(options)) {
2598
+ problems.push({
2599
+ key: `resources.${key}`,
2600
+ location: null,
2601
+ problem: `must be made by ${resourceCall(name)}, not ${describeValue(value)}`
2602
+ });
2603
+ return void 0;
2604
+ }
2605
+ const checked = {};
2606
+ let valid = true;
2607
+ for (const [option, optionValue] of Object.entries(options)) {
2608
+ const path = `resources.${key}.${option}`;
2609
+ const rule = Object.hasOwn(definition.options, option) ? definition.options[option] : void 0;
2610
+ if (rule === void 0) {
2611
+ valid = false;
2612
+ problems.push({ key: path, location: null, problem: `is not a ${name} option` });
2613
+ continue;
2134
2614
  }
2135
- kept = { name: sandbox.name, stopsAt: keeping.value.stopsAt.toISOString() };
2136
- await progress.emit({ kind: "sandbox-kept", ...kept });
2137
- };
2138
- const owned = (start) => {
2139
- if (closing !== void 0) return Promise.resolve({ ok: false, failure: { kind: "aborted" } });
2140
- return track(
2141
- creating,
2142
- (async () => {
2143
- const started = await start();
2144
- if (!started.ok) return started;
2145
- if (closing !== void 0) {
2146
- await stopAndRemove(started.value);
2147
- return { ok: false, failure: { kind: "aborted" } };
2148
- }
2149
- live.add(started.value);
2150
- return started;
2151
- })()
2152
- );
2153
- };
2154
- return {
2155
- get closed() {
2156
- return closing !== void 0;
2157
- },
2158
- startBuildSandbox: (access, request2) => owned(() => sandboxes.startBuildSandbox(access, request2)),
2159
- startRunnerSandbox: (access, request2) => owned(() => sandboxes.startRunnerSandbox(access, request2)),
2160
- saveSnapshot: (sandbox, request2) => track(
2161
- saving,
2162
- (async () => {
2163
- const saved = await sandboxes.saveSnapshot(sandbox, request2);
2164
- if (saved.ok && live.delete(sandbox)) await remove(sandbox);
2165
- return saved;
2166
- })()
2167
- ),
2168
- close() {
2169
- closing ??= (async () => {
2170
- if (saving.size > 0) await progress.emit({ kind: "waiting-for-snapshot", settleMs: SNAPSHOT_SETTLE_MS });
2171
- await Promise.all([
2172
- settleWithin(timer, creating, CREATE_SETTLE_MS),
2173
- settleWithin(timer, saving, SNAPSHOT_SETTLE_MS)
2174
- ]);
2175
- const held = [...live];
2176
- live.clear();
2177
- await Promise.all(held.map(keepOrRemove));
2178
- return { kept, notKept, notStopped: [...notStopped], notDeleted: [...notDeleted] };
2179
- })();
2180
- return closing;
2615
+ if (optionValue === void 0) continue;
2616
+ const result = checkWith(rule.schema, optionValue);
2617
+ if (result.ok) checked[option] = result.value;
2618
+ else {
2619
+ valid = false;
2620
+ for (const { path: inside, problem } of result.problems)
2621
+ problems.push({ key: [path, ...inside].join("."), location: null, problem });
2181
2622
  }
2182
- };
2623
+ }
2624
+ return valid ? checked : void 0;
2183
2625
  }
2184
- async function settleWithin(timer, tasks, ms) {
2185
- if (tasks.size === 0) return;
2186
- const done = new AbortController();
2187
- await Promise.race([Promise.allSettled(tasks), timer.sleep(ms, done.signal)]);
2188
- done.abort();
2626
+ function isRecord2(value) {
2627
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2189
2628
  }
2190
- function failureMessage(failure) {
2191
- return failure.message ?? failure.kind;
2629
+ function fileProblem(problem) {
2630
+ return { key: null, location: null, problem };
2192
2631
  }
2193
2632
 
2194
- // src/runner/snapshot-save.ts
2195
- var FAILURE_TAIL_LINES = 3;
2196
- var TEMP_DIRECTORIES = ["/tmp", "/var/tmp", '"${TMPDIR:-}"'];
2197
- function scrubGitScript(root = SANDBOX_ROOT) {
2198
- return ["set -euo pipefail", `cd ${root}`, ...RESET_TO_BASE].join("\n");
2633
+ // src/config/errors.ts
2634
+ import { z as z5 } from "zod";
2635
+ var problemSchema = z5.object({
2636
+ /** The key the problem is about; null when it is about the whole file. */
2637
+ key: z5.string().nullable(),
2638
+ /** Where Node said the import failed; null otherwise. */
2639
+ location: z5.object({ line: z5.number(), column: z5.number().nullable() }).nullable(),
2640
+ /** What is wrong, worded to follow the key, or the file name when there is no key. */
2641
+ problem: z5.string()
2642
+ });
2643
+ function configProblemLine(file, { key, location, problem }) {
2644
+ const sentence = `${problem.replace(/\.$/, "")}.`;
2645
+ if (key !== null) return `${file}: ${key} ${sentence}`;
2646
+ if (location !== null)
2647
+ return `${file}:${location.line}${location.column === null ? "" : `:${location.column}`} ${sentence}`;
2648
+ return `${file}: ${sentence}`;
2199
2649
  }
2200
- function scrubTempScript(directories = TEMP_DIRECTORIES) {
2201
- return [
2202
- "set -euo pipefail",
2203
- `for dir in ${directories.join(" ")}; do`,
2204
- ' [ -n "$dir" ] && [ -d "$dir" ] || continue',
2205
- ' find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
2206
- ' if [ -n "$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)" ]; then',
2207
- ' sudo -n find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
2208
- " fi",
2209
- ' left=$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)',
2210
- ` if [ -n "$left" ]; then echo "couldn't empty $dir: $left is left" >&2; exit 1; fi`,
2211
- "done"
2212
- ].join("\n");
2213
- }
2214
- async function saveBranchSnapshot(context, request2, control, progress) {
2215
- const save = await saveOnce(context, request2, control, progress);
2216
- if (save.kind !== "saved") await progress.emit({ kind: "branch-snapshot-not-saved", save });
2217
- return save;
2218
- }
2219
- async function saveOnce(context, request2, control, progress) {
2220
- const { ready, branch, head: head2 } = request2;
2221
- const { scope, signal } = control;
2222
- const stopped = () => signal.aborted || scope.closed;
2223
- if (stopped()) return { kind: "stopped" };
2224
- const { sandbox, startedFrom } = ready;
2225
- const startedAt = context.clock.now().getTime();
2226
- await progress.emit({ kind: "branch-snapshot-saving", branch });
2227
- for (const script of [scrubGitScript(), scrubTempScript()]) {
2228
- if (stopped()) return { kind: "stopped" };
2229
- const ran = await runSaveScript(context, sandbox, script, signal);
2230
- if (ran.kind === "stopped") return ran;
2231
- if (ran.kind === "failed") return { kind: "failed", step: "scrub", message: ran.message };
2232
- }
2233
- if (stopped()) return { kind: "stopped" };
2234
- const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
2235
- if (!saved.ok)
2236
- return saved.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", step: "save-snapshot", message: saved.failure.message };
2237
- if (signal.aborted) return { kind: "stopped" };
2238
- const savedAt2 = context.clock.now();
2239
- const entry = {
2240
- teamId: startedFrom.teamId,
2241
- projectId: startedFrom.projectId,
2242
- region: startedFrom.region,
2243
- runtime: startedFrom.runtime,
2244
- recipeName: startedFrom.recipeName,
2245
- snapshotKey: startedFrom.snapshotKey,
2246
- base: startedFrom.base,
2247
- branch,
2248
- head: head2,
2249
- repoRoot: ready.repoRoot,
2250
- snapshotId: saved.value.snapshotId,
2251
- createdAt: savedAt2.toISOString(),
2252
- expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
2253
- };
2254
- const written = await context.runnerSnapshots.writeEntry(entry);
2255
- if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
2256
- const ms = savedAt2.getTime() - startedAt;
2257
- await progress.emit({
2258
- kind: "branch-snapshot-saved",
2259
- snapshotId: entry.snapshotId,
2260
- branch,
2261
- head: head2,
2262
- ms,
2263
- sizeBytes: saved.value.sizeBytes
2264
- });
2265
- return {
2266
- kind: "saved",
2267
- snapshotId: entry.snapshotId,
2268
- base: entry.base,
2269
- branch,
2270
- head: head2,
2271
- ms,
2272
- sizeBytes: saved.value.sizeBytes,
2273
- entryWritten: written.ok
2274
- };
2650
+ var optionValueSchema = z5.object({
2651
+ /** The option's key path, such as resources.<key>.ttl. */
2652
+ key: z5.string(),
2653
+ /** Its value, as text. */
2654
+ value: z5.string(),
2655
+ /** Where it came from: the command's own flag for the option, the config file or the default. */
2656
+ source: z5.enum(["flag", "file", "default"])
2657
+ });
2658
+ var optionProblemSchema = z5.object({
2659
+ /** The key path of the option the problem is about, such as resources.<key>.ttl. */
2660
+ key: z5.string(),
2661
+ /** What is wrong, worded to follow the key path, as the resource's rule words it. */
2662
+ problem: z5.string(),
2663
+ /** Each value the problem is about, with its source; empty for a required option nothing gave. */
2664
+ values: z5.array(optionValueSchema)
2665
+ });
2666
+ function optionValueText({ key, value, source }, configFile) {
2667
+ switch (source) {
2668
+ case "flag":
2669
+ return `${key} is ${value} from the command line`;
2670
+ case "file":
2671
+ return `${key} is ${value} in ${configFile ?? "storm.config.ts"}`;
2672
+ case "default":
2673
+ return `${key} is ${value} by default`;
2674
+ }
2275
2675
  }
2276
- async function runSaveScript(context, sandbox, script, signal) {
2277
- const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
2278
- const tail = outputTail(FAILURE_TAIL_LINES);
2279
- const keep = (text) => {
2280
- for (const line of splitLines(text)) tail.add(line);
2281
- };
2282
- const ran = await context.runnerSandboxes.runScript(
2283
- sandbox,
2284
- { script, env: STEP_ENV },
2285
- ({ stream, data }) => keep(splitters[stream].push(data)),
2286
- signal
2287
- );
2288
- keep(splitters.stdout.flush());
2289
- keep(splitters.stderr.flush());
2290
- if (!ran.ok)
2291
- return ran.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", message: ran.failure.message };
2292
- const { exitCode } = ran.value;
2293
- if (exitCode === 0) return { kind: "ok" };
2294
- const lines = tail.lines();
2295
- const ended = exitCode === null ? "ended without an exit code" : `exited ${exitCode}`;
2296
- return { kind: "failed", message: lines.length === 0 ? ended : `${ended}: ${lines.join(" / ")}` };
2676
+ function optionProblemLine({ key, problem, values }, configFile) {
2677
+ const where2 = values.map((value) => optionValueText(value, configFile));
2678
+ const sources = where2.length === 0 ? "" : `: ${where2.length === 1 ? where2.join("") : `${where2.slice(0, -1).join(", ")} and ${where2.at(-1) ?? ""}`}`;
2679
+ return `${key} ${problem.replace(/\.$/, "")}${sources}.`;
2680
+ }
2681
+ var configErrors = defineErrors({
2682
+ invalidConfig: {
2683
+ exitCode: 2,
2684
+ description: "storm.config.ts can't be used: it can't be imported, doesn't default-export an object, has an unknown key, or a value in it is invalid. storm checks the whole file whenever a command loads it.",
2685
+ schema: z5.object({
2686
+ /** The config file's absolute path. */
2687
+ file: z5.string(),
2688
+ problems: z5.array(problemSchema)
2689
+ }),
2690
+ render: ({ file, problems }) => {
2691
+ const [first, ...rest] = problems;
2692
+ return {
2693
+ message: first === void 0 ? `${file} can't be used.` : configProblemLine(file, first),
2694
+ ...rest.length === 0 ? {} : { rows: [["Also", rest.map((problem) => configProblemLine(file, problem))]] },
2695
+ next: [{ type: "text", text: `Fix ${file}, then retry.` }]
2696
+ };
2697
+ }
2698
+ },
2699
+ invalidResourceOptions: {
2700
+ exitCode: 2,
2701
+ description: "A resource's options, once its defaults, storm.config.ts and the flags are merged, don't fit together, as the resource's own checks say, or one it requires is missing: such as resources.<key>.ttl not longer than its minTimeLeft. Each problem names the values it is about and where each came from.",
2702
+ schema: z5.object({
2703
+ /** The config file that applied; null when none did. */
2704
+ configFile: z5.string().nullable(),
2705
+ problems: z5.array(optionProblemSchema)
2706
+ }),
2707
+ render: ({ configFile, problems }) => {
2708
+ const [first, ...rest] = problems;
2709
+ return {
2710
+ message: first === void 0 ? "A resource's options don't fit together." : optionProblemLine(first, configFile),
2711
+ ...rest.length === 0 ? {} : { rows: [["Also", rest.map((problem) => optionProblemLine(problem, configFile))]] },
2712
+ next: [
2713
+ {
2714
+ type: "text",
2715
+ text: `Change the options on the command line or in ${configFile ?? "storm.config.ts"}, then retry.`
2716
+ }
2717
+ ]
2718
+ };
2719
+ }
2720
+ }
2721
+ });
2722
+
2723
+ // src/config/typed-options.ts
2724
+ function givenOptionsOf(_definition, values) {
2725
+ return values;
2726
+ }
2727
+ function settingsOf(_definition, settings) {
2728
+ return settings;
2297
2729
  }
2298
-
2299
- // src/runner/session.ts
2300
- function savedAt(runner, head2) {
2301
- const { startedFrom } = runner;
2302
- return isBranchEntry(startedFrom) && startedFrom.head === head2;
2730
+ function resourceOptionsOf(_definition, value) {
2731
+ return value;
2303
2732
  }
2304
- function openRunnerSession(context, request2, control, progress) {
2305
- const { signal, cleanup } = control;
2306
- const plan = request2.sandbox;
2307
- const unsaved = { kind: "keep", ms: unsavedKeepMs(plan) };
2308
- let saveStarted = false;
2309
- const keepMs = () => saveStarted ? 0 : unsaved.ms;
2310
- const scope = runnerSandboxScope(context, progress, { keepMs });
2311
- const closeScope = async () => ({ ...await scope.close(), target: request2.target });
2312
- let readying = false;
2313
- let readied;
2314
- let commandRunning = false;
2315
- let ended;
2316
- const stop = () => {
2317
- void progress.emit({ kind: "stopping", commandRunning, keepMs: keepMs() }).catch(() => void 0);
2318
- void scope.close().catch(() => void 0);
2319
- };
2320
- if (signal.aborted) stop();
2321
- else signal.addEventListener("abort", stop, { once: true });
2733
+
2734
+ // src/config/resolve.ts
2735
+ function resolveSettings(flags, file) {
2736
+ const pick = (flag, fromFile) => flag !== void 0 ? { value: flag, source: "flag" } : fromFile === void 0 ? void 0 : { value: fromFile, source: "file" };
2322
2737
  return {
2323
- async ready(access, laneSignal) {
2324
- if (readying) throw new Error("the runner session readies its runner sandbox once");
2325
- readying = true;
2326
- const outcome = await readyRunner(
2327
- context,
2328
- { prepared: request2.prepared, access, user: request2.user, secrets: request2.secrets },
2329
- { scope, signal: laneSignal },
2330
- progress
2331
- );
2332
- if (outcome.kind === "ready") readied = outcome.runner;
2333
- return outcome;
2334
- },
2335
- async runCommand(command) {
2336
- if (readied === void 0) throw new Error("the runner session's runner sandbox isn't ready");
2337
- commandRunning = true;
2338
- const ran = await runCommandInSandbox(
2339
- context,
2340
- {
2341
- runner: readied,
2342
- argv: command.argv,
2343
- runPayload: command.runPayload,
2344
- ...command.testEvents === void 0 ? {} : { testEvents: command.testEvents }
2345
- },
2346
- { kill: signal },
2347
- progress
2348
- );
2349
- if (ran.kind === "exited") ended = { runner: readied, exitCode: ran.exitCode };
2350
- return ran;
2351
- },
2352
- async finish() {
2353
- commandRunning = false;
2354
- const { prepared } = request2;
2355
- let save = prepared.save?.kind === "skipped" ? prepared.save : null;
2356
- let action = unsaved;
2357
- if (plan.kind === "save" && ended !== void 0 && !signal.aborted && (plan.always || ended.exitCode === 0 && !savedAt(ended.runner, prepared.head.commit))) {
2358
- saveStarted = true;
2359
- action = plan;
2360
- const saving = saveBranchSnapshot(
2361
- context,
2362
- { ready: ended.runner, branch: plan.branch, head: prepared.head.commit },
2363
- { scope, signal },
2364
- progress
2365
- );
2366
- try {
2367
- await cleanup.release(plan);
2368
- } finally {
2369
- save = await saving;
2370
- }
2371
- }
2372
- await cleanup.startCleanup(action);
2373
- const facts = await closeScope();
2374
- signal.removeEventListener("abort", stop);
2375
- await cleanup.release(action);
2376
- return { save, cleanup: facts };
2377
- },
2378
- async close() {
2379
- signal.removeEventListener("abort", stop);
2380
- try {
2381
- return await closeScope();
2382
- } finally {
2383
- await cleanup.release(unsaved);
2384
- }
2385
- }
2738
+ scope: pick(flags.scope, file?.scope),
2739
+ project: pick(flags.project, file?.project),
2740
+ runner: pick(void 0, file?.runner)
2386
2741
  };
2387
2742
  }
2388
-
2389
- // src/config/load.ts
2390
- import { dirname, join as join2 } from "node:path";
2391
-
2392
- // src/config/schema.ts
2393
- var CONFIG_FILE_NAME = "storm.config.ts";
2394
- function checkWith(schema, value) {
2395
- const parsed = schema.safeParse(value);
2396
- if (parsed.success) return { ok: true, value: parsed.data };
2743
+ function optionSource(definition, option, file, flags) {
2744
+ const fromFile = file ?? {};
2745
+ const fromFlags = flags ?? {};
2746
+ if (fromFlags[option] !== void 0) return "flag";
2747
+ if (fromFile[option] !== void 0) return "file";
2748
+ return definition.options[option]?.default === void 0 ? void 0 : "default";
2749
+ }
2750
+ function mergeResourceOptions(definition, key, file, flags) {
2751
+ const fromFile = file ?? {};
2752
+ const fromFlags = flags ?? {};
2753
+ const merged = [];
2754
+ const problems = [];
2755
+ for (const [option, rule] of Object.entries(definition.options)) {
2756
+ const source = optionSource(definition, option, file, flags);
2757
+ if (source === "flag") merged.push([option, { value: fromFlags[option], source }]);
2758
+ else if (source === "file") merged.push([option, { value: fromFile[option], source }]);
2759
+ else if (source === "default") merged.push([option, "default"]);
2760
+ else if (rule.required === true) {
2761
+ problems.push({
2762
+ key: optionKeyPath(key, option),
2763
+ problem: `is required; give it in ${resourceCall(definition.name)}`,
2764
+ values: []
2765
+ });
2766
+ }
2767
+ }
2768
+ if (problems.length > 0) return { ok: false, problems };
2397
2769
  return {
2398
- ok: false,
2399
- problems: parsed.error.issues.map(({ path, message }) => ({ path: path.map(String), problem: message }))
2770
+ ok: true,
2771
+ settings: (run) => (
2772
+ // Every option with a default or marked required is in `merged`, so it is what `definition.check` takes.
2773
+ settingsOf(
2774
+ definition,
2775
+ Object.fromEntries(
2776
+ merged.map(([option, given]) => [
2777
+ option,
2778
+ given === "default" ? { value: defaultValue(definition, option, run), source: "default" } : given
2779
+ ])
2780
+ )
2781
+ )
2782
+ )
2400
2783
  };
2401
2784
  }
2402
- var SETTING_CHECKS = {
2403
- scope: (value) => checkWith(nonEmptyString, value),
2404
- project: (value) => checkWith(nonEmptyString, value),
2405
- runner: checkRecipe
2406
- };
2407
- function isConfigSettingKey(key) {
2408
- return Object.hasOwn(SETTING_CHECKS, key);
2409
- }
2410
- function checkSettingValue(key, value) {
2411
- return SETTING_CHECKS[key](value);
2785
+ function isDefaultFunction(given) {
2786
+ return typeof given === "function";
2412
2787
  }
2413
-
2414
- // src/config/load.ts
2415
- async function findConfigFile(gateway, startDirectory) {
2416
- if (await gateway.hasConfigFile(startDirectory)) return join2(startDirectory, CONFIG_FILE_NAME);
2417
- const root = await worktreeRoot(gateway, startDirectory);
2418
- if (root === void 0) return void 0;
2419
- for (let directory = startDirectory; directory !== root; ) {
2420
- directory = dirname(directory);
2421
- if (await gateway.hasConfigFile(directory)) return join2(directory, CONFIG_FILE_NAME);
2422
- }
2423
- return void 0;
2788
+ function defaultValue(definition, option, run) {
2789
+ const rule = definition.options[option];
2790
+ if (rule === void 0 || !isDefaultFunction(rule.default)) return rule?.default;
2791
+ const checked = rule.schema.safeParse(rule.default(run));
2792
+ if (checked.success) return checked.data;
2793
+ const problems = checked.error.issues.map(({ message }) => message).join("; ");
2794
+ throw new Error(
2795
+ `${definition.name}'s option ${option} has a default that gave a value its schema refuses: ${problems}`
2796
+ );
2424
2797
  }
2425
- async function worktreeRoot(gateway, directory) {
2426
- for (let current = directory; ; current = dirname(current)) {
2427
- if (await gateway.isWorktreeRoot(current)) return current;
2428
- if (dirname(current) === current) return void 0;
2798
+ function mergeRunResources(definitions, file, flags) {
2799
+ const resources = [];
2800
+ const problems = [];
2801
+ for (const { key, definition, given, flagged } of runResources(definitions, file, flags)) {
2802
+ const merged = mergeResourceOptions(definition, key, given, flagged);
2803
+ if (merged.ok) resources.push({ key, definition, settings: merged.settings });
2804
+ else problems.push(...merged.problems);
2429
2805
  }
2806
+ if (problems.length > 0) return { ok: false, problems };
2807
+ const options = Object.fromEntries(
2808
+ resources.map(({ key, definition, settings }) => [
2809
+ key,
2810
+ { definition: definition.name, options: plainValues(settings(NOT_COUNTED)) }
2811
+ ])
2812
+ );
2813
+ return { ok: true, options, plan: (run) => planResources(resources, run) };
2430
2814
  }
2431
- async function loadConfig(gateway, startDirectory, definitions) {
2432
- const path = await findConfigFile(gateway, startDirectory);
2433
- if (path === void 0) return { kind: "none" };
2434
- const imported = await gateway.importConfig(path);
2435
- switch (imported.kind) {
2436
- case "import-failed":
2437
- return {
2438
- kind: "invalid",
2439
- path,
2440
- problems: [{ key: null, location: imported.location ?? null, problem: imported.message }]
2441
- };
2442
- case "no-default-export":
2443
- return {
2444
- kind: "invalid",
2445
- path,
2446
- problems: [fileProblem("has no default export; export default defineConfig({ \u2026 })")]
2815
+ function planResources(resources, run) {
2816
+ const resolved = {};
2817
+ const planned = [];
2818
+ const problems = [];
2819
+ for (const { key, definition, settings: settingsFor } of resources) {
2820
+ const merged = settingsFor(run);
2821
+ const settings = merged;
2822
+ planned.push(...plannedOptions(definition, key, settings));
2823
+ const refused2 = definition.check(merged);
2824
+ if (refused2.length === 0)
2825
+ resolved[key] = {
2826
+ definition: definition.name,
2827
+ options: plainValues(settings),
2828
+ sources: Object.fromEntries(
2829
+ Object.keys(definition.options).map((option) => [option, settings[option]?.source])
2830
+ )
2447
2831
  };
2448
- case "default-export":
2449
- return checkFile(path, imported.value, definitions);
2832
+ else
2833
+ for (const { option, problem, involves } of refused2)
2834
+ problems.push({
2835
+ key: optionKeyPath(key, option),
2836
+ problem,
2837
+ values: involves.flatMap((each) => {
2838
+ const setting = settings[each];
2839
+ return setting === void 0 ? [] : [{ key: optionKeyPath(key, each), value: setting.value, source: setting.source }];
2840
+ })
2841
+ });
2450
2842
  }
2843
+ if (problems.length > 0) return { ok: false, problems };
2844
+ return { ok: true, value: resolved, planned };
2451
2845
  }
2452
- function checkFile(path, value, definitions) {
2453
- if (!isRecord2(value))
2454
- return {
2455
- kind: "invalid",
2456
- path,
2457
- problems: [fileProblem(`must default-export an object, not ${describeValue(value)}`)]
2458
- };
2459
- const settings = {};
2460
- const problems = [];
2461
- let resources = {};
2462
- for (const [key, keyValue] of Object.entries(value)) {
2463
- if (key === "resources") resources = checkResources(keyValue, definitions, problems);
2464
- else if (isConfigSettingKey(key)) {
2465
- if (keyValue !== void 0) checkSetting(key, keyValue, settings, problems);
2466
- } else problems.push({ key, location: null, problem: `is not a ${CONFIG_FILE_NAME} key` });
2467
- }
2468
- if (problems.length > 0) return { kind: "invalid", path, problems };
2469
- return { kind: "loaded", path, values: { settings, resources } };
2846
+ function runResources(definitions, file, flags) {
2847
+ const resources = Object.entries(file ?? {});
2848
+ return definitions.flatMap((definition) => {
2849
+ const defaultKey = defaultResourceKey(definition);
2850
+ const flagged = flags[definition.name];
2851
+ const fromFile = resources.flatMap(
2852
+ ([key, resource]) => resource.definition === definition.name ? [{ key, definition, given: resource.options, flagged: key === defaultKey ? flagged : void 0 }] : []
2853
+ );
2854
+ const flagOnly = flagged !== void 0 && !fromFile.some(({ key }) => key === defaultKey) ? [{ key: defaultKey, definition, given: void 0, flagged }] : [];
2855
+ return [...fromFile, ...flagOnly];
2856
+ });
2857
+ }
2858
+ function plainValues(settings) {
2859
+ return Object.fromEntries(
2860
+ Object.entries(settings).flatMap(([option, setting]) => setting === void 0 ? [] : [[option, setting.value]])
2861
+ );
2862
+ }
2863
+ function plannedOptions(definition, key, settings) {
2864
+ return Object.entries(definition.options).flatMap(([option, rule]) => {
2865
+ const setting = settings[option];
2866
+ if (!isDefaultFunction(rule.default) || setting === void 0) return [];
2867
+ const { value, source } = setting;
2868
+ const path = optionKeyPath(key, option);
2869
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
2870
+ throw new Error(`${path} has a default that is a function, so it must take a string, number or boolean`);
2871
+ return [{ path, value, source }];
2872
+ });
2470
2873
  }
2471
- function checkSetting(key, value, settings, problems) {
2472
- const checked = checkSettingValue(key, value);
2473
- if (checked.ok) Object.assign(settings, { [key]: checked.value });
2474
- else
2475
- for (const { path: inside, problem } of checked.problems)
2476
- problems.push({ key: [key, ...inside].join("."), location: null, problem });
2874
+
2875
+ // src/config/settings-file.ts
2876
+ async function loadSettingsFile(gateway, cwd, definitions) {
2877
+ const loaded = await loadConfig(gateway, cwd, definitions);
2878
+ if (loaded.kind === "invalid") return refused(invalidConfig(loaded.path, loaded.problems));
2879
+ return loaded.kind === "loaded" ? { ok: true, path: loaded.path, values: loaded.values, definitions } : { ok: true, path: null, values: void 0, definitions };
2477
2880
  }
2478
- function checkResources(value, definitions, problems) {
2479
- if (value === void 0) return {};
2480
- if (!isRecord2(value)) {
2481
- problems.push({ key: "resources", location: null, problem: `must be an object, not ${describeValue(value)}` });
2482
- return {};
2483
- }
2484
- const byName = new Map(definitions.map((definition) => [definition.name, definition]));
2485
- const holds = definitions.length === 0 ? "none" : definitions.map((each) => each.name).join(", ");
2486
- const found = {};
2487
- for (const [key, resource] of Object.entries(value)) {
2488
- const named = entryName(resource);
2489
- const definition = byName.get(named !== void 0 && byName.has(named) ? named : key);
2490
- if (named !== void 0 && definition !== void 0 && key !== defaultResourceKey(definition)) {
2491
- problems.push({
2492
- key: `resources.${key}`,
2493
- location: null,
2494
- problem: `holds a ${named} resource; for now a resource's key must be its definition's name: name its key ${defaultResourceKey(definition)}`
2495
- });
2496
- continue;
2497
- }
2498
- if (definition === void 0) {
2499
- problems.push({
2500
- key: `resources.${key}`,
2501
- location: null,
2502
- problem: `is not a resource; resources holds ${holds}`
2503
- });
2504
- continue;
2505
- }
2506
- if (resource === void 0) continue;
2507
- const options = checkResource(definition, key, resource, problems);
2508
- if (options !== void 0) found[key] = { definition: definition.name, options };
2509
- }
2510
- return found;
2881
+ function fileSettings(file, flags) {
2882
+ return resolveSettings(flags, file.values?.settings);
2511
2883
  }
2512
- function entryName(value) {
2513
- return isRecord2(value) && typeof value["name"] === "string" ? value["name"] : void 0;
2884
+ function fileOptions(file, definition) {
2885
+ if (!file.definitions.includes(definition))
2886
+ throw new Error(`The config file wasn't checked against ${definition.name}`);
2887
+ const given = file.values?.resources[defaultResourceKey(definition)];
2888
+ return given === void 0 || given.definition !== definition.name ? void 0 : givenOptionsOf(definition, given.options);
2514
2889
  }
2515
- function checkResource(definition, key, value, problems) {
2516
- const { name } = definition;
2517
- const options = isRecord2(value) && value["name"] === name ? value["options"] : void 0;
2518
- if (!isRecord2(options)) {
2519
- problems.push({
2520
- key: `resources.${key}`,
2521
- location: null,
2522
- problem: `must be made by ${resourceCall(name)}, not ${describeValue(value)}`
2523
- });
2524
- return void 0;
2525
- }
2526
- const checked = {};
2527
- let valid = true;
2528
- for (const [option, optionValue] of Object.entries(options)) {
2529
- const path = `resources.${key}.${option}`;
2530
- const rule = Object.hasOwn(definition.options, option) ? definition.options[option] : void 0;
2531
- if (rule === void 0) {
2532
- valid = false;
2533
- problems.push({ key: path, location: null, problem: `is not a ${name} option` });
2534
- continue;
2535
- }
2536
- if (optionValue === void 0) continue;
2537
- const result = checkWith(rule.schema, optionValue);
2538
- if (result.ok) checked[option] = result.value;
2539
- else {
2540
- valid = false;
2541
- for (const { path: inside, problem } of result.problems)
2542
- problems.push({ key: [path, ...inside].join("."), location: null, problem });
2890
+ function settleRunResources(file, flags) {
2891
+ const merged = mergeRunResources(file.definitions, file.values?.resources, flags);
2892
+ if (!merged.ok) return refused(invalidResourceOptions(file.path, merged.problems));
2893
+ return {
2894
+ ok: true,
2895
+ options: merged.options,
2896
+ plan(run) {
2897
+ const resolved = merged.plan(run);
2898
+ if (!resolved.ok) return refused(invalidResourceOptions(file.path, resolved.problems));
2899
+ return { ok: true, resources: resolved.value, planned: resolved.planned };
2543
2900
  }
2544
- }
2545
- return valid ? checked : void 0;
2901
+ };
2546
2902
  }
2547
- function isRecord2(value) {
2548
- return typeof value === "object" && value !== null && !Array.isArray(value);
2903
+ function invalidConfig(file, problems) {
2904
+ return configErrors.invalidConfig({
2905
+ file,
2906
+ problems: problems.map(({ key, location, problem }) => ({
2907
+ key,
2908
+ location: location === null ? null : { line: location.line, column: location.column ?? null },
2909
+ problem
2910
+ }))
2911
+ });
2549
2912
  }
2550
- function fileProblem(problem) {
2551
- return { key: null, location: null, problem };
2913
+ function invalidResourceOptions(configFile, problems) {
2914
+ return configErrors.invalidResourceOptions({
2915
+ configFile,
2916
+ problems: problems.map(({ key, problem, values }) => ({
2917
+ key,
2918
+ problem,
2919
+ values: values.map(({ key: valueKey, value, source }) => ({ key: valueKey, value: valueText(value), source }))
2920
+ }))
2921
+ });
2922
+ }
2923
+ function valueText(value) {
2924
+ return typeof value === "string" ? value : describeValue(value);
2552
2925
  }
2553
2926
 
2554
2927
  // src/config/credential-resolver.ts
2555
- import { z as z5 } from "zod";
2928
+ import { z as z6 } from "zod";
2556
2929
 
2557
2930
  // src/credential/live/github-actions-token-response.ts
2558
2931
  var SAID_LIMIT = 200;
@@ -2849,185 +3222,55 @@ function mintTargetText(target) {
2849
3222
  return `Vercel project ${target.project} on team ${target.team}`;
2850
3223
  }
2851
3224
 
2852
- // src/config/credential-settle.ts
2853
- import { z as z4 } from "zod";
2854
- var credentialErrors = defineErrors({
2855
- missingTarget: {
2856
- exitCode: 2,
2857
- description: "The command may mint a credential, and neither a flag nor storm.config.ts names the control plane team or project.",
2858
- schema: z4.object({
2859
- /** The settings no flag or config file gave. */
2860
- missing: z4.array(z4.enum(["scope", "project"]))
2861
- }),
2862
- render: ({ missing }) => ({
2863
- message: `No control plane ${missing.map((key) => key === "scope" ? "team" : "project").join(" or ")} to mint a credential for.`,
2864
- next: [
2865
- {
2866
- type: "text",
2867
- text: `Give ${missing.map((key) => `--${key}`).join(" and ")}, or set ${missing.join(" and ")} in storm.config.ts.`
2868
- }
2869
- ]
2870
- })
2871
- }
2872
- });
2873
- function requireTarget(scope, project) {
2874
- if (scope === void 0 || project === void 0)
2875
- return refused(
2876
- credentialErrors.missingTarget({
2877
- missing: [
2878
- ...scope === void 0 ? ["scope"] : [],
2879
- ...project === void 0 ? ["project"] : []
2880
- ]
2881
- })
2882
- );
2883
- return { ok: true, target: { team: scope.value, project: project.value } };
2884
- }
2885
- function settleCredential(source, scope, project) {
2886
- if (source === "github-actions") return { ok: true, credential: { source } };
2887
- const required = requireTarget(scope, project);
2888
- if (!required.ok) return required;
2889
- return { ok: true, credential: { source, target: required.target } };
2890
- }
2891
-
2892
3225
  // src/config/credential-resolver.ts
2893
3226
  var credentialSourceErrors = defineErrors({
2894
3227
  mintFailed: {
2895
3228
  exitCode: 1,
2896
3229
  description: "The vercel CLI couldn't mint a credential for the team and project.",
2897
- schema: z5.object({ team: z5.string(), project: z5.string(), cause: z5.string(), fix: z5.string() }),
3230
+ schema: z6.object({ team: z6.string(), project: z6.string(), cause: z6.string(), fix: z6.string() }),
2898
3231
  render: ({ cause, fix }) => ({
2899
3232
  message: `Couldn't mint a credential: ${cause}.`,
2900
3233
  next: [{ type: "text", text: fix }]
2901
3234
  })
2902
3235
  },
2903
- tokenRequestFailed: {
2904
- exitCode: 1,
2905
- description: "With --credential github-actions, the GitHub Actions OIDC token request failed.",
2906
- schema: z5.object(tokenRequestFailureShape),
2907
- render: ({ detail, fix }) => ({
2908
- message: `Couldn't request a GitHub Actions OIDC token: ${detail}.`,
2909
- next: [{ type: "text", text: fix }]
2910
- })
2911
- }
2912
- });
2913
- function credentialSourceError(failure) {
2914
- return failure.source === "mint" ? credentialSourceErrors.mintFailed({ ...failure.target, ...describeMintFailure(failure.failure, failure.target) }) : credentialSourceErrors.tokenRequestFailed(tokenRequestFailureFacts(failure.failure));
2915
- }
2916
- function credentialResolver(gateways) {
2917
- return {
2918
- source(choice, target, report = {}) {
2919
- const chosen = settleCredential(choice, target.scope, target.project);
2920
- if (!chosen.ok) return chosen;
2921
- const { progress } = report;
2922
- const source = credentialSourceFor(chosen.credential, gateways, {
2923
- emit: async (event) => {
2924
- if (event.kind === "minting") await progress?.(`Minting a credential for ${mintTargetText(event.target)}\u2026`);
2925
- else if (event.kind === "requesting-token") await progress?.(REQUESTING_TOKEN_LINE);
2926
- }
2927
- });
2928
- return {
2929
- ok: true,
2930
- source: {
2931
- async obtain() {
2932
- const got = await source.obtain();
2933
- return got.ok ? got : { ok: false, refusal: credentialSourceError(got.failure) };
2934
- },
2935
- origin: (credential) => source.origin(credential)
2936
- }
2937
- };
2938
- }
2939
- };
2940
- }
2941
-
2942
- // src/config/errors.ts
2943
- import { z as z6 } from "zod";
2944
- var problemSchema = z6.object({
2945
- /** The key the problem is about; null when it is about the whole file. */
2946
- key: z6.string().nullable(),
2947
- /** Where Node said the import failed; null otherwise. */
2948
- location: z6.object({ line: z6.number(), column: z6.number().nullable() }).nullable(),
2949
- /** What is wrong, worded to follow the key, or the file name when there is no key. */
2950
- problem: z6.string()
2951
- });
2952
- function configProblemLine(file, { key, location, problem }) {
2953
- const sentence = `${problem.replace(/\.$/, "")}.`;
2954
- if (key !== null) return `${file}: ${key} ${sentence}`;
2955
- if (location !== null)
2956
- return `${file}:${location.line}${location.column === null ? "" : `:${location.column}`} ${sentence}`;
2957
- return `${file}: ${sentence}`;
2958
- }
2959
- var optionValueSchema = z6.object({
2960
- /** The option's key path, such as resources.<key>.ttl. */
2961
- key: z6.string(),
2962
- /** Its value, as text. */
2963
- value: z6.string(),
2964
- /** Where it came from: the command's own flag for the option, the config file or the default. */
2965
- source: z6.enum(["flag", "file", "default"])
2966
- });
2967
- var optionProblemSchema = z6.object({
2968
- /** The key path of the option the problem is about, such as resources.<key>.ttl. */
2969
- key: z6.string(),
2970
- /** What is wrong, worded to follow the key path, as the resource's rule words it. */
2971
- problem: z6.string(),
2972
- /** Each value the problem is about, with its source; empty for a required option nothing gave. */
2973
- values: z6.array(optionValueSchema)
2974
- });
2975
- function optionValueText({ key, value, source }, configFile) {
2976
- switch (source) {
2977
- case "flag":
2978
- return `${key} is ${value} from the command line`;
2979
- case "file":
2980
- return `${key} is ${value} in ${configFile ?? "storm.config.ts"}`;
2981
- case "default":
2982
- return `${key} is ${value} by default`;
2983
- }
2984
- }
2985
- function optionProblemLine({ key, problem, values }, configFile) {
2986
- const where2 = values.map((value) => optionValueText(value, configFile));
2987
- const sources = where2.length === 0 ? "" : `: ${where2.length === 1 ? where2.join("") : `${where2.slice(0, -1).join(", ")} and ${where2.at(-1) ?? ""}`}`;
2988
- return `${key} ${problem.replace(/\.$/, "")}${sources}.`;
2989
- }
2990
- var configErrors = defineErrors({
2991
- invalidConfig: {
2992
- exitCode: 2,
2993
- description: "storm.config.ts can't be used: it can't be imported, doesn't default-export an object, has an unknown key, or a value in it is invalid. storm checks the whole file whenever a command loads it.",
2994
- schema: z6.object({
2995
- /** The config file's absolute path. */
2996
- file: z6.string(),
2997
- problems: z6.array(problemSchema)
2998
- }),
2999
- render: ({ file, problems }) => {
3000
- const [first, ...rest] = problems;
3001
- return {
3002
- message: first === void 0 ? `${file} can't be used.` : configProblemLine(file, first),
3003
- ...rest.length === 0 ? {} : { rows: [["Also", rest.map((problem) => configProblemLine(file, problem))]] },
3004
- next: [{ type: "text", text: `Fix ${file}, then retry.` }]
3005
- };
3006
- }
3007
- },
3008
- invalidResourceOptions: {
3009
- exitCode: 2,
3010
- description: "A resource's options, once its defaults, storm.config.ts and the flags are merged, don't fit together, as the resource's own checks say, or one it requires is missing: such as resources.<key>.ttl not longer than its minTimeLeft. Each problem names the values it is about and where each came from.",
3011
- schema: z6.object({
3012
- /** The config file that applied; null when none did. */
3013
- configFile: z6.string().nullable(),
3014
- problems: z6.array(optionProblemSchema)
3015
- }),
3016
- render: ({ configFile, problems }) => {
3017
- const [first, ...rest] = problems;
3236
+ tokenRequestFailed: {
3237
+ exitCode: 1,
3238
+ description: "With --credential github-actions, the GitHub Actions OIDC token request failed.",
3239
+ schema: z6.object(tokenRequestFailureShape),
3240
+ render: ({ detail, fix }) => ({
3241
+ message: `Couldn't request a GitHub Actions OIDC token: ${detail}.`,
3242
+ next: [{ type: "text", text: fix }]
3243
+ })
3244
+ }
3245
+ });
3246
+ function credentialSourceError(failure) {
3247
+ return failure.source === "mint" ? credentialSourceErrors.mintFailed({ ...failure.target, ...describeMintFailure(failure.failure, failure.target) }) : credentialSourceErrors.tokenRequestFailed(tokenRequestFailureFacts(failure.failure));
3248
+ }
3249
+ function credentialResolver(gateways) {
3250
+ return {
3251
+ source(choice, target, report = {}) {
3252
+ const chosen = settleCredential(choice, target.scope, target.project);
3253
+ if (!chosen.ok) return chosen;
3254
+ const { progress } = report;
3255
+ const source = credentialSourceFor(chosen.credential, gateways, {
3256
+ emit: async (event) => {
3257
+ if (event.kind === "minting") await progress?.(`Minting a credential for ${mintTargetText(event.target)}\u2026`);
3258
+ else if (event.kind === "requesting-token") await progress?.(REQUESTING_TOKEN_LINE);
3259
+ }
3260
+ });
3018
3261
  return {
3019
- message: first === void 0 ? "A resource's options don't fit together." : optionProblemLine(first, configFile),
3020
- ...rest.length === 0 ? {} : { rows: [["Also", rest.map((problem) => optionProblemLine(problem, configFile))]] },
3021
- next: [
3022
- {
3023
- type: "text",
3024
- text: `Change the options on the command line or in ${configFile ?? "storm.config.ts"}, then retry.`
3025
- }
3026
- ]
3262
+ ok: true,
3263
+ source: {
3264
+ async obtain() {
3265
+ const got = await source.obtain();
3266
+ return got.ok ? got : { ok: false, refusal: credentialSourceError(got.failure) };
3267
+ },
3268
+ origin: (credential) => source.origin(credential)
3269
+ }
3027
3270
  };
3028
3271
  }
3029
- }
3030
- });
3272
+ };
3273
+ }
3031
3274
 
3032
3275
  // src/config/live/config-gateway.ts
3033
3276
  import { stat } from "node:fs/promises";
@@ -3076,17 +3319,6 @@ function errorLocation(error, name) {
3076
3319
  return void 0;
3077
3320
  }
3078
3321
 
3079
- // src/config/typed-options.ts
3080
- function givenOptionsOf(_definition, values) {
3081
- return values;
3082
- }
3083
- function settingsOf(_definition, settings) {
3084
- return settings;
3085
- }
3086
- function resourceOptionsOf(_definition, value) {
3087
- return value;
3088
- }
3089
-
3090
3322
  // src/config/recipe-run.ts
3091
3323
  var NOT_PRESENT = Object.freeze({ present: false });
3092
3324
  function recipeRun(resources) {
@@ -3104,199 +3336,6 @@ function recipeRun(resources) {
3104
3336
  return { run: Object.freeze(run), resourceKeys: Object.keys(resources) };
3105
3337
  }
3106
3338
 
3107
- // src/config/resolve.ts
3108
- function resolveSettings(flags, file) {
3109
- const pick = (flag, fromFile) => flag !== void 0 ? { value: flag, source: "flag" } : fromFile === void 0 ? void 0 : { value: fromFile, source: "file" };
3110
- return {
3111
- scope: pick(flags.scope, file?.scope),
3112
- project: pick(flags.project, file?.project),
3113
- runner: pick(void 0, file?.runner)
3114
- };
3115
- }
3116
- function optionSource(definition, option, file, flags) {
3117
- const fromFile = file ?? {};
3118
- const fromFlags = flags ?? {};
3119
- if (fromFlags[option] !== void 0) return "flag";
3120
- if (fromFile[option] !== void 0) return "file";
3121
- return definition.options[option]?.default === void 0 ? void 0 : "default";
3122
- }
3123
- function mergeResourceOptions(definition, key, file, flags) {
3124
- const fromFile = file ?? {};
3125
- const fromFlags = flags ?? {};
3126
- const merged = [];
3127
- const problems = [];
3128
- for (const [option, rule] of Object.entries(definition.options)) {
3129
- const source = optionSource(definition, option, file, flags);
3130
- if (source === "flag") merged.push([option, { value: fromFlags[option], source }]);
3131
- else if (source === "file") merged.push([option, { value: fromFile[option], source }]);
3132
- else if (source === "default") merged.push([option, "default"]);
3133
- else if (rule.required === true) {
3134
- problems.push({
3135
- key: optionKeyPath(key, option),
3136
- problem: `is required; give it in ${resourceCall(definition.name)}`,
3137
- values: []
3138
- });
3139
- }
3140
- }
3141
- if (problems.length > 0) return { ok: false, problems };
3142
- return {
3143
- ok: true,
3144
- settings: (run) => (
3145
- // Every option with a default or marked required is in `merged`, so it is what `definition.check` takes.
3146
- settingsOf(
3147
- definition,
3148
- Object.fromEntries(
3149
- merged.map(([option, given]) => [
3150
- option,
3151
- given === "default" ? { value: defaultValue(definition, option, run), source: "default" } : given
3152
- ])
3153
- )
3154
- )
3155
- )
3156
- };
3157
- }
3158
- function isDefaultFunction(given) {
3159
- return typeof given === "function";
3160
- }
3161
- function defaultValue(definition, option, run) {
3162
- const rule = definition.options[option];
3163
- if (rule === void 0 || !isDefaultFunction(rule.default)) return rule?.default;
3164
- const checked = rule.schema.safeParse(rule.default(run));
3165
- if (checked.success) return checked.data;
3166
- const problems = checked.error.issues.map(({ message }) => message).join("; ");
3167
- throw new Error(
3168
- `${definition.name}'s option ${option} has a default that gave a value its schema refuses: ${problems}`
3169
- );
3170
- }
3171
- function mergeRunResources(definitions, file, flags) {
3172
- const resources = [];
3173
- const problems = [];
3174
- for (const { key, definition, given, flagged } of runResources(definitions, file, flags)) {
3175
- const merged = mergeResourceOptions(definition, key, given, flagged);
3176
- if (merged.ok) resources.push({ key, definition, settings: merged.settings });
3177
- else problems.push(...merged.problems);
3178
- }
3179
- if (problems.length > 0) return { ok: false, problems };
3180
- const options = Object.fromEntries(
3181
- resources.map(({ key, definition, settings }) => [
3182
- key,
3183
- { definition: definition.name, options: plainValues(settings(NOT_COUNTED)) }
3184
- ])
3185
- );
3186
- return { ok: true, options, plan: (run) => planResources(resources, run) };
3187
- }
3188
- function planResources(resources, run) {
3189
- const resolved = {};
3190
- const planned = [];
3191
- const problems = [];
3192
- for (const { key, definition, settings: settingsFor } of resources) {
3193
- const merged = settingsFor(run);
3194
- const settings = merged;
3195
- planned.push(...plannedOptions(definition, key, settings));
3196
- const refused2 = definition.check(merged);
3197
- if (refused2.length === 0)
3198
- resolved[key] = {
3199
- definition: definition.name,
3200
- options: plainValues(settings),
3201
- sources: Object.fromEntries(
3202
- Object.keys(definition.options).map((option) => [option, settings[option]?.source])
3203
- )
3204
- };
3205
- else
3206
- for (const { option, problem, involves } of refused2)
3207
- problems.push({
3208
- key: optionKeyPath(key, option),
3209
- problem,
3210
- values: involves.flatMap((each) => {
3211
- const setting = settings[each];
3212
- return setting === void 0 ? [] : [{ key: optionKeyPath(key, each), value: setting.value, source: setting.source }];
3213
- })
3214
- });
3215
- }
3216
- if (problems.length > 0) return { ok: false, problems };
3217
- return { ok: true, value: resolved, planned };
3218
- }
3219
- function runResources(definitions, file, flags) {
3220
- const resources = Object.entries(file ?? {});
3221
- return definitions.flatMap((definition) => {
3222
- const defaultKey = defaultResourceKey(definition);
3223
- const flagged = flags[definition.name];
3224
- const fromFile = resources.flatMap(
3225
- ([key, resource]) => resource.definition === definition.name ? [{ key, definition, given: resource.options, flagged: key === defaultKey ? flagged : void 0 }] : []
3226
- );
3227
- const flagOnly = flagged !== void 0 && !fromFile.some(({ key }) => key === defaultKey) ? [{ key: defaultKey, definition, given: void 0, flagged }] : [];
3228
- return [...fromFile, ...flagOnly];
3229
- });
3230
- }
3231
- function plainValues(settings) {
3232
- return Object.fromEntries(
3233
- Object.entries(settings).flatMap(([option, setting]) => setting === void 0 ? [] : [[option, setting.value]])
3234
- );
3235
- }
3236
- function plannedOptions(definition, key, settings) {
3237
- return Object.entries(definition.options).flatMap(([option, rule]) => {
3238
- const setting = settings[option];
3239
- if (!isDefaultFunction(rule.default) || setting === void 0) return [];
3240
- const { value, source } = setting;
3241
- const path = optionKeyPath(key, option);
3242
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
3243
- throw new Error(`${path} has a default that is a function, so it must take a string, number or boolean`);
3244
- return [{ path, value, source }];
3245
- });
3246
- }
3247
-
3248
- // src/config/settings-file.ts
3249
- async function loadSettingsFile(gateway, cwd, definitions) {
3250
- const loaded = await loadConfig(gateway, cwd, definitions);
3251
- if (loaded.kind === "invalid") return refused(invalidConfig(loaded.path, loaded.problems));
3252
- return loaded.kind === "loaded" ? { ok: true, path: loaded.path, values: loaded.values, definitions } : { ok: true, path: null, values: void 0, definitions };
3253
- }
3254
- function fileSettings(file, flags) {
3255
- return resolveSettings(flags, file.values?.settings);
3256
- }
3257
- function fileOptions(file, definition) {
3258
- if (!file.definitions.includes(definition))
3259
- throw new Error(`The config file wasn't checked against ${definition.name}`);
3260
- const given = file.values?.resources[defaultResourceKey(definition)];
3261
- return given === void 0 || given.definition !== definition.name ? void 0 : givenOptionsOf(definition, given.options);
3262
- }
3263
- function settleRunResources(file, flags) {
3264
- const merged = mergeRunResources(file.definitions, file.values?.resources, flags);
3265
- if (!merged.ok) return refused(invalidResourceOptions(file.path, merged.problems));
3266
- return {
3267
- ok: true,
3268
- options: merged.options,
3269
- plan(run) {
3270
- const resolved = merged.plan(run);
3271
- if (!resolved.ok) return refused(invalidResourceOptions(file.path, resolved.problems));
3272
- return { ok: true, resources: resolved.value, planned: resolved.planned };
3273
- }
3274
- };
3275
- }
3276
- function invalidConfig(file, problems) {
3277
- return configErrors.invalidConfig({
3278
- file,
3279
- problems: problems.map(({ key, location, problem }) => ({
3280
- key,
3281
- location: location === null ? null : { line: location.line, column: location.column ?? null },
3282
- problem
3283
- }))
3284
- });
3285
- }
3286
- function invalidResourceOptions(configFile, problems) {
3287
- return configErrors.invalidResourceOptions({
3288
- configFile,
3289
- problems: problems.map(({ key, problem, values }) => ({
3290
- key,
3291
- problem,
3292
- values: values.map(({ key: valueKey, value, source }) => ({ key: valueKey, value: valueText(value), source }))
3293
- }))
3294
- });
3295
- }
3296
- function valueText(value) {
3297
- return typeof value === "string" ? value : describeValue(value);
3298
- }
3299
-
3300
3339
  // src/config/resolver.ts
3301
3340
  function configResolver(launcher) {
3302
3341
  return {
@@ -3328,7 +3367,10 @@ export {
3328
3367
  credentialSourceErrors,
3329
3368
  credentialResolver,
3330
3369
  configErrors,
3331
- liveCheckoutGateway,
3370
+ RUNNER_SECRET_MIN_LENGTH,
3371
+ declaredSecretValues,
3372
+ readRunnerSecrets,
3373
+ RUNNER_SNAPSHOTS_SUBPATH,
3332
3374
  parseKeepTime,
3333
3375
  systemTimer,
3334
3376
  systemClock,
@@ -3337,18 +3379,18 @@ export {
3337
3379
  parseTestEvent,
3338
3380
  redactSecrets,
3339
3381
  lineSplitter,
3340
- runStepTakesSecret,
3382
+ prepareSnapshotBuild,
3383
+ buildSnapshots,
3384
+ liveCheckoutGateway,
3341
3385
  liveRunnerSandboxGateway,
3342
3386
  liveRunnerTerminal,
3343
3387
  localUserName,
3344
- RUNNER_SNAPSHOTS_SUBPATH,
3345
3388
  liveRunnerSnapshotCacheGateway,
3346
3389
  unavailableRunnerSnapshotCacheGateway,
3347
3390
  prepareRunner,
3348
3391
  SANDBOX_TEST_EVENTS_PATH,
3349
- RUNNER_SECRET_MIN_LENGTH,
3350
- readRunnerSecrets,
3351
3392
  openRunnerSession,
3393
+ inspectSnapshotCache,
3352
3394
  CONFIG_FILE_NAME,
3353
3395
  liveConfigGateway,
3354
3396
  findConfigFile,