@selvajs/selva 4.21.0-beta.13 → 4.21.0-beta.15

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 (208) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/assets/0.DOeouCe4.css +2 -0
  3. package/build/client/_app/immutable/assets/0.DOeouCe4.css.br +0 -0
  4. package/build/client/_app/immutable/assets/0.DOeouCe4.css.gz +0 -0
  5. package/build/client/_app/immutable/chunks/{BRA_lgsI.js → B3e8ZKjr.js} +1 -1
  6. package/build/client/_app/immutable/chunks/B3e8ZKjr.js.br +0 -0
  7. package/build/client/_app/immutable/chunks/{BRA_lgsI.js.gz → B3e8ZKjr.js.gz} +0 -0
  8. package/build/client/_app/immutable/chunks/{CzHxHvr2.js → B7agp_uZ.js} +1 -1
  9. package/build/client/_app/immutable/chunks/B7agp_uZ.js.br +0 -0
  10. package/build/client/_app/immutable/chunks/B7agp_uZ.js.gz +0 -0
  11. package/build/client/_app/immutable/chunks/BUENW6k7.js +1 -0
  12. package/build/client/_app/immutable/chunks/BUENW6k7.js.br +0 -0
  13. package/build/client/_app/immutable/chunks/BUENW6k7.js.gz +0 -0
  14. package/build/client/_app/immutable/chunks/CCHz3Pcq.js +1 -0
  15. package/build/client/_app/immutable/chunks/CCHz3Pcq.js.br +1 -0
  16. package/build/client/_app/immutable/chunks/CCHz3Pcq.js.gz +0 -0
  17. package/build/client/_app/immutable/chunks/CVA0v6Z8.js +6085 -0
  18. package/build/client/_app/immutable/chunks/CVA0v6Z8.js.br +0 -0
  19. package/build/client/_app/immutable/chunks/CVA0v6Z8.js.gz +0 -0
  20. package/build/client/_app/immutable/chunks/Ch_UJBk-.js +1 -0
  21. package/build/client/_app/immutable/chunks/Ch_UJBk-.js.br +1 -0
  22. package/build/client/_app/immutable/chunks/Ch_UJBk-.js.gz +0 -0
  23. package/build/client/_app/immutable/chunks/{BCbumNc2.js → DEthS42j.js} +1 -1
  24. package/build/client/_app/immutable/chunks/DEthS42j.js.br +0 -0
  25. package/build/client/_app/immutable/chunks/DEthS42j.js.gz +0 -0
  26. package/build/client/_app/immutable/chunks/{FIoX_cjM.js → Nv1S5RTq.js} +1 -1
  27. package/build/client/_app/immutable/chunks/Nv1S5RTq.js.br +0 -0
  28. package/build/client/_app/immutable/chunks/Nv1S5RTq.js.gz +0 -0
  29. package/build/client/_app/immutable/entry/{app.BP5swwM7.js → app.B1zrk4oJ.js} +2 -2
  30. package/build/client/_app/immutable/entry/app.B1zrk4oJ.js.br +0 -0
  31. package/build/client/_app/immutable/entry/app.B1zrk4oJ.js.gz +0 -0
  32. package/build/client/_app/immutable/entry/{start.BW9gOvFV.js → start.B312GghS.js} +2 -2
  33. package/build/client/_app/immutable/entry/start.B312GghS.js.br +1 -0
  34. package/build/client/_app/immutable/entry/start.B312GghS.js.gz +0 -0
  35. package/build/client/_app/immutable/nodes/{11.NPUXRN3p.js → 11.CnQVPSaL.js} +1 -1
  36. package/build/client/_app/immutable/nodes/11.CnQVPSaL.js.br +0 -0
  37. package/build/client/_app/immutable/nodes/11.CnQVPSaL.js.gz +0 -0
  38. package/build/client/_app/immutable/nodes/{13.BQ0cOim-.js → 13.TEbI6lFx.js} +2 -2
  39. package/build/client/_app/immutable/nodes/13.TEbI6lFx.js.br +0 -0
  40. package/build/client/_app/immutable/nodes/13.TEbI6lFx.js.gz +0 -0
  41. package/build/client/_app/immutable/nodes/{14.BsbXlPTK.js → 14.Dx84-S7G.js} +1 -1
  42. package/build/client/_app/immutable/nodes/14.Dx84-S7G.js.br +0 -0
  43. package/build/client/_app/immutable/nodes/14.Dx84-S7G.js.gz +0 -0
  44. package/build/client/_app/immutable/nodes/{15.C0vWxAsK.js → 15.CEROqZ8B.js} +1 -1
  45. package/build/client/_app/immutable/nodes/15.CEROqZ8B.js.br +0 -0
  46. package/build/client/_app/immutable/nodes/15.CEROqZ8B.js.gz +0 -0
  47. package/build/client/_app/immutable/nodes/{16.BE4OfH4C.js → 16.C7nA7TCy.js} +1 -1
  48. package/build/client/_app/immutable/nodes/16.C7nA7TCy.js.br +0 -0
  49. package/build/client/_app/immutable/nodes/16.C7nA7TCy.js.gz +0 -0
  50. package/build/client/_app/immutable/nodes/{2.CWOFnTAV.js → 2.Dstc2B2E.js} +1 -1
  51. package/build/client/_app/immutable/nodes/2.Dstc2B2E.js.br +0 -0
  52. package/build/client/_app/immutable/nodes/2.Dstc2B2E.js.gz +0 -0
  53. package/build/client/_app/immutable/nodes/{20.4vwwwrQ_.js → 20.B2EnikH5.js} +2 -2
  54. package/build/client/_app/immutable/nodes/20.B2EnikH5.js.br +0 -0
  55. package/build/client/_app/immutable/nodes/20.B2EnikH5.js.gz +0 -0
  56. package/build/client/_app/immutable/nodes/21.CFGMFbJt.js +1 -0
  57. package/build/client/_app/immutable/nodes/21.CFGMFbJt.js.br +1 -0
  58. package/build/client/_app/immutable/nodes/21.CFGMFbJt.js.gz +0 -0
  59. package/build/client/_app/immutable/nodes/{25.DR2ojPn5.js → 25.DCzT_X3a.js} +6 -6
  60. package/build/client/_app/immutable/nodes/25.DCzT_X3a.js.br +0 -0
  61. package/build/client/_app/immutable/nodes/25.DCzT_X3a.js.gz +0 -0
  62. package/build/client/_app/immutable/nodes/{29.PsrL6xdd.js → 29.DWokJWH0.js} +1 -1
  63. package/build/client/_app/immutable/nodes/29.DWokJWH0.js.br +0 -0
  64. package/build/client/_app/immutable/nodes/29.DWokJWH0.js.gz +0 -0
  65. package/build/client/_app/immutable/nodes/{30.Cd56Qv6o.js → 30.ForK2knd.js} +1 -1
  66. package/build/client/_app/immutable/nodes/30.ForK2knd.js.br +0 -0
  67. package/build/client/_app/immutable/nodes/30.ForK2knd.js.gz +0 -0
  68. package/build/client/_app/immutable/nodes/{31.CFCkC-P2.js → 31.DEYw8Upz.js} +1 -1
  69. package/build/client/_app/immutable/nodes/31.DEYw8Upz.js.br +0 -0
  70. package/build/client/_app/immutable/nodes/31.DEYw8Upz.js.gz +0 -0
  71. package/build/client/_app/immutable/nodes/{32.DWY9hRHg.js → 32.Bi8d2lf7.js} +1 -1
  72. package/build/client/_app/immutable/nodes/32.Bi8d2lf7.js.br +0 -0
  73. package/build/client/_app/immutable/nodes/32.Bi8d2lf7.js.gz +0 -0
  74. package/build/client/_app/immutable/nodes/{34.ZQaLUUXZ.js → 34.DUW5te4K.js} +1 -1
  75. package/build/client/_app/immutable/nodes/34.DUW5te4K.js.br +0 -0
  76. package/build/client/_app/immutable/nodes/34.DUW5te4K.js.gz +0 -0
  77. package/build/client/_app/immutable/nodes/{35.BPmyLjFW.js → 35.Dpj9Kp45.js} +2 -2
  78. package/build/client/_app/immutable/nodes/35.Dpj9Kp45.js.br +0 -0
  79. package/build/client/_app/immutable/nodes/35.Dpj9Kp45.js.gz +0 -0
  80. package/build/client/_app/immutable/nodes/{5.wbpOzblK.js → 5.CA3-Q2Yj.js} +1 -1
  81. package/build/client/_app/immutable/nodes/5.CA3-Q2Yj.js.br +1 -0
  82. package/build/client/_app/immutable/nodes/5.CA3-Q2Yj.js.gz +0 -0
  83. package/build/client/_app/immutable/nodes/{6.B2HdJrZB.js → 6.DXhDcOvi.js} +1 -1
  84. package/build/client/_app/immutable/nodes/6.DXhDcOvi.js.br +0 -0
  85. package/build/client/_app/immutable/nodes/6.DXhDcOvi.js.gz +0 -0
  86. package/build/client/_app/immutable/nodes/{7.BuWU0YDv.js → 7.B-g8F3Ul.js} +1 -1
  87. package/build/client/_app/immutable/nodes/7.B-g8F3Ul.js.br +0 -0
  88. package/build/client/_app/immutable/nodes/7.B-g8F3Ul.js.gz +0 -0
  89. package/build/client/_app/immutable/nodes/{9.Bxpo8jgd.js → 9.Bk5Lntvs.js} +1 -1
  90. package/build/client/_app/immutable/nodes/9.Bk5Lntvs.js.br +0 -0
  91. package/build/client/_app/immutable/nodes/9.Bk5Lntvs.js.gz +0 -0
  92. package/build/client/_app/version.json +1 -1
  93. package/build/client/_app/version.json.br +0 -0
  94. package/build/client/_app/version.json.gz +0 -0
  95. package/build/server/.vite/manifest.json +3 -2
  96. package/build/server/_app/immutable/assets/_layout.DOeouCe4.css +2 -0
  97. package/build/server/chunks/instance.js +3 -3
  98. package/build/server/chunks/internal.js +1 -1
  99. package/build/server/chunks/package.js +1 -1
  100. package/build/server/chunks/package.js.map +1 -1
  101. package/build/server/chunks/providers.server.js +4 -0
  102. package/build/server/chunks/providers.server.js.map +1 -1
  103. package/build/server/chunks/update-outcome.js +24 -7
  104. package/build/server/chunks/update-outcome.js.map +1 -1
  105. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +99 -25
  106. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js.map +1 -1
  107. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +17 -7
  108. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
  109. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +27 -14
  110. package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
  111. package/build/server/entries/pages/library/_guid_/_page.svelte.js +13 -1
  112. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  113. package/build/server/entries/pages/projects/_page.svelte.js +1 -0
  114. package/build/server/entries/pages/projects/_page.svelte.js.map +1 -1
  115. package/build/server/manifest-full.js +1 -1
  116. package/build/server/manifest.js +1 -1
  117. package/build/server/nodes/0.js +2 -2
  118. package/build/server/nodes/11.js +1 -1
  119. package/build/server/nodes/13.js +1 -1
  120. package/build/server/nodes/14.js +1 -1
  121. package/build/server/nodes/15.js +1 -1
  122. package/build/server/nodes/16.js +1 -1
  123. package/build/server/nodes/2.js +1 -1
  124. package/build/server/nodes/20.js +1 -1
  125. package/build/server/nodes/21.js +1 -1
  126. package/build/server/nodes/25.js +1 -1
  127. package/build/server/nodes/29.js +1 -1
  128. package/build/server/nodes/30.js +1 -1
  129. package/build/server/nodes/31.js +1 -1
  130. package/build/server/nodes/32.js +1 -1
  131. package/build/server/nodes/34.js +1 -1
  132. package/build/server/nodes/35.js +1 -1
  133. package/build/server/nodes/5.js +1 -1
  134. package/build/server/nodes/6.js +1 -1
  135. package/build/server/nodes/7.js +1 -1
  136. package/build/server/nodes/9.js +1 -1
  137. package/build/server/server.js +1 -1
  138. package/package.json +9 -9
  139. package/templates/ecosystem.config.cjs +2 -0
  140. package/build/client/_app/immutable/assets/0.DOeHn583.css +0 -2
  141. package/build/client/_app/immutable/assets/0.DOeHn583.css.br +0 -0
  142. package/build/client/_app/immutable/assets/0.DOeHn583.css.gz +0 -0
  143. package/build/client/_app/immutable/chunks/2rFska3d.js +0 -1
  144. package/build/client/_app/immutable/chunks/2rFska3d.js.br +0 -1
  145. package/build/client/_app/immutable/chunks/2rFska3d.js.gz +0 -0
  146. package/build/client/_app/immutable/chunks/5M5n6ftO.js +0 -6085
  147. package/build/client/_app/immutable/chunks/5M5n6ftO.js.br +0 -0
  148. package/build/client/_app/immutable/chunks/5M5n6ftO.js.gz +0 -0
  149. package/build/client/_app/immutable/chunks/BCbumNc2.js.br +0 -0
  150. package/build/client/_app/immutable/chunks/BCbumNc2.js.gz +0 -0
  151. package/build/client/_app/immutable/chunks/BRA_lgsI.js.br +0 -0
  152. package/build/client/_app/immutable/chunks/CzHxHvr2.js.br +0 -0
  153. package/build/client/_app/immutable/chunks/CzHxHvr2.js.gz +0 -0
  154. package/build/client/_app/immutable/chunks/DUooINX6.js +0 -1
  155. package/build/client/_app/immutable/chunks/DUooINX6.js.br +0 -1
  156. package/build/client/_app/immutable/chunks/DUooINX6.js.gz +0 -0
  157. package/build/client/_app/immutable/chunks/FIoX_cjM.js.br +0 -0
  158. package/build/client/_app/immutable/chunks/FIoX_cjM.js.gz +0 -0
  159. package/build/client/_app/immutable/chunks/LbAo7oFZ.js +0 -1
  160. package/build/client/_app/immutable/chunks/LbAo7oFZ.js.br +0 -0
  161. package/build/client/_app/immutable/chunks/LbAo7oFZ.js.gz +0 -0
  162. package/build/client/_app/immutable/entry/app.BP5swwM7.js.br +0 -0
  163. package/build/client/_app/immutable/entry/app.BP5swwM7.js.gz +0 -0
  164. package/build/client/_app/immutable/entry/start.BW9gOvFV.js.br +0 -0
  165. package/build/client/_app/immutable/entry/start.BW9gOvFV.js.gz +0 -0
  166. package/build/client/_app/immutable/nodes/11.NPUXRN3p.js.br +0 -0
  167. package/build/client/_app/immutable/nodes/11.NPUXRN3p.js.gz +0 -0
  168. package/build/client/_app/immutable/nodes/13.BQ0cOim-.js.br +0 -0
  169. package/build/client/_app/immutable/nodes/13.BQ0cOim-.js.gz +0 -0
  170. package/build/client/_app/immutable/nodes/14.BsbXlPTK.js.br +0 -0
  171. package/build/client/_app/immutable/nodes/14.BsbXlPTK.js.gz +0 -0
  172. package/build/client/_app/immutable/nodes/15.C0vWxAsK.js.br +0 -0
  173. package/build/client/_app/immutable/nodes/15.C0vWxAsK.js.gz +0 -0
  174. package/build/client/_app/immutable/nodes/16.BE4OfH4C.js.br +0 -0
  175. package/build/client/_app/immutable/nodes/16.BE4OfH4C.js.gz +0 -0
  176. package/build/client/_app/immutable/nodes/2.CWOFnTAV.js.br +0 -0
  177. package/build/client/_app/immutable/nodes/2.CWOFnTAV.js.gz +0 -0
  178. package/build/client/_app/immutable/nodes/20.4vwwwrQ_.js.br +0 -0
  179. package/build/client/_app/immutable/nodes/20.4vwwwrQ_.js.gz +0 -0
  180. package/build/client/_app/immutable/nodes/21.C1xtue6U.js +0 -1
  181. package/build/client/_app/immutable/nodes/21.C1xtue6U.js.br +0 -0
  182. package/build/client/_app/immutable/nodes/21.C1xtue6U.js.gz +0 -0
  183. package/build/client/_app/immutable/nodes/25.DR2ojPn5.js.br +0 -0
  184. package/build/client/_app/immutable/nodes/25.DR2ojPn5.js.gz +0 -0
  185. package/build/client/_app/immutable/nodes/29.PsrL6xdd.js.br +0 -0
  186. package/build/client/_app/immutable/nodes/29.PsrL6xdd.js.gz +0 -0
  187. package/build/client/_app/immutable/nodes/30.Cd56Qv6o.js.br +0 -0
  188. package/build/client/_app/immutable/nodes/30.Cd56Qv6o.js.gz +0 -0
  189. package/build/client/_app/immutable/nodes/31.CFCkC-P2.js.br +0 -0
  190. package/build/client/_app/immutable/nodes/31.CFCkC-P2.js.gz +0 -0
  191. package/build/client/_app/immutable/nodes/32.DWY9hRHg.js.br +0 -0
  192. package/build/client/_app/immutable/nodes/32.DWY9hRHg.js.gz +0 -0
  193. package/build/client/_app/immutable/nodes/34.ZQaLUUXZ.js.br +0 -0
  194. package/build/client/_app/immutable/nodes/34.ZQaLUUXZ.js.gz +0 -0
  195. package/build/client/_app/immutable/nodes/35.BPmyLjFW.js.br +0 -0
  196. package/build/client/_app/immutable/nodes/35.BPmyLjFW.js.gz +0 -0
  197. package/build/client/_app/immutable/nodes/5.wbpOzblK.js.br +0 -0
  198. package/build/client/_app/immutable/nodes/5.wbpOzblK.js.gz +0 -0
  199. package/build/client/_app/immutable/nodes/6.B2HdJrZB.js.br +0 -0
  200. package/build/client/_app/immutable/nodes/6.B2HdJrZB.js.gz +0 -0
  201. package/build/client/_app/immutable/nodes/7.BuWU0YDv.js.br +0 -0
  202. package/build/client/_app/immutable/nodes/7.BuWU0YDv.js.gz +0 -0
  203. package/build/client/_app/immutable/nodes/9.Bxpo8jgd.js.br +0 -0
  204. package/build/client/_app/immutable/nodes/9.Bxpo8jgd.js.gz +0 -0
  205. package/build/server/_app/immutable/assets/_layout.DOeHn583.css +0 -2
  206. /package/build/client/_app/immutable/nodes/{0.CXQcjMDK.js → 0.BQ4J6cqX.js} +0 -0
  207. /package/build/client/_app/immutable/nodes/{0.CXQcjMDK.js.br → 0.BQ4J6cqX.js.br} +0 -0
  208. /package/build/client/_app/immutable/nodes/{0.CXQcjMDK.js.gz → 0.BQ4J6cqX.js.gz} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\n# mktemp, never a fixed name: /tmp is shared, and a file another account left at\n# a known path survives the write below and would run as the app user.\nRUNNER=$(mktemp \"\\${TMPDIR:-/tmp}/selva-update-runner.XXXXXXXX\") || {\n\techo \"[ERROR] Could not create the update runner in \\${TMPDIR:-/tmp}\"\n\texit 1\n}\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__' || { echo \"[ERROR] Could not write the update runner\"; exit 1; }\nrm -f \"$0\"\nfor _ in $(seq 1 50); do\n kill -0 \"$SELVA_RUNNER_SPAWNER\" 2>/dev/null || break\n sleep 0.1\ndone\n${runnerScript}\n__SELVA_RUNNER_EOF__\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# When the runner calls pm2 stop, pm2 lists the app's descendants and SIGKILLs\n# whatever on that list outlives its kill timeout. A runner still parented to this\n# launcher is on the list: it died mid-update and left the app stopped whenever the\n# registry answered inside the pause below. So it is orphaned before it runs a\n# line: the subshell forks it and exits, and the runner waits for that exit.\n# setsid gives it its own session; its stdio is detached from selva-compute's pipes.\nRUNNER_PID=$( (SELVA_RUNNER_SPAWNER=$BASHPID setsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 & echo $!) )\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app. Refuse a target\n// that cannot read this deployment's data.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 3. pm2 stop — stop selva-compute before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === 'selva-compute');\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] selva-compute still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] selva-compute stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete selva-compute >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] selva-compute is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete selva-compute; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 1c. Data format pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# A release with a lower data format than the installed one cannot read what\n# this deployment has already stored (dataFormat.server.ts). It would boot, fail\n# its health check and roll back: two outages for nothing. Installed by hand it\n# leaves stored Compute API keys unreadable. A release that declares no format\n# is format 1. Skipped when the registry gave no answer: the target is unknown.\nINSTALLED_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$INSTALLED_FORMAT\" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac\nif [ -n \"$LATEST\" ] && TARGET_FORMAT=$(npm view \"@selvajs/selva@$TAG\" selva.dataFormat --silent 2>/dev/null); then\n TARGET_FORMAT=$(echo \"$TARGET_FORMAT\" | tr -d '\"' | tr -d \"'\" | tr -d '[:space:]')\n case \"$TARGET_FORMAT\" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac\n if [ \"$TARGET_FORMAT\" -lt \"$INSTALLED_FORMAT\" ]; then\n echo \"[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT.\"\n echo \"[FATAL] It could not read what the installed version has stored, such as Compute API keys.\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n echo \"[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'.\"\n exit 10\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop selva-compute BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping selva-compute\"\nif ! \"$PM2\" stop selva-compute; then\n echo \"[WARN] pm2 stop failed — selva-compute may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves selva-compute unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting selva-compute with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs selva-compute\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\necho \"[STEP] Health-probing the new process on port $PORT\"\n# mktemp for the same reason as the runner itself: /tmp is shared. Without one\n# the probe still runs; only the rollback loses the body it names the cause from.\nHEALTH_BODY=$(mktemp \"\\${TMPDIR:-/tmp}/selva-health.XXXXXXXX\") || HEALTH_BODY=\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o \"\\${HEALTH_BODY:-/dev/null}\" -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n [ -n \"$HEALTH_BODY\" ] && rm -f \"$HEALTH_BODY\"\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -s \"$HEALTH_BODY\" ]; then\n BODY=$(cat \"$HEALTH_BODY\")\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs selva-compute\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f \"$HEALTH_BODY\"\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\n# The failed version has already booted, so it may have rewritten stored data in\n# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.\nAFTER_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$AFTER_FORMAT\" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac\nif [ \"$AFTER_FORMAT\" -gt \"$INSTALLED_FORMAT\" ]; then\n echo \"[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT.\"\n echo \"[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute.\"\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop selva-compute >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs selva-compute\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,aAAa,KAAK,KAAK,gBAAgB,YAAY,SAAS,cAAc,GAAG,MAAM,CACpF;EACA,OAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,KAAA;CACxD,QAAQ;EACP;CACD;AACD;AAKA,SAAgB,WAAW,GAAmB;CAC7C,OAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,EAAE;AACrC;AAoBA,SAAgB,cACf,cACA,SACA,UAAoB,CAAC,GACZ;CACT,MAAM,SAAS,QAAQ,KAAK,SAAS,QAAQ,WAAW,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAG1E,OAAO;UACE,WAAW,OAAO,EAAE;;;;;;;;;;;;;;;;EAgB5B,aAAa;;;;;EAKb,OAAO;;;;;;;;;;;;;;;;;AAiBT;AAyBA,SAAgB,qBACf,SACA,eACA,eACA,KACS;CACT,MAAM,aAAa,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG;CAY/D,OAAO;;SATQ,WAAW,iBAAiB,EAWnC,EAAO;YAVG,WAAW,aAWlB,EAAU;MALL,WAAW,GAMtB,EAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CAAC;EACF,SAAS,KAAK;GACb,UAAU,OAAO,EAAE,MAAM,oCAAoC,MAAM,CAAC;GACpE,UAAU,QAAQ,EAAE,MAAM,GAAG,CAAC;GAC9B,WAAW,MAAM;EAClB;CACD,EACD,CAAC;CAED,OAAO,IAAI,SAAS,QAAQ,EAC3B,SAAS;EACR,gBAAgB;EAChB,iBAAiB;EACjB,YAAY;CACb,EACD,CAAC;AACF;AAgBA,IAAa,MAAsB,OAAO,EAAE,QAAQ,KAAK,YAAY;CACpE,kBAAkB,QAAQ,gBAAgB;CAE1C,IAAI,IAAI,aAAa,IAAI,OAAO,MAAM,MACrC,OAAO,KAAK,MAAM,eAAe,OAAO,YAAY,CAAC,GAAG,EACvD,SAAS,EAAE,iBAAiB,WAAW,EACxC,CAAC;CAGF,IAAI,OAAO;CACX,IAAI;EACH,OAAOC,eAAa,cAAc,kBAAkB,GAAG,CAAC,GAAG,MAAM;CAClE,QAAQ,CAGR;CACA,OAAO,IAAI,SAAS,MAAM,EACzB,SAAS;EACR,gBAAgB;EAChB,iBAAiB;CAClB,EACD,CAAC;AACF"}
1
+ {"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\n# mktemp, never a fixed name: /tmp is shared, and a file another account left at\n# a known path survives the write below and would run as the app user.\nRUNNER=$(mktemp \"\\${TMPDIR:-/tmp}/selva-update-runner.XXXXXXXX\") || {\n\techo \"[ERROR] Could not create the update runner in \\${TMPDIR:-/tmp}\"\n\texit 1\n}\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__' || { echo \"[ERROR] Could not write the update runner\"; exit 1; }\nrm -f \"$0\"\nfor _ in $(seq 1 50); do\n kill -0 \"$SELVA_RUNNER_SPAWNER\" 2>/dev/null || break\n sleep 0.1\ndone\n${runnerScript}\n__SELVA_RUNNER_EOF__\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# When the runner calls pm2 stop, pm2 lists the app's descendants and SIGKILLs\n# whatever on that list outlives its kill timeout. A runner still parented to this\n# launcher is on the list: it died mid-update and left the app stopped whenever the\n# registry answered inside the pause below. So it is orphaned before it runs a\n# line: the subshell forks it and exits, and the runner waits for that exit.\n# setsid gives it its own session; its stdio is detached from selva-compute's pipes.\nRUNNER_PID=$( (SELVA_RUNNER_SPAWNER=$BASHPID setsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 & echo $!) )\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app. Refuse a target\n// that cannot read this deployment's data.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 2b. ownership — refuse when pm2's app of this name belongs to another\n// install: the stop would take THAT one down.\n// 3. pm2 stop — stop the app before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 3b. gone? — refuse when the old process still answers the port:\n// this pm2 does not run it, so it cannot replace it.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# pm2 finds an app by name alone, and the name is whatever this install's\n# ecosystem file declares. Two installs under one pm2 daemon need different ones.\nAPP=$(node -p \"require(process.argv[1]).apps[0].name\" \"$ECOSYSTEM\" 2>/dev/null)\ncase \"$APP\" in ''|undefined|null) APP=selva-compute ;; esac\nHERE=$(cd \"$(dirname \"$ECOSYSTEM\")\" 2>/dev/null && pwd -P)\n\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\n# Prints one string field of the /api/health body on stdin.\njson_field() {\n grep -o '\"'\"$1\"'\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4\n}\n\n# Prints the instanceId of whatever answers this install's port, or nothing while\n# the port is silent.\nserving_instance() {\n curl -sS --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null | json_field instanceId\n}\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | SELVA_APP=\"$APP\" node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === process.env.SELVA_APP);\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\n# Prints the directory pm2 runs this app from, or nothing when pm2 has no app of\n# that name.\napp_dir() {\n \"$PM2\" jlist 2>/dev/null | SELVA_APP=\"$APP\" node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === process.env.SELVA_APP);\n process.stdout.write((app && app.pm2_env.pm_cwd) || '');\n } catch {}\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] $APP still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] $APP stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete \"$APP\" >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] $APP is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete $APP; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 1c. Data format pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# A release with a lower data format than the installed one cannot read what\n# this deployment has already stored (dataFormat.server.ts). It would boot, fail\n# its health check and roll back: two outages for nothing. Installed by hand it\n# leaves stored Compute API keys unreadable. A release that declares no format\n# is format 1. Skipped when the registry gave no answer: the target is unknown.\nINSTALLED_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$INSTALLED_FORMAT\" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac\nif [ -n \"$LATEST\" ] && TARGET_FORMAT=$(npm view \"@selvajs/selva@$TAG\" selva.dataFormat --silent 2>/dev/null); then\n TARGET_FORMAT=$(echo \"$TARGET_FORMAT\" | tr -d '\"' | tr -d \"'\" | tr -d '[:space:]')\n case \"$TARGET_FORMAT\" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac\n if [ \"$TARGET_FORMAT\" -lt \"$INSTALLED_FORMAT\" ]; then\n echo \"[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT.\"\n echo \"[FATAL] It could not read what the installed version has stored, such as Compute API keys.\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n echo \"[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'.\"\n exit 10\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 2b. This install must own the pm2 app it is about to stop.\n# ---------------------------------------------------------------------------\n# With two installs under one daemon and one name, the stop below takes the\n# OTHER install down while this one keeps serving, and npm then rewrites build/\n# under it.\nOWNER=$(app_dir)\nOWNER_REAL=\nif [ -n \"$OWNER\" ]; then\n OWNER_REAL=$(cd \"$OWNER\" 2>/dev/null && pwd -P)\nfi\nif [ -n \"$OWNER\" ] && [ -n \"$HERE\" ] && [ \"\\${OWNER_REAL:-$OWNER}\" != \"$HERE\" ]; then\n echo \"[FATAL] PM2_NAME_TAKEN: pm2's '$APP' runs from $OWNER, not from this install ($HERE).\"\n echo \"[FATAL] Two installs share one pm2 app name, so this update would have stopped the other one.\"\n echo \"[FATAL] Give this install its own name: change 'name' in $ECOSYSTEM, then from a shell:\"\n echo \"[FATAL] cd $HERE && npx selva start\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 11\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop the app BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping $APP\"\nif ! \"$PM2\" stop \"$APP\"; then\n echo \"[WARN] pm2 stop failed — $APP may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 3b. Nothing may answer the port once the app is stopped.\n# ---------------------------------------------------------------------------\n# A process this pm2 does not run (another pm2 daemon, a systemd unit, a shell)\n# survives the stop above, and so does one that outlived its kill timeout. Either\n# would keep rendering pages that name the old build's files after npm has\n# replaced them, and would answer the health probe below, so the update would\n# report success with nothing restarted.\nSURVIVOR=\nfor i in $(seq 1 5); do\n SURVIVOR=$(serving_instance)\n if [ -z \"$SURVIVOR\" ]; then\n break\n fi\n sleep 1\ndone\nif [ -n \"$SURVIVOR\" ]; then\n echo \"[FATAL] NOT_STOPPED: something still answers on port $PORT after 'pm2 stop $APP'.\"\n echo \"[FATAL] Either this install's pm2 does not run that process, or it did not exit.\"\n echo \"[FATAL] Nothing was installed. Find what holds the port, stop it there, then start the app from this install:\"\n echo \"[FATAL] ss -ltnp | grep ':$PORT '\"\n echo \"[FATAL] cd $HERE && npx selva start\"\n exit 12\nfi\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves $APP unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting $APP with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs $APP\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\necho \"[STEP] Health-probing the new process on port $PORT\"\n# mktemp for the same reason as the runner itself: /tmp is shared. Without one\n# the probe still runs; only the rollback loses the body it names the cause from.\nHEALTH_BODY=$(mktemp \"\\${TMPDIR:-/tmp}/selva-health.XXXXXXXX\") || HEALTH_BODY=\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o \"\\${HEALTH_BODY:-/dev/null}\" -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n [ -n \"$HEALTH_BODY\" ] && rm -f \"$HEALTH_BODY\"\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -s \"$HEALTH_BODY\" ]; then\n BODY=$(cat \"$HEALTH_BODY\")\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs $APP\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f \"$HEALTH_BODY\"\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\n# The failed version has already booted, so it may have rewritten stored data in\n# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.\nAFTER_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$AFTER_FORMAT\" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac\nif [ \"$AFTER_FORMAT\" -gt \"$INSTALLED_FORMAT\" ]; then\n echo \"[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT.\"\n echo \"[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute.\"\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop \"$APP\" >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs $APP\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,aAAa,KAAK,KAAK,gBAAgB,YAAY,SAAS,cAAc,GAAG,MAAM,CACpF;EACA,OAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,KAAA;CACxD,QAAQ;EACP;CACD;AACD;AAKA,SAAgB,WAAW,GAAmB;CAC7C,OAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,EAAE;AACrC;AAoBA,SAAgB,cACf,cACA,SACA,UAAoB,CAAC,GACZ;CACT,MAAM,SAAS,QAAQ,KAAK,SAAS,QAAQ,WAAW,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAG1E,OAAO;UACE,WAAW,OAAO,EAAE;;;;;;;;;;;;;;;;EAgB5B,aAAa;;;;;EAKb,OAAO;;;;;;;;;;;;;;;;;AAiBT;AA6BA,SAAgB,qBACf,SACA,eACA,eACA,KACS;CACT,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zB,MAAM,QAAQ,UAAU,IAAI,CAAC,CAAC,KAAK;KACnC,IAAI,OACH,UAAU,OAAO,EAAE,MAAM,WAAW,QAAQ,CAAC;IAE/C;GACD,CAAC;GAGD,MAAM,GAAG,UAAU,SAAS;IAC3B,aAAa,OAAO;IACpB,UAAU,QAAQ,EAAE,MAAM,QAAQ,GAAG,CAAC;IACtC,WAAW,MAAM;GAClB,CAAC;GAGD,MAAM,GAAG,UAAU,QAAQ;IAC1B,aAAa,OAAO;IACpB,UAAU,OAAO,EAAE,MAAM,WAAW,IAAI,UAAU,CAAC;IACnD,UAAU,QAAQ,EAAE,MAAM,GAAG,CAAC;IAC9B,WAAW,MAAM;GAClB,CAAC;EACF,SAAS,KAAK;GACb,UAAU,OAAO,EAAE,MAAM,oCAAoC,MAAM,CAAC;GACpE,UAAU,QAAQ,EAAE,MAAM,GAAG,CAAC;GAC9B,WAAW,MAAM;EAClB;CACD,EACD,CAAC;CAED,OAAO,IAAI,SAAS,QAAQ,EAC3B,SAAS;EACR,gBAAgB;EAChB,iBAAiB;EACjB,YAAY;CACb,EACD,CAAC;AACF;AAgBA,IAAa,MAAsB,OAAO,EAAE,QAAQ,KAAK,YAAY;CACpE,kBAAkB,QAAQ,gBAAgB;CAE1C,IAAI,IAAI,aAAa,IAAI,OAAO,MAAM,MACrC,OAAO,KAAK,MAAM,eAAe,OAAO,YAAY,CAAC,GAAG,EACvD,SAAS,EAAE,iBAAiB,WAAW,EACxC,CAAC;CAGF,IAAI,OAAO;CACX,IAAI;EACH,OAAOC,eAAa,cAAc,kBAAkB,GAAG,CAAC,GAAG,MAAM;CAClE,QAAQ,CAGR;CACA,OAAO,IAAI,SAAS,MAAM,EACzB,SAAS;EACR,gBAAgB;EAChB,iBAAiB;CAClB,EACD,CAAC;AACF"}
@@ -7,22 +7,32 @@ import { l as requireMaxBodySize } from "../../../../../chunks/admin-auth.server
7
7
  import { n as tryResolveShareToken } from "../../../../../chunks/resolve.server.js";
8
8
  import { n as runSolve, t as mapSolveError } from "../../../../../chunks/solve.server.js";
9
9
  // src/routes/api/v1/compute/+server.ts
10
- var POST = (event) => {
11
- if (!wantsKeepalive(event.request)) return solve(event);
12
- return respondWithKeepalive(solve(event).catch((err) => errorResponse(err, event.locals.log)));
10
+ var POST = async (event) => {
11
+ const received = await receive(event);
12
+ if (!wantsKeepalive(event.request)) return solve(event, received);
13
+ return respondWithKeepalive(solve(event, received).catch((err) => errorResponse(err, event.locals.log)));
13
14
  };
14
- async function solve({ request, locals, url }) {
15
+ async function receive({ request, locals }) {
15
16
  requireMaxBodySize(request, computeRequestCap());
16
17
  const loadStart = performance.now();
17
- const prepMarks = [];
18
+ try {
19
+ return {
20
+ body: await request.json(),
21
+ loadStart,
22
+ bodyMs: performance.now() - loadStart
23
+ };
24
+ } catch (err) {
25
+ mapSolveError(err, locals);
26
+ }
27
+ }
28
+ async function solve({ request, locals, url }, { body, loadStart, bodyMs }) {
29
+ const prepMarks = [["body", bodyMs]];
18
30
  let prevMark = performance.now();
19
31
  const mark = (label) => {
20
32
  prepMarks.push([label, performance.now() - prevMark]);
21
33
  prevMark = performance.now();
22
34
  };
23
35
  try {
24
- const body = await request.json();
25
- mark("body");
26
36
  const { inputs, values } = body;
27
37
  const definitionUrl = body.definitionUrl;
28
38
  const channel = body.channel ?? "live";
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/compute/+server.ts"],"sourcesContent":["import type { RequestEvent, RequestHandler } from './$types';\nimport { apiError, ApiErrorCode, errorResponse } from '#lib/server/api-errors.js';\nimport { computeRequestCap } from '#lib/server/compute/engine.server.js';\nimport { requireMaxBodySize } from '#lib/server/admin-auth.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { runSolve, mapSolveError, type SolveAccess } from '#lib/server/compute/solve.server.js';\nimport { SolveModeSchema } from '@selvajs/server/api';\nimport { respondWithKeepalive, wantsKeepalive } from '@selvajs/solve/server';\n\ninterface ComputeRequest {\n\t/** Read for a remote `definitionUrl` only: a stored definition's inputs come from its schema. */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tdefinitionUrl: string;\n\t/** Spec §6 channel selector. Defaults to 'live'. 'draft' requires editor. */\n\tchannel?: 'live' | 'draft';\n\t/**\n\t * Explicit version pick (versioning tab \"Run\"). Solves this exact version\n\t * instead of the channel pointer; editor-only, never share-token accessible.\n\t */\n\tversionId?: string;\n\t/** The caller's open live-event stream; see `SolveParams.streamId`. */\n\tstreamId?: string;\n\t/** See `SolveBodySchema.mode`. */\n\tmode?: string;\n}\n\n// The URL-addressed solve: takes an arbitrary `definitionUrl`, and is the only\n// route that accepts a share token. The solve mechanics it shares with\n// `/api/v1/definitions/{guid}/solve` live in `solve.server.ts`; what stays here\n// is the body shape and the share-token branch, which must NOT reach the\n// definition-addressed route.\n//\n// The web app asks for keep-alive, so a solve longer than the reverse proxy's read timeout\n// still lands. Errors then travel inside the 200, which is why they become responses here.\n\nexport const POST: RequestHandler = (event) => {\n\tif (!wantsKeepalive(event.request)) return solve(event);\n\treturn respondWithKeepalive(solve(event).catch((err) => errorResponse(err, event.locals.log)));\n};\n\nasync function solve({ request, locals, url }: RequestEvent): Promise<Response> {\n\t// Reject oversized payloads before buffering.\n\trequireMaxBodySize(request, computeRequestCap());\n\n\t// DEBUG (SELVA_FLAG_COMPUTE_DEBUG): start of server-side work. The solve metric's\n\t// `durationMs` wraps ONLY scheduler.solve, so everything before it (auth, DB reads,\n\t// definition fetch, input tree build) and the response serialization after it are\n\t// otherwise invisible. `runSolve` continues these marks and logs the breakdown.\n\tconst loadStart = performance.now();\n\tconst prepMarks: [string, number][] = [];\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\ttry {\n\t\tconst body: ComputeRequest = await request.json();\n\t\tmark('body');\n\n\t\tconst { inputs, values } = body;\n\t\tconst definitionUrl = body.definitionUrl;\n\t\tconst channel: 'live' | 'draft' = body.channel ?? 'live';\n\t\tconst explicitVersionId = body.versionId ?? null;\n\n\t\tif (!values || !definitionUrl) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t'Missing required fields: values or definitionUrl'\n\t\t\t);\n\t\t}\n\t\tconst mode = SolveModeSchema.default('full').safeParse(body.mode);\n\t\tif (!mode.success) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid mode: ${String(body.mode)}. Must be 'preview' or 'full'.`\n\t\t\t);\n\t\t}\n\t\tif (channel !== 'live' && channel !== 'draft') {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid channel: ${channel}. Must be 'live' or 'draft'.`\n\t\t\t);\n\t\t}\n\n\t\t// Share-link tokens (spec §7); null for remote definitions or no token.\n\t\tconst isLocal = definitionUrl.startsWith('local:');\n\t\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\t\t// Explicit-version solves are editor-only, so don't resolve a share token\n\t\t// for them — force the logged-in editor gate instead.\n\t\tconst sharedAccess =\n\t\t\tisLocal && guid && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, channel, { requireSolve: true })\n\t\t\t\t: null;\n\t\tmark('shareToken');\n\n\t\tif (!sharedAccess && (!locals.ctx || !locals.user)) {\n\t\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t\t}\n\n\t\t// Rate-limit bucket per caller: `share:{linkId}` for token solves so an\n\t\t// anonymous crowd on one public link can't drain the owner's budget.\n\t\tconst access: SolveAccess = sharedAccess\n\t\t\t? {\n\t\t\t\t\tkind: 'share',\n\t\t\t\t\tctx: sharedAccess.ctx,\n\t\t\t\t\tlink: sharedAccess.link,\n\t\t\t\t\trateLimitKey: `share:${sharedAccess.link.id}`\n\t\t\t\t}\n\t\t\t: { kind: 'user', ctx: locals.ctx!, rateLimitKey: `user:${locals.user!.id}` };\n\n\t\treturn await runSolve({\n\t\t\taccess,\n\t\t\tdefinitionUrl,\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tchannel,\n\t\t\tversionId: explicitVersionId,\n\t\t\trequest,\n\t\t\tlocals,\n\t\t\tloadStart,\n\t\t\tprepMarks,\n\t\t\tstreamId: typeof body.streamId === 'string' ? body.streamId : null,\n\t\t\tsolveMode: mode.data\n\t\t});\n\t} catch (err) {\n\t\tmapSolveError(err, locals);\n\t}\n}\n"],"mappings":";;;;;;;;;AAoCA,IAAa,QAAwB,UAAU;CAC9C,IAAI,CAAC,eAAe,MAAM,OAAO,GAAG,OAAO,MAAM,KAAK;CACtD,OAAO,qBAAqB,MAAM,KAAK,CAAC,CAAC,OAAO,QAAQ,cAAc,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC;AAC9F;AAEA,eAAe,MAAM,EAAE,SAAS,QAAQ,OAAwC;CAE/E,mBAAmB,SAAS,kBAAkB,CAAC;CAM/C,MAAM,YAAY,YAAY,IAAI;CAClC,MAAM,YAAgC,CAAC;CACvC,IAAI,WAAW,YAAY,IAAI;CAC/B,MAAM,QAAQ,UAAkB;EAC/B,UAAU,KAAK,CAAC,OAAO,YAAY,IAAI,IAAI,QAAQ,CAAC;EACpD,WAAW,YAAY,IAAI;CAC5B;CAEA,IAAI;EACH,MAAM,OAAuB,MAAM,QAAQ,KAAK;EAChD,KAAK,MAAM;EAEX,MAAM,EAAE,QAAQ,WAAW;EAC3B,MAAM,gBAAgB,KAAK;EAC3B,MAAM,UAA4B,KAAK,WAAW;EAClD,MAAM,oBAAoB,KAAK,aAAa;EAE5C,IAAI,CAAC,UAAU,CAAC,eACf,SACC,KACA,aAAa,mBACb,kDACD;EAED,MAAM,OAAO,gBAAgB,QAAQ,MAAM,CAAC,CAAC,UAAU,KAAK,IAAI;EAChE,IAAI,CAAC,KAAK,SACT,SACC,KACA,aAAa,mBACb,iBAAiB,OAAO,KAAK,IAAI,EAAE,+BACpC;EAED,IAAI,YAAY,UAAU,YAAY,SACrC,SACC,KACA,aAAa,mBACb,oBAAoB,QAAQ,6BAC7B;EAID,MAAM,UAAU,cAAc,WAAW,QAAQ;EACjD,MAAM,OAAO,UAAU,cAAc,UAAU,CAAC,IAAI;EAGpD,MAAM,eACL,WAAW,QAAQ,CAAC,oBACjB,MAAM,qBAAqB,SAAS,KAAK,MAAM,SAAS,EAAE,cAAc,KAAK,CAAC,IAC9E;EACJ,KAAK,YAAY;EAEjB,IAAI,CAAC,iBAAiB,CAAC,OAAO,OAAO,CAAC,OAAO,OAC5C,SAAS,KAAK,aAAa,cAAc,cAAc;EAKxD,MAAM,SAAsB,eACzB;GACA,MAAM;GACN,KAAK,aAAa;GAClB,MAAM,aAAa;GACnB,cAAc,SAAS,aAAa,KAAK;EAC1C,IACC;GAAE,MAAM;GAAQ,KAAK,OAAO;GAAM,cAAc,QAAQ,OAAO,KAAM;EAAK;EAE7E,OAAO,MAAM,SAAS;GACrB;GACA;GACA;GACA;GACA;GACA,WAAW;GACX;GACA;GACA;GACA;GACA,UAAU,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;GAC9D,WAAW,KAAK;EACjB,CAAC;CACF,SAAS,KAAK;EACb,cAAc,KAAK,MAAM;CAC1B;AACD"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/compute/+server.ts"],"sourcesContent":["import type { RequestEvent, RequestHandler } from './$types';\nimport { apiError, ApiErrorCode, errorResponse } from '#lib/server/api-errors.js';\nimport { computeRequestCap } from '#lib/server/compute/engine.server.js';\nimport { requireMaxBodySize } from '#lib/server/admin-auth.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { runSolve, mapSolveError, type SolveAccess } from '#lib/server/compute/solve.server.js';\nimport { SolveModeSchema } from '@selvajs/server/api';\nimport { respondWithKeepalive, wantsKeepalive } from '@selvajs/solve/server';\n\ninterface ComputeRequest {\n\t/** Read for a remote `definitionUrl` only: a stored definition's inputs come from its schema. */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tdefinitionUrl: string;\n\t/** Spec §6 channel selector. Defaults to 'live'. 'draft' requires editor. */\n\tchannel?: 'live' | 'draft';\n\t/**\n\t * Explicit version pick (versioning tab \"Run\"). Solves this exact version\n\t * instead of the channel pointer; editor-only, never share-token accessible.\n\t */\n\tversionId?: string;\n\t/** The caller's open live-event stream; see `SolveParams.streamId`. */\n\tstreamId?: string;\n\t/** See `SolveBodySchema.mode`. */\n\tmode?: string;\n}\n\n// The URL-addressed solve: takes an arbitrary `definitionUrl`, and is the only\n// route that accepts a share token. The solve mechanics it shares with\n// `/api/v1/definitions/{guid}/solve` live in `solve.server.ts`; what stays here\n// is the body shape and the share-token branch, which must NOT reach the\n// definition-addressed route.\n//\n// The web app asks for keep-alive, so a solve longer than the reverse proxy's read timeout\n// still lands. Errors then travel inside the 200, which is why they become responses here.\n// The body is read before the 200 goes out, as `respondWithKeepalive` requires.\n\nexport const POST: RequestHandler = async (event) => {\n\tconst received = await receive(event);\n\tif (!wantsKeepalive(event.request)) return solve(event, received);\n\treturn respondWithKeepalive(\n\t\tsolve(event, received).catch((err) => errorResponse(err, event.locals.log))\n\t);\n};\n\ninterface Received {\n\tbody: ComputeRequest;\n\t/** `performance.now()` when the body read began. */\n\tloadStart: number;\n\tbodyMs: number;\n}\n\nasync function receive({ request, locals }: RequestEvent): Promise<Received> {\n\t// Reject oversized payloads before buffering.\n\trequireMaxBodySize(request, computeRequestCap());\n\n\tconst loadStart = performance.now();\n\ttry {\n\t\tconst body: ComputeRequest = await request.json();\n\t\treturn { body, loadStart, bodyMs: performance.now() - loadStart };\n\t} catch (err) {\n\t\tmapSolveError(err, locals);\n\t}\n}\n\nasync function solve(\n\t{ request, locals, url }: RequestEvent,\n\t{ body, loadStart, bodyMs }: Received\n): Promise<Response> {\n\t// DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the solve metric's `durationMs` wraps ONLY\n\t// scheduler.solve, so everything before it (body read, auth, DB reads, definition fetch,\n\t// input tree build) and the response serialization after it are otherwise invisible.\n\t// `runSolve` continues these marks and logs the breakdown.\n\tconst prepMarks: [string, number][] = [['body', bodyMs]];\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\ttry {\n\t\tconst { inputs, values } = body;\n\t\tconst definitionUrl = body.definitionUrl;\n\t\tconst channel: 'live' | 'draft' = body.channel ?? 'live';\n\t\tconst explicitVersionId = body.versionId ?? null;\n\n\t\tif (!values || !definitionUrl) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t'Missing required fields: values or definitionUrl'\n\t\t\t);\n\t\t}\n\t\tconst mode = SolveModeSchema.default('full').safeParse(body.mode);\n\t\tif (!mode.success) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid mode: ${String(body.mode)}. Must be 'preview' or 'full'.`\n\t\t\t);\n\t\t}\n\t\tif (channel !== 'live' && channel !== 'draft') {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid channel: ${channel}. Must be 'live' or 'draft'.`\n\t\t\t);\n\t\t}\n\n\t\t// Share-link tokens (spec §7); null for remote definitions or no token.\n\t\tconst isLocal = definitionUrl.startsWith('local:');\n\t\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\t\t// Explicit-version solves are editor-only, so don't resolve a share token\n\t\t// for them — force the logged-in editor gate instead.\n\t\tconst sharedAccess =\n\t\t\tisLocal && guid && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, channel, { requireSolve: true })\n\t\t\t\t: null;\n\t\tmark('shareToken');\n\n\t\tif (!sharedAccess && (!locals.ctx || !locals.user)) {\n\t\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t\t}\n\n\t\t// Rate-limit bucket per caller: `share:{linkId}` for token solves so an\n\t\t// anonymous crowd on one public link can't drain the owner's budget.\n\t\tconst access: SolveAccess = sharedAccess\n\t\t\t? {\n\t\t\t\t\tkind: 'share',\n\t\t\t\t\tctx: sharedAccess.ctx,\n\t\t\t\t\tlink: sharedAccess.link,\n\t\t\t\t\trateLimitKey: `share:${sharedAccess.link.id}`\n\t\t\t\t}\n\t\t\t: { kind: 'user', ctx: locals.ctx!, rateLimitKey: `user:${locals.user!.id}` };\n\n\t\treturn await runSolve({\n\t\t\taccess,\n\t\t\tdefinitionUrl,\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tchannel,\n\t\t\tversionId: explicitVersionId,\n\t\t\trequest,\n\t\t\tlocals,\n\t\t\tloadStart,\n\t\t\tprepMarks,\n\t\t\tstreamId: typeof body.streamId === 'string' ? body.streamId : null,\n\t\t\tsolveMode: mode.data\n\t\t});\n\t} catch (err) {\n\t\tmapSolveError(err, locals);\n\t}\n}\n"],"mappings":";;;;;;;;;AAqCA,IAAa,OAAuB,OAAO,UAAU;CACpD,MAAM,WAAW,MAAM,QAAQ,KAAK;CACpC,IAAI,CAAC,eAAe,MAAM,OAAO,GAAG,OAAO,MAAM,OAAO,QAAQ;CAChE,OAAO,qBACN,MAAM,OAAO,QAAQ,CAAC,CAAC,OAAO,QAAQ,cAAc,KAAK,MAAM,OAAO,GAAG,CAAC,CAC3E;AACD;AASA,eAAe,QAAQ,EAAE,SAAS,UAA2C;CAE5E,mBAAmB,SAAS,kBAAkB,CAAC;CAE/C,MAAM,YAAY,YAAY,IAAI;CAClC,IAAI;EAEH,OAAO;GAAE,MAAA,MAD0B,QAAQ,KAAK;GACjC;GAAW,QAAQ,YAAY,IAAI,IAAI;EAAU;CACjE,SAAS,KAAK;EACb,cAAc,KAAK,MA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AM,SAAS;GACrB;GACA;GACA;GACA;GACA;GACA,WAAW;GACX;GACA;GACA;GACA;GACA,UAAU,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;GAC9D,WAAW,KAAK;EACjB,CAAC;CACF,SAAS,KAAK;EACb,cAAc,KAAK,MAAM;CAC1B;AACD"}
@@ -176,25 +176,29 @@ function createDefinitionLoader(deps) {
176
176
  const fresh = cachedSchemaFor(version);
177
177
  if (options?.skipComputeDefaults && fresh) return {
178
178
  ...loaded,
179
- schema: fresh
179
+ schema: fresh,
180
+ defaultsPending: false
180
181
  };
181
182
  const values = savedValues.get(version.id);
182
183
  if (fresh && values) return {
183
184
  ...loaded,
184
- schema: applySavedValues(fresh, values)
185
+ schema: applySavedValues(fresh, values),
186
+ defaultsPending: false
185
187
  };
186
188
  const stored = fresh ?? servableStaleSchema(version);
187
189
  if (stored) {
188
190
  readInBackground(job);
189
191
  return {
190
192
  ...loaded,
191
- schema: values ? applySavedValues(stored, values) : stored
193
+ schema: values ? applySavedValues(stored, values) : stored,
194
+ defaultsPending: !values
192
195
  };
193
196
  }
194
197
  const schema = await withTimeout(read(job), renderWaitMs, () => new DefinitionLoadError("connect", "Rhino.Compute is still reading this definition. Retry in a moment."));
195
198
  return {
196
199
  ...loaded,
197
- schema
200
+ schema,
201
+ defaultsPending: false
198
202
  };
199
203
  };
200
204
  }
@@ -247,19 +251,27 @@ function sameDefaults(a, b) {
247
251
  function messageOf(err) {
248
252
  return err instanceof Error ? err.message : String(err);
249
253
  }
254
+ // src/lib/saved-values.ts
255
+ /** What the definition page's load `depends` on, and the page invalidates to repeat it. */
256
+ var SAVED_VALUES_DEPENDENCY = "selva:saved-values";
250
257
  // src/lib/server/definitions/loadForRender.server.ts
251
- async function loadDefinitionForRender(ctx, record, channel, explicitVersionId) {
252
- return createDefinitionLoader({
253
- storage: getStorageProvider(),
254
- definitions: getDefinitionMeta(),
255
- projects: getProjectProvider(),
256
- resolveServer: (ctx, orgId, opts) => serverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),
257
- getClient,
258
- computeDebug: COMPUTE_DEBUG
259
- })(ctx, record, channel, explicitVersionId);
258
+ var load$1 = createDefinitionLoader({
259
+ storage: { get: (key) => getStorageProvider().get(key) },
260
+ definitions: {
261
+ getVersion: (ctx, versionId) => getDefinitionMeta().getVersion(ctx, versionId),
262
+ setVersionSchema: (ctx, versionId, schema) => getDefinitionMeta().setVersionSchema(ctx, versionId, schema)
263
+ },
264
+ projects: { getProject: (ctx, projectId) => getProjectProvider().getProject(ctx, projectId) },
265
+ resolveServer: (ctx, orgId, opts) => serverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),
266
+ getClient,
267
+ computeDebug: COMPUTE_DEBUG
268
+ });
269
+ function loadDefinitionForRender(ctx, record, channel, explicitVersionId) {
270
+ return load$1(ctx, record, channel, explicitVersionId);
260
271
  }
261
272
  // src/routes/library/[guid]/+page.server.ts
262
- var load = (async ({ params, locals, request, url }) => {
273
+ var load = (async ({ params, locals, request, url, depends }) => {
274
+ depends(SAVED_VALUES_DEPENDENCY);
263
275
  const meta = getDefinitionMeta();
264
276
  const guid = params.guid;
265
277
  const channel = url.searchParams.get("channel") === "draft" ? "draft" : "live";
@@ -282,6 +294,7 @@ var load = (async ({ params, locals, request, url }) => {
282
294
  const solveDeadlineMs = await solveDeadlineFor(loaded.computeServer);
283
295
  return {
284
296
  schema: loaded.schema,
297
+ defaultsPending: loaded.defaultsPending,
285
298
  ghDefinition: clientDefUrl,
286
299
  currentDefinition: guid,
287
300
  serverLabel: loaded.computeServer.label,