@selvajs/selva 4.20.1-beta.4 → 4.21.0-beta.10
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.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css +2 -0
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css.br +0 -0
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css.gz +0 -0
- package/build/client/_app/immutable/chunks/{CzfnuBzq.js → BAhtiTKe.js} +1 -1
- package/build/client/_app/immutable/chunks/BAhtiTKe.js.br +0 -0
- package/build/client/_app/immutable/chunks/BAhtiTKe.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{qi43d-TM.js → CKbHmAlc.js} +1 -1
- package/build/client/_app/immutable/chunks/CKbHmAlc.js.br +0 -0
- package/build/client/_app/immutable/chunks/CKbHmAlc.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{C6Y_BUwr.js → CmlXAF26.js} +1 -1
- package/build/client/_app/immutable/chunks/CmlXAF26.js.br +0 -0
- package/build/client/_app/immutable/chunks/CmlXAF26.js.gz +0 -0
- package/build/client/_app/immutable/chunks/Cv7GBWJh.js +2 -0
- package/build/client/_app/immutable/chunks/Cv7GBWJh.js.br +0 -0
- package/build/client/_app/immutable/chunks/Cv7GBWJh.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{BDYCH-_Q.js → D5j4-ZO1.js} +1 -1
- package/build/client/_app/immutable/chunks/D5j4-ZO1.js.br +0 -0
- package/build/client/_app/immutable/chunks/D5j4-ZO1.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DW5EJMC7.js +1 -0
- package/build/client/_app/immutable/chunks/DW5EJMC7.js.br +0 -0
- package/build/client/_app/immutable/chunks/DW5EJMC7.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{D-uUm_OB.js → DptnDNFA.js} +61 -56
- package/build/client/_app/immutable/chunks/DptnDNFA.js.br +0 -0
- package/build/client/_app/immutable/chunks/{D-uUm_OB.js.gz → DptnDNFA.js.gz} +0 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js +1 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js.br +1 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{DzxE3j6C.js → qXnHMKD9.js} +1 -1
- package/build/client/_app/immutable/chunks/qXnHMKD9.js.br +0 -0
- package/build/client/_app/immutable/chunks/qXnHMKD9.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.BpT6WkO1.js → app.DPbjEDd3.js} +2 -2
- package/build/client/_app/immutable/entry/app.DPbjEDd3.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DPbjEDd3.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{1.D3kiiIk_.js → 1.DWd6YbcT.js} +1 -1
- package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.br +0 -0
- package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15._hpTnSzc.js +36 -0
- package/build/client/_app/immutable/nodes/15._hpTnSzc.js.br +0 -0
- package/build/client/_app/immutable/nodes/15._hpTnSzc.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{2.CUNbzjI_.js → 2.CS32Eh9m.js} +1 -1
- package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{20.9OIre0ah.js → 20.CVaxGEhZ.js} +1 -1
- package/build/client/_app/immutable/nodes/20.CVaxGEhZ.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.CVaxGEhZ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js +1 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js +3 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{25.DW1_vMxq.js → 25.DiYmTwXC.js} +2 -2
- package/build/client/_app/immutable/nodes/25.DiYmTwXC.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.DiYmTwXC.js.gz +0 -0
- package/build/client/_app/immutable/nodes/26.7nAJpm5P.js +5 -0
- package/build/client/_app/immutable/nodes/26.7nAJpm5P.js.br +0 -0
- package/build/client/_app/immutable/nodes/26.7nAJpm5P.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{3.3Z4QUsQQ.js → 3.Ctd9OGCk.js} +1 -1
- package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.br +0 -0
- package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{5.DmA9lTA-.js → 5.Wh_w3RkZ.js} +1 -1
- package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.br +2 -0
- package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{6.D6WLqCgl.js → 6.C-DiUI5R.js} +1 -1
- package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{7.CNuRjkv2.js → 7.B8yubYrv.js} +1 -1
- package/build/client/_app/immutable/nodes/7.B8yubYrv.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.B8yubYrv.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/runtime-meta.json +1 -1
- package/build/server/.vite/manifest.json +35 -45
- package/build/server/_app/immutable/assets/_layout.CqqJCiiV.css +2 -0
- package/build/server/chunks/DefinitionCard.js +3 -0
- package/build/server/chunks/DefinitionCard.js.map +1 -1
- package/build/server/chunks/access.js +15 -3
- package/build/server/chunks/access.js.map +1 -1
- package/build/server/chunks/api-errors.js +18 -3
- package/build/server/chunks/api-errors.js.map +1 -1
- package/build/server/chunks/api.js +9 -2
- package/build/server/chunks/api.js.map +1 -1
- package/build/server/chunks/auth-bootstrap.server.js +63 -39
- package/build/server/chunks/auth-bootstrap.server.js.map +1 -1
- package/build/server/chunks/boot.server.js +1 -1
- package/build/server/chunks/bootHealth.server.js +23 -23
- package/build/server/chunks/bootHealth.server.js.map +1 -1
- package/build/server/chunks/computeRateLimit.server.js +2 -2
- package/build/server/chunks/delete-with-blobs.js +1 -1
- package/build/server/chunks/engine.server.js +52 -5
- package/build/server/chunks/engine.server.js.map +1 -1
- package/build/server/chunks/grasshopper.js +217 -162
- package/build/server/chunks/grasshopper.js.map +1 -1
- package/build/server/chunks/handlers.js +70 -60
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/http.js +24 -24
- package/build/server/chunks/http.js.map +1 -1
- package/build/server/chunks/http2.js +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/instanceAdmins.server.js +31 -16
- package/build/server/chunks/instanceAdmins.server.js.map +1 -1
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/{abort-Bfrdupaj.js → keepalive-vtcjhAV3.js} +6 -3
- package/build/server/chunks/keepalive-vtcjhAV3.js.map +1 -0
- package/build/server/chunks/liveSolve.server.js +1 -1
- package/build/server/chunks/localeContext.svelte.js +14 -0
- package/build/server/chunks/localeContext.svelte.js.map +1 -1
- package/build/server/chunks/oauth.js +70 -24
- package/build/server/chunks/oauth.js.map +1 -1
- package/build/server/chunks/{outcome-DNrffAXp.js → outcome-D28FgvFK.js} +9 -6
- package/build/server/chunks/outcome-D28FgvFK.js.map +1 -0
- package/build/server/chunks/package.js +2 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/permissions.server.js +1 -1
- package/build/server/chunks/presets.server.js +1 -1
- package/build/server/chunks/providers.server.js +324 -121
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/registry.js +1 -1
- package/build/server/chunks/resolve-server.js +1 -1
- package/build/server/chunks/schema-extraction.js +75 -8
- package/build/server/chunks/schema-extraction.js.map +1 -1
- package/build/server/chunks/schema.js +1 -1
- package/build/server/chunks/schema.js.map +1 -1
- package/build/server/chunks/server-config-write.js +6 -6
- package/build/server/chunks/server-config-write.js.map +1 -1
- package/build/server/chunks/server2.js +2 -2
- package/build/server/chunks/server2.js.map +1 -1
- package/build/server/chunks/serverStats.server.js +1 -1
- package/build/server/chunks/signInMaxAge.server.js +1 -1
- package/build/server/chunks/solve.server.js +34 -8
- package/build/server/chunks/solve.server.js.map +1 -1
- package/build/server/chunks/sveltekit.js +4 -5
- package/build/server/chunks/sveltekit.js.map +1 -1
- package/build/server/chunks/update-outcome.js +11 -0
- package/build/server/chunks/update-outcome.js.map +1 -1
- package/build/server/chunks/updateCheck.server.js +24 -12
- package/build/server/chunks/updateCheck.server.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +9 -2
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +59 -15
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +42 -16
- package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +24 -13
- package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +15 -6
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +3 -3
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +5 -4
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/me/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/me/starred/_guid_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/me/token/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_tokenId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
- package/build/server/entries/endpoints/auth/email/callback/_server.ts.js +2 -2
- package/build/server/entries/endpoints/auth/email/callback/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/auth/supabase/callback/_server.ts.js +2 -2
- package/build/server/entries/endpoints/auth/supabase/callback/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
- package/build/server/entries/endpoints/mcp/_server.ts.js +43 -13
- package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
- package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
- package/build/server/entries/hooks.server.js +25 -6
- package/build/server/entries/hooks.server.js.map +1 -1
- package/build/server/entries/pages/admin/compute/_page.server.ts.js +1 -2
- package/build/server/entries/pages/admin/compute/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.server.ts.js +8 -3
- package/build/server/entries/pages/admin/system/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js +18 -2
- package/build/server/entries/pages/admin/system/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +198 -99
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +693 -40
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +3 -2
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.svelte.js +8 -1
- package/build/server/entries/pages/oauth/authorize/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/projects/_page.svelte.js +2 -0
- package/build/server/entries/pages/projects/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/setup/_page.server.ts.js +62 -8
- package/build/server/entries/pages/setup/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/setup/_page.svelte.js +52 -33
- package/build/server/entries/pages/setup/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/team/tokens/_page.server.ts.js +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/0.js +2 -2
- package/build/server/nodes/1.js +1 -1
- package/build/server/nodes/15.js +1 -1
- package/build/server/nodes/2.js +1 -1
- package/build/server/nodes/20.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/nodes/24.js +1 -1
- package/build/server/nodes/25.js +1 -1
- package/build/server/nodes/26.js +1 -1
- package/build/server/nodes/3.js +1 -1
- package/build/server/nodes/5.js +1 -1
- package/build/server/nodes/6.js +1 -1
- package/build/server/nodes/7.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +16 -13
- package/templates/.env.example +15 -7
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css +0 -2
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
- package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
- package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
- package/build/client/_app/immutable/chunks/C6Y_BUwr.js.br +0 -0
- package/build/client/_app/immutable/chunks/C6Y_BUwr.js.gz +0 -0
- package/build/client/_app/immutable/chunks/CzfnuBzq.js.br +0 -0
- package/build/client/_app/immutable/chunks/CzfnuBzq.js.gz +0 -0
- package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js +0 -1
- package/build/client/_app/immutable/chunks/D84F7w9g.js.br +0 -1
- package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DQsP4nZb.js +0 -1
- package/build/client/_app/immutable/chunks/DQsP4nZb.js.br +0 -0
- package/build/client/_app/immutable/chunks/DQsP4nZb.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DzeQucGI.js +0 -2
- package/build/client/_app/immutable/chunks/DzeQucGI.js.br +0 -0
- package/build/client/_app/immutable/chunks/DzeQucGI.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
- package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
- package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
- package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.br +0 -0
- package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15.BXIV1QfS.js +0 -32
- package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.gz +0 -0
- package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
- package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js +0 -1
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js +0 -3
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.gz +0 -0
- package/build/client/_app/immutable/nodes/26.CqaMEm_t.js +0 -6
- package/build/client/_app/immutable/nodes/26.CqaMEm_t.js.br +0 -0
- package/build/client/_app/immutable/nodes/26.CqaMEm_t.js.gz +0 -0
- package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.br +0 -0
- package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +0 -1
- package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
- package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +0 -2
- package/build/server/chunks/abort-Bfrdupaj.js.map +0 -1
- package/build/server/chunks/computeLimits.js +0 -33
- package/build/server/chunks/computeLimits.js.map +0 -1
- package/build/server/chunks/outcome-DNrffAXp.js.map +0 -1
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js → 0.Ds0zeDAg.js} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.br → 0.Ds0zeDAg.js.br} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.gz → 0.Ds0zeDAg.js.gz} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\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\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAOA,SAAgB,sBACf,KACA,aACkC;CAClC,IAAI,EAAE,eAAe,eAAe,OAAO,CAAC;CAC5C,MAAM,EAAE,WAAW,iBAAiB,IAAI,WAAW,CAAC;CACpD,OAAO;EACN,GAAI,OAAO,cAAc,YAAY,EAAE,kBAAkB,UAAU;EACnE,GAAI,OAAO,iBAAiB,YAAY;GACvC,kBAAkB,aAAa;GAC/B,GAAI,eAAe,EAAE,qBAAqB,aAAa;EACxD;CACD;AACD;;;;;;ACLA,IAAM,UAAU,8BAA8B;CAC7C,UAAU;CACV,gBAAgB;CAChB,YAAY;CACZ,WAAW,KAAK,IAAI;CACpB,QAAQ;AACT,CAAC;;AAGD,SAAgB,qBAAqB,KAAkC;CACtE,OAAO,QAAQ,KAAK,GAAG;AACxB;;;;;;;;;;;;;;;;;ACqFA,SAAS,iBAAiB,QAA+B;CAUxD,IAAI,EARH,MAAM,QAAQ,MAAM,KACpB,OAAO,OACL,UACA,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAqB,OA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QAAQ;EACzB,iBAAiB,QAAQ;EACzB,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,gBAAA,CAAiB,QAAQ,CAAC,CAAC;CAC7E,CAAC;MACK;EAGN,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,iBAAiB,KAAK;EACjE,OAAO,IAAI,MAAM,uBAAuB;GACvC,WAAW;GACX;GACA,mBAAmB,mBAAmB;EACvC,CAAC;CACF;CAEA,OAAO,IAAI,MAAM,kBAAkB;EAClC,WAAW;EACX,GAAG,OAAO,YAAY,UAAU,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;CACvF,CAAC;CAGD,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;CAC1B,OAAO,IAAI,MAAM,kCAAkC;EAClD,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"solve.server.js","names":[],"sources":["../../../src/lib/server/compute/sessionId.server.ts","../../../src/lib/server/compute/errorLogFields.ts","../../../src/lib/server/compute/remoteDefinition.server.ts","../../../src/lib/server/compute/solve.server.ts"],"sourcesContent":["import { createHmac } from 'node:crypto';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport type { SolveAccess } from '#lib/server/compute/solve.server.js';\n\n/**\n * Share links have no caller identity, and a remote URL (no `guid`) is caller-chosen, so varying\n * its query string would mint ids: neither gets one, and both route as if compute had no sessions.\n */\nexport function solveSessionId(access: SolveAccess, guid: string | null): string | undefined {\n\tif (access.kind !== 'user' || !access.ctx.userId || !guid) return undefined;\n\treturn computeSessionId(access.ctx.userId, guid);\n}\n\n/**\n * The `X-Session-Id` for one user's solves of one definition: the compute fork routes them back\n * to the child holding that user's warm document. Derived rather than stored, so every Selva\n * instance computes the same id with no shared state, and the browser can't mint ids to fill\n * compute's claim cap. Keyed, so a compute operator can't recover the user id from it.\n *\n * Undefined without `SELVA_HMAC_KEY`: a routing hint never fails a solve. Rotating the key moves\n * every session to a new id, so each solves cold once.\n */\nexport function computeSessionId(userId: string, definitionKey: string): string | undefined {\n\tconst key = hmacKeys().current;\n\tif (!key) return undefined;\n\treturn createHmac('sha256', key)\n\t\t.update(`compute-session\\0${userId}\\0${definitionKey}`)\n\t\t.digest('hex')\n\t\t.slice(0, 32);\n}\n","import { ComputeError } from '@selvajs/compute/core';\n\n/**\n * Log fields for a failed solve. Compute's raw error body can quote what was solved, and erasure\n * can't reach a log line, so it goes out only when an operator asked for raw bodies. The request id\n * ties the line to the server's own logs.\n */\nexport function computeErrorLogFields(\n\terr: unknown,\n\tincludeBody: boolean\n): Record<string, string | number> {\n\tif (!(err instanceof ComputeError)) return {};\n\tconst { requestId, responseBody } = err.context ?? {};\n\treturn {\n\t\t...(typeof requestId === 'string' && { computeRequestId: requestId }),\n\t\t...(typeof responseBody === 'string' && {\n\t\t\tcomputeBodyChars: responseBody.length,\n\t\t\t...(includeBody && { computeResponseBody: responseBody })\n\t\t})\n\t};\n}\n","/**\n * App-wide instance of the remote-definition fetcher (SSRF guard, size cap,\n * deadline, TTL cache all live in `@selvajs/server`'s `createRemoteDefinitionFetcher`).\n */\n\nimport { createRemoteDefinitionFetcher } from '@selvajs/server/compute';\nimport {\n\tREMOTE_DEFINITION_MAX_BYTES,\n\tREMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tREMOTE_DEFINITION_CACHE_TTL_MS\n} from '#lib/server/computeLimits.js';\n// Module-scope init runs before the root logger is fully swapped in, so this\n// needs the forwarding logger, not a snapshot that would pin the boot placeholder.\nimport { lazyLogger } from '#lib/server/providers.server.js';\n\nconst fetcher = createRemoteDefinitionFetcher({\n\tmaxBytes: REMOTE_DEFINITION_MAX_BYTES,\n\tfetchTimeoutMs: REMOTE_DEFINITION_FETCH_TIMEOUT_MS,\n\tcacheTtlMs: REMOTE_DEFINITION_CACHE_TTL_MS,\n\tnow: () => Date.now(),\n\tlogger: lazyLogger\n});\n\n/** Fetch (or return cached) remote `.gh` bytes. Throws on unsafe host / oversized / timeout. */\nexport function loadRemoteDefinition(url: string): Promise<Uint8Array> {\n\treturn fetcher.load(url);\n}\n","/**\n * The body-independent core of a solve request, shared by `POST /api/v1/compute`\n * (share-token and remote-URL capable) and `POST /api/v1/definitions/{guid}/solve`\n * (tenant-scoped, cookie or PAT).\n *\n * **Share-token resolution stays outside this module, in the route.** The caller\n * hands in an already-decided `SolveAccess`; the definition-addressed route only\n * ever constructs the `user` variant, so it cannot inherit the anonymous branch\n * by accident. Adding a token lookup here would silently give it one.\n *\n * What lives here: rate limiting, definition/version resolution, access checks,\n * compute-server routing, schema backfill, the engine call, metric recording, the\n * debug breakdown. What stays in a route: parsing its own body shape and deciding\n * who the caller is.\n */\n\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport {\n\tApiError,\n\tassertScope,\n\tchargeApiRateLimit,\n\tisApiError,\n\trateLimitedResponse,\n\ttoErrorBody,\n\twithRateLimitHeaders\n} from '@selvajs/server/api';\nimport { isHttpError } from '@sveltejs/kit';\nimport { ComputeError, ErrorCodes } from '@selvajs/compute/core';\nimport type { SolveMode } from '@selvajs/compute/grasshopper';\nimport type { ComputeServerConfig, RequestContext, SolveFailureKind } from '@selvajs/platform';\nimport { ComputeServerUnconfiguredError } from '@selvajs/server/compute';\nimport { serverResolver } from './serverResolver.server';\nimport { engine, COMPUTE_DEBUG, COMPUTE_DEBUG_VERBOSE } from '#lib/server/compute/engine.server.js';\nimport { solveSessionId } from '#lib/server/compute/sessionId.server.js';\nimport { computeErrorLogFields } from '#lib/server/compute/errorLogFields.js';\nimport { loadRemoteDefinition } from '#lib/server/compute/remoteDefinition.server.js';\nimport {\n\tpostedServerSourcedIds,\n\tsolveInputsFromSchema,\n\ttype ByteCacheRef,\n\ttype SolveDefinition,\n\ttype SolveEnvelope,\n\ttype SolveInput\n} from '@selvajs/solve/server';\nimport type { UISchema } from '@selvajs/schemas';\nimport { apiRateLimiter, checkComputeRateLimit } from '#lib/server/computeRateLimit.server.js';\nimport { getStorageProvider, getSolveMetricSink, providers } from '#lib/server/providers.server.js';\nimport { requireCanSolve, requireCanEditDefinition, scoped } from '#lib/server/access.server.js';\nimport { fetchSchemaFromCompute } from '@selvajs/server/definitions';\nimport { renderThrown } from '@selvajs/server/logging';\nimport type { ShareLink } from '@selvajs/platform';\nimport { MAX_SOLVE_DEADLINE_MS } from '@selvajs/solve/server';\nimport {\n\tbindLiveSolve,\n\tliveOwnerKey,\n\tsolveEndedKind\n} from '#lib/server/solveEvents/liveSolve.server.js';\n\nexport type SolveChannel = 'live' | 'draft';\n\n/**\n * Who is solving, and under whose authority.\n *\n * `user` — a logged-in caller; the per-definition access rules run.\n * `share` — a share-link token; the token already encodes the grant, so the\n * rules are skipped and the link's solve cap is charged instead.\n */\nexport type SolveAccess =\n\t| { kind: 'user'; ctx: RequestContext; rateLimitKey: string }\n\t| { kind: 'share'; ctx: RequestContext; link: ShareLink; rateLimitKey: string };\n\nexport interface SolveParams {\n\taccess: SolveAccess;\n\tdefinitionUrl: string;\n\t/**\n\t * The request body's inputs, read for a remote URL only. A stored definition's come from its\n\t * version's schema: a caller, a share-link visitor included, must not choose its ids, types or\n\t * bounds.\n\t */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tchannel: SolveChannel;\n\t/** Explicit version pick; editor-only, never share-token accessible. */\n\tversionId: string | null;\n\trequest: Request;\n\t/** Typed loosely: two route trees with different generated `$types` both call this. */\n\tlocals: App.Locals;\n\t/** `performance.now()` at the very start of the request, before body parse. */\n\tloadStart: number;\n\t/** Prep sub-phase timings recorded before this call (body parse, token). */\n\tprepMarks: [string, number][];\n\t/**\n\t * The caller's live-event stream (`GET /api/v1/solve-events?streamId=`). When it is open\n\t * and theirs, this solve is bound to it: the server emits start/end, and the compute\n\t * request carries a callback so the definition can emit mid-solve. Ignored otherwise.\n\t */\n\tstreamId?: string | null;\n\t/** See `SolveBodySchema.mode`. */\n\tsolveMode?: SolveMode;\n\t/**\n\t * Report an access refusal as 404 instead of 403.\n\t *\n\t * The definition-addressed route needs this: a guid is guessable, so\n\t * 403-vs-404 there tells a caller whether a definition they cannot reach\n\t * exists. `/api/v1/compute` leaves it off — its callers navigated to the\n\t * definition, and a 403 is the more useful answer.\n\t */\n\tconcealAccessFailure?: boolean;\n\t/**\n\t * The route already charged the key's request bucket, ahead of any idempotent\n\t * replay that would skip this function, so it must not be charged twice.\n\t */\n\ttokenCharged?: boolean;\n}\n\nfunction readRemoteInputs(inputs: unknown): SolveInput[] {\n\tconst valid =\n\t\tArray.isArray(inputs) &&\n\t\tinputs.every(\n\t\t\t(input) =>\n\t\t\t\ttypeof input === 'object' &&\n\t\t\t\tinput !== null &&\n\t\t\t\ttypeof (input as SolveInput).id === 'string' &&\n\t\t\t\ttypeof (input as SolveInput).nickname === 'string'\n\t\t);\n\tif (!valid) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t'A remote definitionUrl needs inputs: a list of { id, nickname, paramType }.'\n\t\t);\n\t}\n\treturn inputs as SolveInput[];\n}\n\nfunction admittedSolveInputs(\n\tschema: UISchema | undefined,\n\tinputs: unknown,\n\tvalues: Record<string, unknown>\n): SolveInput[] {\n\tconst solveInputs = schema ? solveInputsFromSchema(schema) : readRemoteInputs(inputs);\n\tconst serverOnly = postedServerSourcedIds(solveInputs, values);\n\tif (serverOnly.length > 0) {\n\t\tapiError(\n\t\t\t400,\n\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t`These inputs are filled on the server and may not be posted in values: ${serverOnly.join(', ')}.`\n\t\t);\n\t}\n\treturn solveInputs;\n}\n\n/**\n * Run a solve and return the HTTP response.\n *\n * Throws `HttpError` (via `apiError`) for every refusal, and lets engine/network\n * failures propagate for the caller's outer catch to map — the two routes share\n * that mapping through `mapSolveError`.\n */\nexport async function runSolve(params: SolveParams): Promise<Response> {\n\tconst {\n\t\taccess,\n\t\tdefinitionUrl,\n\t\tinputs,\n\t\tvalues,\n\t\tchannel,\n\t\tversionId: explicitVersionId,\n\t\trequest,\n\t\tlocals,\n\t\tloadStart,\n\t\tprepMarks,\n\t\tconcealAccessFailure = false,\n\t\tstreamId = null,\n\t\tsolveMode = 'full',\n\t\ttokenCharged = false\n\t} = params;\n\tconst storage = getStorageProvider();\n\tconst sharedAccess = access.kind === 'share' ? access : null;\n\tconst solveCtx = access.ctx;\n\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\t// Local definitions solve by reference: a byte-cache `DefinitionRef` whose\n\t// bytes the scheduler loads ONLY when an upload is unavoidable (pointer-known\n\t// re-solves move zero bytes). Remote-URL definitions carry raw fetched bytes.\n\tlet definitionSource: SolveDefinition;\n\t// `.load()` materializes bytes for schema backfill; `.outcome` drives the\n\t// `def_bytes` Server-Timing verdict. Null for remote-URL solves.\n\tlet localDefinitionRef: ByteCacheRef | null = null;\n\tlet localVersionForBackfill: { id: string; hasSchema: boolean } | null = null;\n\tlet storedSchema: UISchema | undefined;\n\t// BYO compute routing per org; null for remote definitions.\n\tlet solveOrgId: string | null = null;\n\tlet definitionPin: string | null = null;\n\t// Started once the project is known; null for remote definitions.\n\tlet pendingServer: Promise<ComputeServerConfig> | null = null;\n\t// Solve-metric attribution; null for remote-URL solves.\n\tlet metricDefinitionId: string | null = null;\n\tlet metricVersionId: string | null = null;\n\n\tconst isLocal = definitionUrl.startsWith('local:');\n\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\n\t// One row per solve attempt, including attempts rejected before the solve\n\t// runs — reads the attribution `let`s at call time, so definition/version\n\t// are null when a record fires pre-resolution. Fire-and-forget: the sink\n\t// never throws (ISolveMetricSink contract).\n\tconst recordMetric = (\n\t\tfailureKind: SolveFailureKind,\n\t\textra: { durationMs?: number; errorCount?: number; warningCount?: number } = {}\n\t) => {\n\t\tgetSolveMetricSink()\n\t\t\t.record(solveCtx, {\n\t\t\t\tdefinitionUrl,\n\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\tversionId: metricVersionId,\n\t\t\t\tchannel,\n\t\t\t\torgId: solveOrgId,\n\t\t\t\tdurationMs: extra.durationMs ?? 0,\n\t\t\t\tok: failureKind === 'ok',\n\t\t\t\tfailureKind,\n\t\t\t\terrorCount: extra.errorCount ?? 0,\n\t\t\t\twarningCount: extra.warningCount ?? 0\n\t\t\t})\n\t\t\t// Sinks are contracted not to throw, but nothing enforces it — a bad sink\n\t\t\t// must surface as a log line, not an unhandled rejection.\n\t\t\t.catch((err) =>\n\t\t\t\tlocals.log.error('Solve-metric record failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t};\n\n\t// Both limits run before DB reads so throttled callers don't burn quota. A\n\t// token pays its own request bucket and its owner's compute bucket, so ten\n\t// keys of one user never buy ten times the compute.\n\tconst tokenVerdict = tokenCharged\n\t\t? undefined\n\t\t: await chargeApiRateLimit(access.ctx, apiRateLimiter);\n\tif (tokenVerdict && !tokenVerdict.allowed) {\n\t\trecordMetric('rate_limited');\n\t\treturn rateLimitedResponse(tokenVerdict);\n\t}\n\tconst rateLimit = checkComputeRateLimit(access.rateLimitKey);\n\tif (!rateLimit.allowed) {\n\t\trecordMetric('rate_limited');\n\t\tconst retryAfter = String(rateLimit.retryAfter ?? 1);\n\t\tconst err = new ApiError(\n\t\t\t429,\n\t\t\tApiErrorCode.RATE_LIMITED,\n\t\t\t`Too many compute requests. Retry in ${retryAfter}s.`,\n\t\t\tundefined,\n\t\t\t{ retryAfter }\n\t\t);\n\t\treturn withRateLimitHeaders(\n\t\t\tnew Response(JSON.stringify(toErrorBody(err)), {\n\t\t\t\tstatus: 429,\n\t\t\t\theaders: { 'Content-Type': 'application/json', 'Retry-After': retryAfter }\n\t\t\t}),\n\t\t\ttokenVerdict\n\t\t);\n\t}\n\n\tif (isLocal && guid) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await providers.data.definitions.get(solveCtx, guid);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to load local definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t}\n\t\tif (!record) apiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\tmark('defRecord');\n\n\t\t// The version and the server need only the record and its project, so they are read\n\t\t// while access is checked, and awaited after it in their old order: a caller refused\n\t\t// access learns nothing from a missing version or server.\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'live' ? record.liveVersionId : record.draftVersionId);\n\t\tconst pendingVersion = versionId\n\t\t\t? providers.data.definitions.getVersion(solveCtx, versionId)\n\t\t\t: null;\n\t\tpendingVersion?.catch(() => {});\n\t\tconst project = await providers.data.projects.getProject(solveCtx, record.projectId);\n\t\tsolveOrgId = project?.orgId ?? null;\n\t\tdefinitionPin = record.computeServerId ?? null;\n\t\tpendingServer = serverResolver.resolve(\n\t\t\tsolveCtx,\n\t\t\tsolveOrgId,\n\t\t\tlocals.providers.data.computeServer,\n\t\t\t{ definitionPin }\n\t\t);\n\t\tpendingServer.catch(() => {});\n\t\tmark('project');\n\n\t\tif (!sharedAccess) {\n\t\t\ttry {\n\t\t\t\tassertScope(access.ctx, 'solve', { projectId: record.projectId, definitionId: guid });\n\t\t\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\t\t\tawait requireCanEditDefinition(scoped(locals), record.projectId, guid, {\n\t\t\t\t\t\tproject,\n\t\t\t\t\t\tdefinition: record\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tawait requireCanSolve(scoped(locals), record.projectId, project ?? undefined);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\t// The guards raise `ApiError`, but `requireCanEditDefinition` may still\n\t\t\t\t// surface an `HttpError` — matching only one shape would let the\n\t\t\t\t// other's 403 leak through, confirming a guid the caller can't reach.\n\t\t\t\tconst status = isApiError(err) ? err.status : isHttpError(err) ? err.status : undefined;\n\t\t\t\tif (concealAccessFailure && status === 403) {\n\t\t\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' not found`);\n\t\t\t\t}\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t\tmark('access');\n\n\t\tif (!versionId || !pendingVersion) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' has no ${channel} version yet`);\n\t\t}\n\t\tconst version = await pendingVersion;\n\t\tif (!version || version.definitionId !== guid) {\n\t\t\tapiError(404, ApiErrorCode.NOT_FOUND, `Definition '${guid}' version is missing`);\n\t\t}\n\t\tlocalVersionForBackfill = { id: version.id, hasSchema: version.schema !== undefined };\n\t\tstoredSchema = version.schema;\n\t\tmetricDefinitionId = guid;\n\t\tmetricVersionId = version.id;\n\t\tmark('version');\n\n\t\t// Keyed on the immutable version id, NEVER the fileKey — a\n\t\t// delete-latest-then-reupload can reuse a fileKey for different content.\n\t\t// A missing blob surfaces at solve time (compute_error → 500) rather than\n\t\t// an upfront 404, since it's no longer read eagerly here.\n\t\tlocalDefinitionRef = engine.definitionRef(version.id, async () => {\n\t\t\tconst bytes = await storage.get(version.fileKey);\n\t\t\tif (!bytes) throw new Error(`Version blob missing: ${version.fileKey}`);\n\t\t\treturn bytes;\n\t\t});\n\t\tdefinitionSource = localDefinitionRef;\n\t\tmark('blob');\n\t} else {\n\t\t// A remote URL names no project, so only an org-wide key may solve it.\n\t\tassertScope(access.ctx, 'solve');\n\t\treadRemoteInputs(inputs);\n\t\ttry {\n\t\t\tdefinitionSource = await loadRemoteDefinition(definitionUrl);\n\t\t} catch (err) {\n\t\t\tlocals.log.error('Failed to fetch remote definition', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tdefinitionUrl,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Failed to load definition: ${err instanceof Error ? err.message : String(err)}`\n\t\t\t);\n\t\t}\n\t\tmark('remoteDef');\n\t}\n\n\t// Everything above (auth, DB, blob/remote fetch) is the \"load\" phase; tree\n\t// build and solve are measured inside the pipeline.\n\tconst defLoadMs = performance.now() - loadStart;\n\n\t// Checked before the share cap, so a request refused for its values spends no\n\t// solve. A version without a stored schema is checked after the backfill below.\n\tlet solveInputs =\n\t\tstoredSchema || !isLocal ? admittedSolveInputs(storedSchema, inputs, values) : null;\n\n\t// Atomic check-and-increment; runs before solve to avoid wasting compute.\n\tif (sharedAccess) {\n\t\tconst next = await providers.data.shareLinks.tryIncrementSolveCount(\n\t\t\tsolveCtx,\n\t\t\tsharedAccess.link.id\n\t\t);\n\t\tif (next === null) {\n\t\t\trecordMetric('share_cap');\n\t\t\tapiError(429, ApiErrorCode.RATE_LIMITED, 'Share link solve cap reached.');\n\t\t}\n\t\tmark('shareCap');\n\t}\n\n\tconst serverConfig = await (pendingServer ??\n\t\tserverResolver.resolve(solveCtx, solveOrgId, locals.providers.data.computeServer, {\n\t\t\tdefinitionPin\n\t\t}));\n\tmark('resolveServer');\n\n\t// BRIDGE: remove ~2026-09 — lazy backfill for versions uploaded before schema\n\t// caching existed. Best-effort. Removing it: delete this block, tighten\n\t// `DefinitionVersion.schema` to required in platform types + Zod, and drop the\n\t// live-fetch fallback in loadForRender.server.ts.\n\tif (localVersionForBackfill && !localVersionForBackfill.hasSchema && localDefinitionRef) {\n\t\tconst versionId = localVersionForBackfill.id;\n\t\ttry {\n\t\t\t// Warms the byte-cache entry the upcoming solve's `load()` would hit anyway.\n\t\t\tconst bytes = await localDefinitionRef.load();\n\t\t\tstoredSchema = await fetchSchemaFromCompute(bytes, serverConfig);\n\t\t\tawait providers.data.definitions.setVersionSchema(solveCtx, versionId, storedSchema);\n\t\t} catch (err) {\n\t\t\tlocals.log.warn('Schema backfill failed', {\n\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\tversionId,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t}\n\t\t// Backfill calls the compute server — seconds when it fires. If this shows\n\t\t// up repeatedly for the same definition, setVersionSchema isn't sticking.\n\t\tmark('schemaBackfill');\n\t}\n\n\tif (isLocal && !storedSchema) {\n\t\tapiError(\n\t\t\t503,\n\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\"This version's inputs could not be read. Retry shortly.\"\n\t\t);\n\t}\n\tsolveInputs ??= admittedSolveInputs(storedSchema, inputs, values);\n\n\t// `SolveEngine.solve` owns warm-client lookup, input-tree build, single-flight\n\t// coalescing (a coalesced solve aborts only when its last caller leaves), and\n\t// per-caller encoding. Remote-URL solves have no version id, so the URL stands\n\t// in as coalesce-key identity (`definitionKey`); local solves already carry\n\t// that identity on `localDefinitionRef.key`.\n\tconst live = bindLiveSolve({\n\t\townerKey: liveOwnerKey(access.kind === 'user' ? access.ctx.userId : null),\n\t\tstreamId,\n\t\trequest,\n\t\t// Outlives any server's deadline by a margin, so a callback racing the response is not\n\t\t// refused. Minted before the warm client that knows this server's deadline.\n\t\ttokenTtlMs: MAX_SOLVE_DEADLINE_MS + 60_000\n\t});\n\n\tlet outcome: Awaited<ReturnType<typeof engine.solve>> | undefined;\n\ttry {\n\t\toutcome = await engine.solve({\n\t\t\tserver: serverConfig,\n\t\t\tdefinitionSource,\n\t\t\tdefinitionKey: isLocal ? undefined : definitionUrl,\n\t\t\tinputs: solveInputs,\n\t\t\tvalues,\n\t\t\tsignal: request.signal,\n\t\t\tacceptEncoding: request.headers.get('accept-encoding') ?? '',\n\t\t\tdefinitionGuid: guid ?? undefined,\n\t\t\tloadStartMs: loadStart,\n\t\t\tdefLoadMs,\n\t\t\tprepMarks,\n\t\t\tselvaEvents: live.selvaEvents,\n\t\t\tsessionId: solveSessionId(access, guid),\n\t\t\tsolveMode\n\t\t});\n\t} finally {\n\t\tlive.end(outcome ? solveEndedKind(outcome) : 'error');\n\t}\n\tmark('solve');\n\n\t// Metric recording is app policy — the engine only maps outcome to HTTP.\n\t// These branches don't return; `engine.toWebResponse` below does.\n\tif (outcome.kind === 'timeout') {\n\t\trecordMetric('timeout', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'client_abort') {\n\t\trecordMetric('client_abort', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'too_large') {\n\t\trecordMetric('too_large');\n\t} else if (outcome.kind === 'shed') {\n\t\trecordMetric('shed', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'compute_error') {\n\t\trecordMetric('compute_error', { durationMs: outcome.durationMs });\n\t} else if (outcome.kind === 'ok') {\n\t\trecordMetric('ok', {\n\t\t\tdurationMs: outcome.solveMs,\n\t\t\terrorCount: outcome.errorCount,\n\t\t\twarningCount: outcome.warningCount\n\t\t});\n\t\t// Best-effort: the solve already succeeded, so a failed counter write\n\t\t// must not turn into a request error. Local definitions only — remote\n\t\t// URLs have no record to bump.\n\t\tif (metricDefinitionId) {\n\t\t\tproviders.data.definitions.incrementSolveCount(solveCtx, metricDefinitionId).catch((err) =>\n\t\t\t\tlocals.log.warn('solveCount increment failed', {\n\t\t\t\t\tcomponent: 'API/Compute',\n\t\t\t\t\tdefinitionId: metricDefinitionId,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t})\n\t\t\t);\n\t\t}\n\n\t\tif (COMPUTE_DEBUG) logDebugBreakdown(locals, request, outcome, defLoadMs, prepMarks);\n\t}\n\n\t// Builds the Response itself (incl. `Retry-After` on a rejected `shed`,\n\t// which `apiError` cannot set) and still throws `compute_error` through to\n\t// the caller's outer catch.\n\treturn withRateLimitHeaders(engine.toWebResponse(outcome), tokenVerdict);\n}\n\n/**\n * Both solve routes share this so they cannot drift on which failures read as\n * \"compute is down\" (503) versus a server bug (500).\n */\nexport function mapSolveError(err: unknown, locals: App.Locals): never {\n\tif (isHttpError(err)) throw err;\n\t// A guard's own refusal, not a failed solve — converted rather than\n\t// re-thrown. These routes return their Response directly instead of going\n\t// through `mount`, so an `ApiError` escaping here would reach SvelteKit,\n\t// which gives anything that isn't an `HttpError` a 500, turning a working\n\t// permission check into an operator error page.\n\tif (isApiError(err)) {\n\t\tapiError(err.status, err.code, err.message, err.fields, err.details);\n\t}\n\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\n\tconst message = err instanceof Error ? err.message : 'Unknown error';\n\tlocals.log.error('Solve request failed', {\n\t\tcomponent: 'API/Compute',\n\t\terr: renderThrown(err),\n\t\t...computeErrorLogFields(err, COMPUTE_DEBUG_VERBOSE)\n\t});\n\n\t// The compute transport classifies its failures — map the classes the caller\n\t// can act on. Unreachable/credentials/saturation are operator problems (503),\n\t// a deadline is 504; only a genuine solve failure stays 500.\n\tif (err instanceof ComputeError) {\n\t\tif (err.code === ErrorCodes.NETWORK_ERROR || err.code === ErrorCodes.CORS_ERROR) {\n\t\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t\t}\n\t\tif (err.code === ErrorCodes.AUTH_ERROR) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t\"Compute server rejected this deployment's credentials — check the compute API key configuration.\"\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.RATE_LIMIT) {\n\t\t\tapiError(\n\t\t\t\t503,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server is rate-limiting requests. Retry shortly.'\n\t\t\t);\n\t\t}\n\t\tif (err.code === ErrorCodes.TIMEOUT_ERROR) {\n\t\t\tapiError(\n\t\t\t\t504,\n\t\t\t\tApiErrorCode.COMPUTE_UNAVAILABLE,\n\t\t\t\t'Compute server timed out running the solve.'\n\t\t\t);\n\t\t}\n\t}\n\n\t// A transport-layer fetch failure means the compute server is unreachable,\n\t// not an internal error. (Raw TypeError only from fetches outside the compute\n\t// transport — the transport wraps its own into ComputeError NETWORK_ERROR.)\n\tif (err instanceof TypeError && message === 'fetch failed') {\n\t\tapiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, 'Compute server is unreachable');\n\t}\n\n\tapiError(500, ApiErrorCode.INTERNAL, message);\n}\n\n/**\n * DEBUG (SELVA_FLAG_COMPUTE_DEBUG): the server-side overhead the solve metric's\n * `durationMs` doesn't capture. `load` = auth + DB + definition fetch; `tree` =\n * input tree build; `serialize` = JSON.stringify of the result.\n */\nfunction logDebugBreakdown(\n\tlocals: App.Locals,\n\trequest: Request,\n\toutcome: { envelope: SolveEnvelope },\n\tdefLoadMs: number,\n\tprepMarks: [string, number][]\n): void {\n\tconst { metrics } = outcome.envelope;\n\tlocals.log.debug('Solve server-side phase breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\tloadMs: Math.round(defLoadMs),\n\t\ttreeBuildMs: Math.round(metrics.treeBuildMs),\n\t\tsolveMs: Math.round(metrics.solveMs),\n\t\tserializeMs: Math.round(metrics.serializeMs),\n\t\tgzipMs: Math.round(metrics.gzipMs),\n\t\tserverTotalMs: Math.round(metrics.serverTotalMs),\n\t\tserializedBytes: metrics.serializedBytes\n\t});\n\tif (metrics.compressedBytes !== null) {\n\t\tlocals.log.debug('Response gzipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tserializedBytes: metrics.serializedBytes,\n\t\t\tcompressedBytes: metrics.compressedBytes,\n\t\t\tratio: Number((metrics.serializedBytes / metrics.compressedBytes).toFixed(1))\n\t\t});\n\t} else {\n\t\t// If this fires for browser requests, a proxy in front is stripping\n\t\t// Accept-Encoding, making compression impossible end-to-end.\n\t\tconst acceptEncoding = request.headers.get('accept-encoding') ?? '';\n\t\tlocals.log.debug('Compression skipped', {\n\t\t\tcomponent: 'Compute/server',\n\t\t\tacceptEncoding,\n\t\t\thasAcceptEncoding: acceptEncoding !== ''\n\t\t});\n\t}\n\t// Names the step a `load` (or pre-solve) spike hides in.\n\tlocals.log.debug('Prep breakdown', {\n\t\tcomponent: 'Compute/server',\n\t\t...Object.fromEntries(prepMarks.map(([label, ms]) => [`p_${label}Ms`, Math.round(ms)]))\n\t});\n\t// The only place evictions surface — per-request Server-Timing only carries\n\t// hit/miss verdicts.\n\tconst db = engine.stats().definitionBytes;\n\tlocals.log.debug('Definition byte-cache counters', {\n\t\tcomponent: 'Compute/def-bytes',\n\t\thits: db.hits,\n\t\tmisses: db.misses,\n\t\tevictions: db.evictions,\n\t\tentries: db.entries,\n\t\tretainedBytes: db.bytes\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,QAAqB,MAAyC;CAC5F,IAAI,OAAO,SAAS,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC,MAAM,OAAO,KAAA;CAClE,OAAO,iBAAiB,OAAO,IAAI,QAAQ,IAAI;AAChD;;;;;;;;;;AAWA,SAAgB,iBAAiB,QAAgB,eAA2C;CAC3F,MAAM,MAAM,SAAS,CAAC,CAAC;CACvB,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,OAAO,WAAW,UAAU,GAAG,CAAC,CAC9B,OAAO,oBAAoB,OAAO,IAAI,eAAe,CAAC,CACtD,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;AACd;;;;;;;ACtBA,SAAgB,sBACf,KACA,aACkC;CAClC,IAAI,EAAE,eAAe,eAAe,OAAO,CAAC;CAC5C,MAAM,EAAE,WAAW,iBAAiB,IAAI,WAAW,CAAC;CACpD,OAAO;EACN,GAAI,OAAO,cAAc,YAAY,EAAE,kBAAkB,UAAU;EACnE,GAAI,OAAO,iBAAiB,YAAY;GACvC,kBAAkB,aAAa;GAC/B,GAAI,eAAe,EAAE,qBAAqB,aAAa;EACxD;CACD;AACD;;;;;;ACLA,IAA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I,MAAM,qCAAqC;EACrD,WAAW;EACX,QAAQ,KAAK,MAAM,SAAS;EAC5B,aAAa,KAAK,MAAM,QAAQ,WAAW;EAC3C,SAAS,KAAK,MAAM,QAAQ,OAAO;EACnC,aAAa,KAAK,MAAM,QAAQ,WAAW;EAC3C,QAAQ,KAAK,MAAM,QAAQ,MAAM;EACjC,eAAe,KAAK,MAAM,QAAQ,aAAa;EAC/C,iBAAiB,QAAQ;CAC1B,CAAC;CACD,IAAI,QAAQ,oBAAoB,MAC/B,OAAO,IAAI,MAAM,oBAAoB;EACpC,WAAW;EACX,iBAAiB,QAAQ;EACzB,iBAAiB,QAAQ;EACzB,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,gBAAA,CAAiB,QAAQ,CAAC,CAAC;CAC7E,CAAC;MACK;EAGN,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,iBAAiB,KAAK;EACjE,OAAO,IAAI,MAAM,uBAAuB;GACvC,WAAW;GACX;GACA,mBAAmB,mBAAmB;EACvC,CAAC;CACF;CAEA,OAAO,IAAI,MAAM,kBAAkB;EAClC,WAAW;EACX,GAAG,OAAO,YAAY,UAAU,KAAK,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC;CACvF,CAAC;CAGD,MAAM,KAAK,OAAO,MAAM,CAAC,CAAC;CAC1B,OAAO,IAAI,MAAM,kCAAkC;EAClD,WAAW;EACX,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,WAAW,GAAG;EACd,SAAS,GAAG;EACZ,eAAe,GAAG;CACnB,CAAC;AACF"}
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { G as NoopEventSink, c as getDefinitionService, i as getBranding, m as getOrgAssetService, p as getNotificationProvider } from "./providers.server.js";
|
|
2
2
|
import { O as ApiError, j as codeForStatus, k as ApiErrorCode, z as isFlagEnabled } from "./access.js";
|
|
3
3
|
import { i as ProviderError } from "./context.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { A as rateLimitedResponse, D as chargeApiRateLimit, M as withRateLimitHeaders, x as runHandler } from "./api.js";
|
|
5
|
+
import { t as SchemaExtractionError, u as ComputeServerUnconfiguredError } from "./schema-extraction.js";
|
|
6
6
|
import { t as publicUrl } from "./origin.js";
|
|
7
|
-
import {
|
|
8
|
-
import { s as evictComputeClient } from "./engine.server.js";
|
|
7
|
+
import { _ as MAX_IMAGE_FILE_SIZE, c as evictComputeClient, g as MAX_DEFINITION_FILE_SIZE } from "./engine.server.js";
|
|
9
8
|
import { t as serverResolver } from "./serverResolver.server.js";
|
|
10
9
|
import { n as apiTokenResolutions, t as apiTokenCodec } from "./token2.server.js";
|
|
11
10
|
import { r as shareLinkCodec } from "./token3.server.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sveltekit.js","names":[],"sources":["../../../../server/src/api/deps.ts","../../../../server/src/api/map-core-error.ts","../../../src/lib/server/api/sveltekit.ts"],"sourcesContent":["/**\n * Everything an API handler talks to, as one injected value.\n *\n * Handlers used to reach module-global getters (`getProjectProvider()`,\n * `getDefinitionService()`, …) from the Selva app's composition root — 77 call\n * sites across the v1 routes. That welded them to one app's boot: a second app\n * on a different provider set could not call them at all.\n *\n * Most fields are sub-stores of `IDataProvider`, so a host that already built a\n * `SelvaConfig` gets them via `depsFromConfig`. `services` stays host-defined:\n * `DefinitionService` and friends are composed rather than resolved, and a host\n * may supply its own.\n */\n\nimport { isFlagEnabled, NoopEventSink } from '@selvajs/platform';\nimport type { DefinitionService } from '../definitions/definition-service.js';\nimport type { OrgAssetService } from '../organizations/org-asset-service.js';\nimport type { TokenCodec } from '../tokens/token-codec.js';\nimport type { ApiTokenCodec } from '../tokens/api-token-codec.js';\nimport type { ApiTokenHolderPolicy } from '../tokens/api-token-holder.js';\nimport type { ApiTokenResolutionCache } from '../http/api-token.js';\nimport type { ApiRateLimiter } from './rate-limit.js';\nimport type { ApiIdempotencyStore } from './idempotency.js';\nimport type {\n\tIAuthProvider,\n\tIDataProvider,\n\tIEventSink,\n\tINotificationProvider,\n\tIStorageProvider,\n\tSelvaConfig,\n\tSelvaFlags\n} from '@selvajs/platform';\n\nexport interface SelvaDeps {\n\tauth: IAuthProvider;\n\tstorage: IStorageProvider;\n\tdata: IDataProvider;\n\t/** `data.orgs` — hoisted because 18 v1 call sites read it directly. */\n\torgs: IDataProvider['orgs'];\n\t/** `data.projects` — 18 call sites. */\n\tprojects: IDataProvider['projects'];\n\t/** `data.definitions` — the definition metadata store. */\n\tdefinitionMeta: IDataProvider['definitions'];\n\tcomputeServer: IDataProvider['computeServer'];\n\tuserProfile: IDataProvider['userProfile'];\n\tshareLinks: IDataProvider['shareLinks'];\n\tinvites: IDataProvider['invites'];\n\tpermissions: IDataProvider['permissions'];\n\tplatformProjectGrants: IDataProvider['platformProjectGrants'];\n\t/**\n\t * Audit sink. Never optional here even though `SelvaConfig.events` is:\n\t * handlers emit escalation events (`project.reclaimed`,\n\t * `org_member.removed_orphaning_projects`) that the audit trail depends on,\n\t * and a handler deciding for itself what a missing sink means is how one of\n\t * them ends up silently unlogged. `depsFromConfig` substitutes\n\t * `NoopEventSink`, which discards explicitly.\n\t */\n\tevents: IEventSink;\n\t/**\n\t * Feature flags, as a predicate rather than a record: an omitted flag must\n\t * read as false, and keeping that in `isFlagEnabled` stops each caller from\n\t * re-deciding what a missing flag means.\n\t */\n\tflag: (name: keyof SelvaFlags) => boolean;\n\t/**\n\t * Token codecs, one per family, keyed by what they mint.\n\t *\n\t * Injected rather than resolved because the codec is built from an\n\t * instance-wide HMAC secret, and reading that secret is the host's job — a\n\t * package that reached for `process.env.SELVA_HMAC_KEY` itself would pin\n\t * every host to one env var name and one way of loading it. Rotating a\n\t * secret invalidates that family's outstanding tokens, so the two families\n\t * are separate values rather than one shared codec.\n\t *\n\t * Optional: a host with no sharing and no invites wires neither. The\n\t * handlers that need one fail loudly if it is absent rather than minting a\n\t * token nobody can verify.\n\t */\n\ttokens: {\n\t\tshareLinks?: TokenCodec;\n\t\tinvites?: TokenCodec;\n\t\t/** Without it, minting answers 503 `API_TOKENS_UNAVAILABLE`. */\n\t\tapiTokens?: ApiTokenCodec;\n\t\t/** Who may mint and use API tokens. Absent: the platform permission `manage_api_tokens`. */\n\t\tmayHoldApiTokens?: ApiTokenHolderPolicy;\n\t\t/** How long one sign-in lasts before minting needs a new one (`resolveSignInMaxAgeMs`). Absent: no limit. */\n\t\tsignInMaxAgeMs?: number;\n\t\t/**\n\t\t * The cache the host hands `resolveApiToken`, so a revoke through these handlers drops\n\t\t * the key from it at once. Absent: nothing to drop.\n\t\t */\n\t\tresolutionCache?: ApiTokenResolutionCache;\n\t};\n\t/**\n\t * Upload caps, in bytes.\n\t *\n\t * Deployment config, so the host resolves them — a package reading its own\n\t * env would pin every host to one variable name. Defaults apply when the\n\t * host says nothing, because a missing cap must not read as \"unlimited\":\n\t * `requireUpload` compares against this number, and `undefined` would let\n\t * any size through.\n\t */\n\tuploadLimits: {\n\t\tmaxDefinitionFileSize: number;\n\t\tmaxImageFileSize: number;\n\t};\n\t/**\n\t * Outbound mail, and the instance name to fall back to when a record has no\n\t * name of its own.\n\t *\n\t * Optional because mail is best-effort by design: an invite row is committed\n\t * before delivery is attempted, and the caller still holds the accept URL to\n\t * share by hand. A host with no mail configured wires nothing and the\n\t * handlers report `not-configured` rather than failing the write.\n\t */\n\tnotifications?: INotificationProvider;\n\t/**\n\t * Per-token request limit `runHandler` charges. Absent: the process-wide\n\t * default (`DEFAULT_API_RATE_LIMIT`). `null`: no limit. A host's own limiter\n\t * must outlive the request, since deps are rebuilt per request.\n\t */\n\tapiRateLimiter?: ApiRateLimiter | null;\n\t/**\n\t * Projects one owner may create through API keys, across all their keys.\n\t * Absent: the process-wide default (`DEFAULT_PROJECT_CREATE_LIMIT`). `null`:\n\t * no limit.\n\t */\n\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t/** Replay store for routes mounted with `idempotent: true`. Absent: the process-wide default. */\n\tidempotency?: ApiIdempotencyStore;\n\t/** Instance display name, used where a record has none. */\n\tinstanceName: string;\n\t/** Where a person manages their API tokens, linked from the new-key email. Host-relative. */\n\tapiTokenSettingsPath: string;\n\t/**\n\t * Drop the host's warm compute client for one server id.\n\t *\n\t * A warm client caches on server `id`, so a rotated URL or key keeps the\n\t * same cache key with stale connection details and never ages out. The\n\t * config-write handlers evict through this rather than importing a cache:\n\t * which cache holds them is the host's decision, and importing one would\n\t * pull a whole solve engine into every consumer.\n\t *\n\t * Defaults to a no-op — a host with no client cache has nothing to evict,\n\t * and the handler must not have to know which kind of host it is running on.\n\t */\n\tevictComputeClient: (id: string) => void;\n\t/**\n\t * Called after every compute-config save, so a host remembering resolved servers\n\t * (`createServerResolver`) reads the config again. Defaults to a no-op.\n\t */\n\tonComputeConfigSaved: () => void;\n\t/**\n\t * Composed services the host supplies.\n\t *\n\t * The named ones are typed because handlers call them — leaving a service\n\t * `unknown` pushes a cast into every call site, and a cast is exactly where\n\t * a second host's differently-shaped service would slip through unnoticed.\n\t * The index signature keeps host-specific extras possible without naming\n\t * them here.\n\t */\n\tservices: {\n\t\tdefinitions?: DefinitionService;\n\t\torgAssets?: OrgAssetService;\n\t} & Record<string, unknown>;\n}\n\n/**\n * Build deps from a resolved `SelvaConfig`, plus whatever services and token\n * codecs the host composed on top. The hoisted fields are aliases into `data`,\n * not copies.\n *\n * `services` stays positional — every existing caller passes it there — and\n * `tokens` arrives in an options object rather than as a third positional, so\n * the two composed bags cannot be swapped at a call site.\n */\nexport function depsFromConfig(\n\tconfig: SelvaConfig,\n\tservices: SelvaDeps['services'] = {},\n\t{\n\t\ttokens = {},\n\t\tuploadLimits,\n\t\tevictComputeClient = () => {},\n\t\tonComputeConfigSaved = () => {},\n\t\tnotifications,\n\t\tinstanceName = 'Selva',\n\t\tapiTokenSettingsPath = '/settings/tokens',\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency\n\t}: {\n\t\ttokens?: SelvaDeps['tokens'];\n\t\tuploadLimits?: Partial<SelvaDeps['uploadLimits']>;\n\t\tevictComputeClient?: SelvaDeps['evictComputeClient'];\n\t\tonComputeConfigSaved?: SelvaDeps['onComputeConfigSaved'];\n\t\tnotifications?: INotificationProvider;\n\t\tinstanceName?: string;\n\t\tapiTokenSettingsPath?: string;\n\t\tapiRateLimiter?: ApiRateLimiter | null;\n\t\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t\tidempotency?: ApiIdempotencyStore;\n\t} = {}\n): SelvaDeps {\n\tconst { data } = config;\n\treturn {\n\t\tauth: config.auth,\n\t\tstorage: config.storage,\n\t\tdata,\n\t\torgs: data.orgs,\n\t\tprojects: data.projects,\n\t\tdefinitionMeta: data.definitions,\n\t\tcomputeServer: data.computeServer,\n\t\tuserProfile: data.userProfile,\n\t\tshareLinks: data.shareLinks,\n\t\tinvites: data.invites,\n\t\tpermissions: data.permissions,\n\t\tplatformProjectGrants: data.platformProjectGrants,\n\t\tevents: config.events ?? new NoopEventSink(),\n\t\tflag: (name) => isFlagEnabled(config, name),\n\t\ttokens,\n\t\t// Same defaults `resolveComputeLimits` applies, repeated rather than\n\t\t// imported: pulling that in would make every host resolving deps also\n\t\t// resolve compute limits from env, which is the coupling this avoids.\n\t\tuploadLimits: {\n\t\t\tmaxDefinitionFileSize: uploadLimits?.maxDefinitionFileSize ?? 50 * 1024 * 1024,\n\t\t\tmaxImageFileSize: uploadLimits?.maxImageFileSize ?? 10 * 1024 * 1024\n\t\t},\n\t\tevictComputeClient,\n\t\tonComputeConfigSaved,\n\t\tnotifications,\n\t\tinstanceName,\n\t\tapiTokenSettingsPath,\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency,\n\t\tservices\n\t};\n}\n","/**\n * The domain errors this package's own handlers raise, folded into the envelope.\n *\n * A host's `mapError` should call this first and add only its own error types.\n * These rules cannot live solely in a host: the handler that throws them ships\n * from here, so a host that forgot one would serve 500 where every other host\n * serves 503 — the same API answering differently depending on who mounted it.\n *\n * Postgres surfaces a unique-constraint name verbatim, which is useless to an\n * end user, so the constraints this package's handlers can trip are translated\n * here rather than left to each host.\n */\n\nimport { ApiError, ApiErrorCode, codeForStatus } from './errors.js';\nimport { ComputeServerUnconfiguredError } from '../compute/errors.js';\nimport { SchemaExtractionError } from '../definitions/schema-extraction.js';\nimport { ProviderError } from '@selvajs/platform';\n\nconst UNIQUE_CONSTRAINT_MESSAGES: Record<string, string> = {\n\tprojects_org_name_unique: 'A project with that name already exists in this organization.',\n\tprojects_org_id_slug_key: 'A project with that name already exists in this organization.',\n\torgs_slug_key: 'An organization with that slug already exists.',\n\tdefinitions_pkey: 'A definition with that ID already exists.'\n};\n\nfunction friendlyConstraintMessage(raw: string): string | null {\n\tfor (const [name, msg] of Object.entries(UNIQUE_CONSTRAINT_MESSAGES)) {\n\t\tif (raw.includes(name)) return msg;\n\t}\n\treturn null;\n}\n\n/**\n * Compute unreachable or serving an unreadable schema is operator-side (503); a\n * schema the parser cannot read is the caller's file (422).\n */\nexport function mapCoreError(err: unknown): ApiError | undefined {\n\tif (err instanceof SchemaExtractionError) {\n\t\treturn err.kind === 'unreachable' || err.kind === 'malformed'\n\t\t\t? new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message)\n\t\t\t: new ApiError(422, ApiErrorCode.UNPROCESSABLE, err.message);\n\t}\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\treturn new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\tif (err instanceof ProviderError) {\n\t\tconst friendly = friendlyConstraintMessage(err.message);\n\t\treturn new ApiError(err.statusCode, codeForStatus(err.statusCode), friendly ?? err.message);\n\t}\n\treturn undefined;\n}\n","/**\n * The SvelteKit binding for the transport-free handlers in `@selvajs/server/api`.\n *\n * The only file in the app that knows both worlds: it turns a `RequestEvent`\n * into an `ApiRequest` and folds this app's domain errors into the shared\n * envelope. A handler mounted through here names no framework, so the same\n * handler runs under Next or Hono behind a sibling adapter roughly this size.\n */\n\nimport { isHttpError, json, type RequestEvent } from '@sveltejs/kit';\nimport { publicUrl } from '#lib/server/origin.js';\nimport {\n\tApiError,\n\tApiErrorCode,\n\tchargeApiRateLimit,\n\tcodeForStatus,\n\tdepsFromConfig,\n\tmapCoreError,\n\trateLimitedResponse,\n\trunHandler,\n\twithRateLimitHeaders,\n\ttype ApiHandler,\n\ttype ApiRequest,\n\ttype RunHandlerOptions,\n\ttype SelvaDeps\n} from '@selvajs/server/api';\nimport {\n\tgetBranding,\n\tgetDefinitionService,\n\tgetNotificationProvider,\n\tgetOrgAssetService\n} from '../providers.server';\nimport { shareLinkCodec } from '../shareLinks/token.server';\nimport { inviteCodec } from '../invites/token.server';\nimport { apiTokenCodec, apiTokenResolutions } from '../apiTokens/token.server';\nimport { MAX_DEFINITION_FILE_SIZE, MAX_IMAGE_FILE_SIZE } from '../computeLimits';\nimport { evictComputeClient } from '../compute/engine.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { apiRateLimiter } from '../computeRateLimit.server';\nimport { signInMaxAgeMs } from '../signInMaxAge.server';\n\n/**\n * This app's own errors, folded into the shared envelope.\n *\n * SvelteKit's `HttpError` is the only one left here — everything else the v1\n * handlers throw ships from `@selvajs/server`, so `mapCoreError` owns those\n * rules and a second host gets the same statuses without copying them.\n */\nexport function mapAppError(err: unknown): ApiError | undefined {\n\t// Access guards in `access.server.ts` throw SvelteKit's error() and must\n\t// keep doing so — page loads share them and need SvelteKit to render the\n\t// failure. Without this branch every guard 403 falls through to the 500\n\t// fallback, a downgrade no type check catches.\n\tif (isHttpError(err)) {\n\t\t// Guards throw `error(status, 'string')`; `apiError` throws the object\n\t\t// form with `fields` (Zod's per-field detail) — both are live, so this\n\t\t// reads the body rather than just the status.\n\t\tconst body = err.body as\n\t\t\t| {\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: ApiErrorCode;\n\t\t\t\t\tfields?: Record<string, string>;\n\t\t\t\t\tdetails?: Record<string, string>;\n\t\t\t }\n\t\t\t| string;\n\t\tif (typeof body === 'string') {\n\t\t\treturn new ApiError(err.status, codeForStatus(err.status), body);\n\t\t}\n\t\treturn new ApiError(\n\t\t\terr.status,\n\t\t\tbody?.code ?? codeForStatus(err.status),\n\t\t\tbody?.message ?? 'Request failed',\n\t\t\tbody?.fields,\n\t\t\tbody?.details\n\t\t);\n\t}\n\treturn mapCoreError(err);\n}\n\n// Providers resolve lazily and memoize, so building deps per request costs a\n// few property reads — no provider is constructed here.\nfunction buildDeps(event: RequestEvent): SelvaDeps {\n\treturn depsFromConfig(\n\t\tevent.locals.providers,\n\t\t{\n\t\t\tdefinitions: getDefinitionService(),\n\t\t\torgAssets: getOrgAssetService()\n\t\t},\n\t\t{\n\t\t\t// Resolved per request, not captured: both codecs re-key on the secret,\n\t\t\t// so a rotated SELVA_HMAC_KEY takes effect without a restart.\n\t\t\ttokens: {\n\t\t\t\tshareLinks: shareLinkCodec(),\n\t\t\t\tinvites: inviteCodec(),\n\t\t\t\tapiTokens: apiTokenCodec(),\n\t\t\t\tsignInMaxAgeMs,\n\t\t\t\tresolutionCache: apiTokenResolutions\n\t\t\t},\n\t\t\t// Passed explicitly — depsFromConfig's defaults would silently ignore\n\t\t\t// this deployment's MAX_*_FILE_SIZE_BYTES.\n\t\t\tuploadLimits: {\n\t\t\t\tmaxDefinitionFileSize: MAX_DEFINITION_FILE_SIZE,\n\t\t\t\tmaxImageFileSize: MAX_IMAGE_FILE_SIZE\n\t\t\t},\n\t\t\t// Cache is keyed on server id; without this a compute-config write\n\t\t\t// leaves a warm client holding a rotated URL or key.\n\t\t\tevictComputeClient,\n\t\t\tonComputeConfigSaved: () => serverResolver.forget(),\n\t\t\tnotifications: getNotificationProvider(),\n\t\t\tinstanceName: getBranding().name,\n\t\t\tapiTokenSettingsPath: '/team/tokens',\n\t\t\t// Module singleton: the limiter must outlive this per-request deps object.\n\t\t\tapiRateLimiter\n\t\t}\n\t);\n}\n\nexport function toApiRequest(event: RequestEvent): ApiRequest {\n\treturn {\n\t\tctx: event.locals.ctx,\n\t\tuser: event.locals.user,\n\t\tprofile: event.locals.profile,\n\t\tlog: event.locals.log,\n\t\tparams: event.params,\n\t\turl: publicUrl(event.url),\n\t\trequest: event.request,\n\t\tdeps: buildDeps(event)\n\t};\n}\n\n/**\n * Mount a transport-free handler as a SvelteKit `RequestHandler`.\n *\n * Routes addressed by a project or definition pass `scopeTarget`, so a key\n * scoped to that project or definition can reach them; solve routes pass\n * `action: 'solve'`; creates pass `idempotent: true`.\n */\nexport function mount(\n\tfallback: string,\n\thandler: ApiHandler,\n\topts: Pick<RunHandlerOptions, 'action' | 'scopeTarget' | 'anyScope' | 'idempotent'> = {}\n) {\n\treturn (event: RequestEvent): Promise<Response> =>\n\t\trunHandler(handler, toApiRequest(event), { fallback, mapError: mapAppError, ...opts });\n}\n\n/**\n * The per-token rate limit for a route that builds its own `Response` instead\n * of going through `mount`: charged before the handler runs, and `RateLimit-*`\n * on every token response, thrown errors included.\n */\nexport function withApiRateLimit<E extends RequestEvent>(\n\thandler: (event: E) => Promise<Response>\n): (event: E) => Promise<Response> {\n\treturn async (event) => {\n\t\tconst verdict = await chargeApiRateLimit(event.locals.ctx, apiRateLimiter);\n\t\tif (verdict && !verdict.allowed) return rateLimitedResponse(verdict);\n\t\ttry {\n\t\t\treturn withRateLimitHeaders(await handler(event), verdict);\n\t\t} catch (err) {\n\t\t\tif (!verdict || !isHttpError(err)) throw err;\n\t\t\treturn withRateLimitHeaders(json(err.body, { status: err.status }), verdict);\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgLA,SAAgB,eACf,QACA,WAAkC,CAAC,GACnC,EACC,SAAS,CAAC,GACV,cACA,2BAA2B,CAAC,GAC5B,6BAA6B,CAAC,GAC9B,eACA,eAAe,SACf,uBAAuB,oBACvB,gBACA,sBACA,gBAYG,CAAC,GACO;CACZ,MAAM,EAAE,SAAS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AC,WAAW,CAAC,YAAY,GAAG,GAAG,MAAM;GACzC,OAAO,qBAAqB,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC,GAAG,OAAO;EAC5E;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"sveltekit.js","names":[],"sources":["../../../../server/src/api/deps.ts","../../../../server/src/api/map-core-error.ts","../../../src/lib/server/api/sveltekit.ts"],"sourcesContent":["/**\n * Everything an API handler talks to, as one injected value.\n *\n * Handlers used to reach module-global getters (`getProjectProvider()`,\n * `getDefinitionService()`, …) from the Selva app's composition root — 77 call\n * sites across the v1 routes. That welded them to one app's boot: a second app\n * on a different provider set could not call them at all.\n *\n * Most fields are sub-stores of `IDataProvider`, so a host that already built a\n * `SelvaConfig` gets them via `depsFromConfig`. `services` stays host-defined:\n * `DefinitionService` and friends are composed rather than resolved, and a host\n * may supply its own.\n */\n\nimport { isFlagEnabled, NoopEventSink } from '@selvajs/platform';\nimport type { DefinitionService } from '../definitions/definition-service.js';\nimport type { OrgAssetService } from '../organizations/org-asset-service.js';\nimport type { TokenCodec } from '../tokens/token-codec.js';\nimport type { ApiTokenCodec } from '../tokens/api-token-codec.js';\nimport type { ApiTokenHolderPolicy } from '../tokens/api-token-holder.js';\nimport type { ApiTokenResolutionCache } from '../http/api-token.js';\nimport type { ApiRateLimiter } from './rate-limit.js';\nimport type { ApiIdempotencyStore } from './idempotency.js';\nimport type {\n\tIAuthProvider,\n\tIDataProvider,\n\tIEventSink,\n\tINotificationProvider,\n\tIStorageProvider,\n\tSelvaConfig,\n\tSelvaFlags\n} from '@selvajs/platform';\n\nexport interface SelvaDeps {\n\tauth: IAuthProvider;\n\tstorage: IStorageProvider;\n\tdata: IDataProvider;\n\t/** `data.orgs` — hoisted because 18 v1 call sites read it directly. */\n\torgs: IDataProvider['orgs'];\n\t/** `data.projects` — 18 call sites. */\n\tprojects: IDataProvider['projects'];\n\t/** `data.definitions` — the definition metadata store. */\n\tdefinitionMeta: IDataProvider['definitions'];\n\tcomputeServer: IDataProvider['computeServer'];\n\tuserProfile: IDataProvider['userProfile'];\n\tshareLinks: IDataProvider['shareLinks'];\n\tinvites: IDataProvider['invites'];\n\tpermissions: IDataProvider['permissions'];\n\tplatformProjectGrants: IDataProvider['platformProjectGrants'];\n\t/**\n\t * Audit sink. Never optional here even though `SelvaConfig.events` is:\n\t * handlers emit escalation events (`project.reclaimed`,\n\t * `org_member.removed_orphaning_projects`) that the audit trail depends on,\n\t * and a handler deciding for itself what a missing sink means is how one of\n\t * them ends up silently unlogged. `depsFromConfig` substitutes\n\t * `NoopEventSink`, which discards explicitly.\n\t */\n\tevents: IEventSink;\n\t/**\n\t * Feature flags, as a predicate rather than a record: an omitted flag must\n\t * read as false, and keeping that in `isFlagEnabled` stops each caller from\n\t * re-deciding what a missing flag means.\n\t */\n\tflag: (name: keyof SelvaFlags) => boolean;\n\t/**\n\t * Token codecs, one per family, keyed by what they mint.\n\t *\n\t * Injected rather than resolved because the codec is built from an\n\t * instance-wide HMAC secret, and reading that secret is the host's job — a\n\t * package that reached for `process.env.SELVA_HMAC_KEY` itself would pin\n\t * every host to one env var name and one way of loading it. Rotating a\n\t * secret invalidates that family's outstanding tokens, so the two families\n\t * are separate values rather than one shared codec.\n\t *\n\t * Optional: a host with no sharing and no invites wires neither. The\n\t * handlers that need one fail loudly if it is absent rather than minting a\n\t * token nobody can verify.\n\t */\n\ttokens: {\n\t\tshareLinks?: TokenCodec;\n\t\tinvites?: TokenCodec;\n\t\t/** Without it, minting answers 503 `API_TOKENS_UNAVAILABLE`. */\n\t\tapiTokens?: ApiTokenCodec;\n\t\t/** Who may mint and use API tokens. Absent: the platform permission `manage_api_tokens`. */\n\t\tmayHoldApiTokens?: ApiTokenHolderPolicy;\n\t\t/** How long one sign-in lasts before minting needs a new one (`resolveSignInMaxAgeMs`). Absent: no limit. */\n\t\tsignInMaxAgeMs?: number;\n\t\t/**\n\t\t * The cache the host hands `resolveApiToken`, so a revoke through these handlers drops\n\t\t * the key from it at once. Absent: nothing to drop.\n\t\t */\n\t\tresolutionCache?: ApiTokenResolutionCache;\n\t};\n\t/**\n\t * Upload caps, in bytes.\n\t *\n\t * Deployment config, so the host resolves them — a package reading its own\n\t * env would pin every host to one variable name. Defaults apply when the\n\t * host says nothing, because a missing cap must not read as \"unlimited\":\n\t * `requireUpload` compares against this number, and `undefined` would let\n\t * any size through.\n\t */\n\tuploadLimits: {\n\t\tmaxDefinitionFileSize: number;\n\t\tmaxImageFileSize: number;\n\t};\n\t/**\n\t * Outbound mail, and the instance name to fall back to when a record has no\n\t * name of its own.\n\t *\n\t * Optional because mail is best-effort by design: an invite row is committed\n\t * before delivery is attempted, and the caller still holds the accept URL to\n\t * share by hand. A host with no mail configured wires nothing and the\n\t * handlers report `not-configured` rather than failing the write.\n\t */\n\tnotifications?: INotificationProvider;\n\t/**\n\t * Per-token request limit `runHandler` charges. Absent: the process-wide\n\t * default (`DEFAULT_API_RATE_LIMIT`). `null`: no limit. A host's own limiter\n\t * must outlive the request, since deps are rebuilt per request.\n\t */\n\tapiRateLimiter?: ApiRateLimiter | null;\n\t/**\n\t * Projects one owner may create through API keys, across all their keys.\n\t * Absent: the process-wide default (`DEFAULT_PROJECT_CREATE_LIMIT`). `null`:\n\t * no limit.\n\t */\n\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t/** Replay store for routes mounted with `idempotent: true`. Absent: the process-wide default. */\n\tidempotency?: ApiIdempotencyStore;\n\t/** Instance display name, used where a record has none. */\n\tinstanceName: string;\n\t/** Where a person manages their API tokens, linked from the new-key email. Host-relative. */\n\tapiTokenSettingsPath: string;\n\t/**\n\t * Drop the host's warm compute client for one server id.\n\t *\n\t * A warm client caches on server `id`, so a rotated URL or key keeps the\n\t * same cache key with stale connection details and never ages out. The\n\t * config-write handlers evict through this rather than importing a cache:\n\t * which cache holds them is the host's decision, and importing one would\n\t * pull a whole solve engine into every consumer.\n\t *\n\t * Defaults to a no-op — a host with no client cache has nothing to evict,\n\t * and the handler must not have to know which kind of host it is running on.\n\t */\n\tevictComputeClient: (id: string) => void;\n\t/**\n\t * Called after every compute-config save, so a host remembering resolved servers\n\t * (`createServerResolver`) reads the config again. Defaults to a no-op.\n\t */\n\tonComputeConfigSaved: () => void;\n\t/**\n\t * Composed services the host supplies.\n\t *\n\t * The named ones are typed because handlers call them — leaving a service\n\t * `unknown` pushes a cast into every call site, and a cast is exactly where\n\t * a second host's differently-shaped service would slip through unnoticed.\n\t * The index signature keeps host-specific extras possible without naming\n\t * them here.\n\t */\n\tservices: {\n\t\tdefinitions?: DefinitionService;\n\t\torgAssets?: OrgAssetService;\n\t} & Record<string, unknown>;\n}\n\n/**\n * Build deps from a resolved `SelvaConfig`, plus whatever services and token\n * codecs the host composed on top. The hoisted fields are aliases into `data`,\n * not copies.\n *\n * `services` stays positional — every existing caller passes it there — and\n * `tokens` arrives in an options object rather than as a third positional, so\n * the two composed bags cannot be swapped at a call site.\n */\nexport function depsFromConfig(\n\tconfig: SelvaConfig,\n\tservices: SelvaDeps['services'] = {},\n\t{\n\t\ttokens = {},\n\t\tuploadLimits,\n\t\tevictComputeClient = () => {},\n\t\tonComputeConfigSaved = () => {},\n\t\tnotifications,\n\t\tinstanceName = 'Selva',\n\t\tapiTokenSettingsPath = '/settings/tokens',\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency\n\t}: {\n\t\ttokens?: SelvaDeps['tokens'];\n\t\tuploadLimits?: Partial<SelvaDeps['uploadLimits']>;\n\t\tevictComputeClient?: SelvaDeps['evictComputeClient'];\n\t\tonComputeConfigSaved?: SelvaDeps['onComputeConfigSaved'];\n\t\tnotifications?: INotificationProvider;\n\t\tinstanceName?: string;\n\t\tapiTokenSettingsPath?: string;\n\t\tapiRateLimiter?: ApiRateLimiter | null;\n\t\tprojectCreateLimiter?: ApiRateLimiter | null;\n\t\tidempotency?: ApiIdempotencyStore;\n\t} = {}\n): SelvaDeps {\n\tconst { data } = config;\n\treturn {\n\t\tauth: config.auth,\n\t\tstorage: config.storage,\n\t\tdata,\n\t\torgs: data.orgs,\n\t\tprojects: data.projects,\n\t\tdefinitionMeta: data.definitions,\n\t\tcomputeServer: data.computeServer,\n\t\tuserProfile: data.userProfile,\n\t\tshareLinks: data.shareLinks,\n\t\tinvites: data.invites,\n\t\tpermissions: data.permissions,\n\t\tplatformProjectGrants: data.platformProjectGrants,\n\t\tevents: config.events ?? new NoopEventSink(),\n\t\tflag: (name) => isFlagEnabled(config, name),\n\t\ttokens,\n\t\t// Same defaults `resolveComputeLimits` applies, repeated rather than\n\t\t// imported: pulling that in would make every host resolving deps also\n\t\t// resolve compute limits from env, which is the coupling this avoids.\n\t\tuploadLimits: {\n\t\t\tmaxDefinitionFileSize: uploadLimits?.maxDefinitionFileSize ?? 50 * 1024 * 1024,\n\t\t\tmaxImageFileSize: uploadLimits?.maxImageFileSize ?? 10 * 1024 * 1024\n\t\t},\n\t\tevictComputeClient,\n\t\tonComputeConfigSaved,\n\t\tnotifications,\n\t\tinstanceName,\n\t\tapiTokenSettingsPath,\n\t\tapiRateLimiter,\n\t\tprojectCreateLimiter,\n\t\tidempotency,\n\t\tservices\n\t};\n}\n","/**\n * The domain errors this package's own handlers raise, folded into the envelope.\n *\n * A host's `mapError` should call this first and add only its own error types.\n * These rules cannot live solely in a host: the handler that throws them ships\n * from here, so a host that forgot one would serve 500 where every other host\n * serves 503 — the same API answering differently depending on who mounted it.\n *\n * Postgres surfaces a unique-constraint name verbatim, which is useless to an\n * end user, so the constraints this package's handlers can trip are translated\n * here rather than left to each host.\n */\n\nimport { ApiError, ApiErrorCode, codeForStatus } from './errors.js';\nimport { ComputeServerUnconfiguredError } from '../compute/errors.js';\nimport { SchemaExtractionError } from '../definitions/schema-extraction.js';\nimport { ProviderError } from '@selvajs/platform';\n\nconst UNIQUE_CONSTRAINT_MESSAGES: Record<string, string> = {\n\tprojects_org_name_unique: 'A project with that name already exists in this organization.',\n\tprojects_org_id_slug_key: 'A project with that name already exists in this organization.',\n\torgs_slug_key: 'An organization with that slug already exists.',\n\tdefinitions_pkey: 'A definition with that ID already exists.'\n};\n\nfunction friendlyConstraintMessage(raw: string): string | null {\n\tfor (const [name, msg] of Object.entries(UNIQUE_CONSTRAINT_MESSAGES)) {\n\t\tif (raw.includes(name)) return msg;\n\t}\n\treturn null;\n}\n\n/**\n * Compute unreachable or serving an unreadable schema is operator-side (503); a\n * schema the parser cannot read is the caller's file (422).\n */\nexport function mapCoreError(err: unknown): ApiError | undefined {\n\tif (err instanceof SchemaExtractionError) {\n\t\treturn err.kind === 'unreachable' || err.kind === 'malformed'\n\t\t\t? new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message)\n\t\t\t: new ApiError(422, ApiErrorCode.UNPROCESSABLE, err.message);\n\t}\n\tif (err instanceof ComputeServerUnconfiguredError) {\n\t\treturn new ApiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, err.message);\n\t}\n\tif (err instanceof ProviderError) {\n\t\tconst friendly = friendlyConstraintMessage(err.message);\n\t\treturn new ApiError(err.statusCode, codeForStatus(err.statusCode), friendly ?? err.message);\n\t}\n\treturn undefined;\n}\n","/**\n * The SvelteKit binding for the transport-free handlers in `@selvajs/server/api`.\n *\n * The only file in the app that knows both worlds: it turns a `RequestEvent`\n * into an `ApiRequest` and folds this app's domain errors into the shared\n * envelope. A handler mounted through here names no framework, so the same\n * handler runs under Next or Hono behind a sibling adapter roughly this size.\n */\n\nimport { isHttpError, json, type RequestEvent } from '@sveltejs/kit';\nimport { publicUrl } from '#lib/server/origin.js';\nimport {\n\tApiError,\n\tApiErrorCode,\n\tchargeApiRateLimit,\n\tcodeForStatus,\n\tdepsFromConfig,\n\tmapCoreError,\n\trateLimitedResponse,\n\trunHandler,\n\twithRateLimitHeaders,\n\ttype ApiHandler,\n\ttype ApiRequest,\n\ttype RunHandlerOptions,\n\ttype SelvaDeps\n} from '@selvajs/server/api';\nimport {\n\tgetBranding,\n\tgetDefinitionService,\n\tgetNotificationProvider,\n\tgetOrgAssetService\n} from '../providers.server';\nimport { shareLinkCodec } from '../shareLinks/token.server';\nimport { inviteCodec } from '../invites/token.server';\nimport { apiTokenCodec, apiTokenResolutions } from '../apiTokens/token.server';\nimport { MAX_DEFINITION_FILE_SIZE, MAX_IMAGE_FILE_SIZE } from '../computeLimits';\nimport { evictComputeClient } from '../compute/engine.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { apiRateLimiter } from '../computeRateLimit.server';\nimport { signInMaxAgeMs } from '../signInMaxAge.server';\n\n/**\n * This app's own errors, folded into the shared envelope.\n *\n * SvelteKit's `HttpError` is the only one left here — everything else the v1\n * handlers throw ships from `@selvajs/server`, so `mapCoreError` owns those\n * rules and a second host gets the same statuses without copying them.\n */\nexport function mapAppError(err: unknown): ApiError | undefined {\n\t// Access guards in `access.server.ts` throw SvelteKit's error() and must\n\t// keep doing so — page loads share them and need SvelteKit to render the\n\t// failure. Without this branch every guard 403 falls through to the 500\n\t// fallback, a downgrade no type check catches.\n\tif (isHttpError(err)) {\n\t\t// Guards throw `error(status, 'string')`; `apiError` throws the object\n\t\t// form with `fields` (Zod's per-field detail) — both are live, so this\n\t\t// reads the body rather than just the status.\n\t\tconst body = err.body as\n\t\t\t| {\n\t\t\t\t\tmessage?: string;\n\t\t\t\t\tcode?: ApiErrorCode;\n\t\t\t\t\tfields?: Record<string, string>;\n\t\t\t\t\tdetails?: Record<string, string>;\n\t\t\t }\n\t\t\t| string;\n\t\tif (typeof body === 'string') {\n\t\t\treturn new ApiError(err.status, codeForStatus(err.status), body);\n\t\t}\n\t\treturn new ApiError(\n\t\t\terr.status,\n\t\t\tbody?.code ?? codeForStatus(err.status),\n\t\t\tbody?.message ?? 'Request failed',\n\t\t\tbody?.fields,\n\t\t\tbody?.details\n\t\t);\n\t}\n\treturn mapCoreError(err);\n}\n\n// Providers resolve lazily and memoize, so building deps per request costs a\n// few property reads — no provider is constructed here.\nfunction buildDeps(event: RequestEvent): SelvaDeps {\n\treturn depsFromConfig(\n\t\tevent.locals.providers,\n\t\t{\n\t\t\tdefinitions: getDefinitionService(),\n\t\t\torgAssets: getOrgAssetService()\n\t\t},\n\t\t{\n\t\t\t// Resolved per request, not captured: both codecs re-key on the secret,\n\t\t\t// so a rotated SELVA_HMAC_KEY takes effect without a restart.\n\t\t\ttokens: {\n\t\t\t\tshareLinks: shareLinkCodec(),\n\t\t\t\tinvites: inviteCodec(),\n\t\t\t\tapiTokens: apiTokenCodec(),\n\t\t\t\tsignInMaxAgeMs,\n\t\t\t\tresolutionCache: apiTokenResolutions\n\t\t\t},\n\t\t\t// Passed explicitly — depsFromConfig's defaults would silently ignore\n\t\t\t// this deployment's MAX_*_FILE_SIZE_BYTES.\n\t\t\tuploadLimits: {\n\t\t\t\tmaxDefinitionFileSize: MAX_DEFINITION_FILE_SIZE,\n\t\t\t\tmaxImageFileSize: MAX_IMAGE_FILE_SIZE\n\t\t\t},\n\t\t\t// Cache is keyed on server id; without this a compute-config write\n\t\t\t// leaves a warm client holding a rotated URL or key.\n\t\t\tevictComputeClient,\n\t\t\tonComputeConfigSaved: () => serverResolver.forget(),\n\t\t\tnotifications: getNotificationProvider(),\n\t\t\tinstanceName: getBranding().name,\n\t\t\tapiTokenSettingsPath: '/team/tokens',\n\t\t\t// Module singleton: the limiter must outlive this per-request deps object.\n\t\t\tapiRateLimiter\n\t\t}\n\t);\n}\n\nexport function toApiRequest(event: RequestEvent): ApiRequest {\n\treturn {\n\t\tctx: event.locals.ctx,\n\t\tuser: event.locals.user,\n\t\tprofile: event.locals.profile,\n\t\tlog: event.locals.log,\n\t\tparams: event.params,\n\t\turl: publicUrl(event.url),\n\t\trequest: event.request,\n\t\tdeps: buildDeps(event)\n\t};\n}\n\n/**\n * Mount a transport-free handler as a SvelteKit `RequestHandler`.\n *\n * Routes addressed by a project or definition pass `scopeTarget`, so a key\n * scoped to that project or definition can reach them; solve routes pass\n * `action: 'solve'`; creates pass `idempotent: true`.\n */\nexport function mount(\n\tfallback: string,\n\thandler: ApiHandler,\n\topts: Pick<RunHandlerOptions, 'action' | 'scopeTarget' | 'anyScope' | 'idempotent'> = {}\n) {\n\treturn (event: RequestEvent): Promise<Response> =>\n\t\trunHandler(handler, toApiRequest(event), { fallback, mapError: mapAppError, ...opts });\n}\n\n/**\n * The per-token rate limit for a route that builds its own `Response` instead\n * of going through `mount`: charged before the handler runs, and `RateLimit-*`\n * on every token response, thrown errors included.\n */\nexport function withApiRateLimit<E extends RequestEvent>(\n\thandler: (event: E) => Promise<Response>\n): (event: E) => Promise<Response> {\n\treturn async (event) => {\n\t\tconst verdict = await chargeApiRateLimit(event.locals.ctx, apiRateLimiter);\n\t\tif (verdict && !verdict.allowed) return rateLimitedResponse(verdict);\n\t\ttry {\n\t\t\treturn withRateLimitHeaders(await handler(event), verdict);\n\t\t} catch (err) {\n\t\t\tif (!verdict || !isHttpError(err)) throw err;\n\t\t\treturn withRateLimitHeaders(json(err.body, { status: err.status }), verdict);\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgLA,SAAgB,eACf,QACA,WAAkC,CAAC,GACnC,EACC,SAAS,CAAC,GACV,cACA,2BAA2B,CAAC,GAC5B,6BAA6B,CAAC,GAC9B,eACA,eAAe,SACf,uBAAuB,oBACvB,gBACA,sBACA,gBAYG,CAAC,GACO;CACZ,MAAM,EAAE,SAAS;CACjB,OAAO;EACN,MAAM,OAAO;EACb,SAAS,OAAO;EAChB;EACA,MAAM,KAAK;EACX,UAAU,KAAK;EACf,gBAAgB,KAAK;EACrB,eAAe,KAAK;EACpB,aAAa,KAAK;EAClB,YAAY,KAAK;EACjB,SAAS,KAAK;EACd,aAAa,KAAK;EAClB,uBAAuB,KAAK;EAC5B,QAAQ,OAAO,UAAU,IAAI,cAAc;EAC3C,OAAO,SAAS,cAAc,QAAQ,IAAI;EAC1C;EAIA,cAAc;GACb,uBAAuB,cAAc,yBAAyB;GAC9D,kBAAkB,cAAc,oBAAoB;EACrD;EACA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B,WAAW,cAAc;GACzB;GACA,iBAAiB;EAClB;EAGA,cAAc;GACb,uBAAuB;GACvB,kBAAkB;EACnB;EAGA;EACA,4BAA4B,eAAe,OAAO;EAClD,eAAe,wBAAwB;EACvC,cAAc,YAAY,CAAC,CAAC;EAC5B,sBAAsB;EAEtB;CACD,CACD;AACD;AAEA,SAAgB,aAAa,OAAiC;CAC7D,OAAO;EACN,KAAK,MAAM,OAAO;EAClB,MAAM,MAAM,OAAO;EACnB,SAAS,MAAM,OAAO;EACtB,KAAK,MAAM,OAAO;EAClB,QAAQ,MAAM;EACd,KAAK,UAAU,MAAM,GAAG;EACxB,SAAS,MAAM;EACf,MAAM,UAAU,KAAK;CACtB;AACD;;;;;;;;AASA,SAAgB,MACf,UACA,SACA,OAAsF,CAAC,GACtF;CACD,QAAQ,UACP,WAAW,SAAS,aAAa,KAAK,GAAG;EAAE;EAAU,UAAU;EAAa,GAAG;CAAK,CAAC;AACvF;;;;;;AAOA,SAAgB,iBACf,SACkC;CAClC,OAAO,OAAO,UAAU;EACvB,MAAM,UAAU,MAAM,mBAAmB,MAAM,OAAO,KAAK,cAAc;EACzE,IAAI,WAAW,CAAC,QAAQ,SAAS,OAAO,oBAAoB,OAAO;EACnE,IAAI;GACH,OAAO,qBAAqB,MAAM,QAAQ,KAAK,GAAG,OAAO;EAC1D,SAAS,KAAK;GACb,IAAI,CAAC,WAAW,CAAC,YAAY,GAAG,GAAG,MAAM;GACzC,OAAO,qBAAqB,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC,GAAG,OAAO;EAC5E;CACD;AACD"}
|
|
@@ -61,6 +61,17 @@ function deriveOutcome(exitCode, logs) {
|
|
|
61
61
|
from,
|
|
62
62
|
to
|
|
63
63
|
};
|
|
64
|
+
if (exitCode === 10 || has(logs, "DATA_FORMAT:")) {
|
|
65
|
+
const target = firstMatch(logs, /reads data format (\d+),/);
|
|
66
|
+
const installed = firstMatch(logs, /this deployment is on format (\d+)\./);
|
|
67
|
+
return {
|
|
68
|
+
severity: "warning",
|
|
69
|
+
title: `Update cancelled — ${to ?? "the target version"} cannot read this deployment's data. The app is untouched.`,
|
|
70
|
+
detail: (target && installed ? `It reads data format ${target}; this deployment is on format ${installed}. ` : "") + "Installing it would leave stored data, such as Compute API keys, unreadable. Switch the release channel back to stay on the installed version. To go back anyway, follow \"Going back to an older release\" in the admin guide.",
|
|
71
|
+
from,
|
|
72
|
+
to
|
|
73
|
+
};
|
|
74
|
+
}
|
|
64
75
|
if (exitCode === 8 || has(logs, "PM2_SKEW")) {
|
|
65
76
|
const daemon = firstMatch(logs, /daemon \(v(\d+\.\d+\.\d+)\)/);
|
|
66
77
|
const local = firstMatch(logs, /deployment's pm2 \(v(\d+\.\d+\.\d+)\)/);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update-outcome.js","names":[],"sources":["../../../src/lib/update-outcome.ts"],"sourcesContent":["// ============================================================================\n// Update-outcome derivation\n// ============================================================================\n//\n// The update runner (admin/api/system/update/+server.ts) emits structured log\n// lines and a small set of meaningful exit codes; `deriveOutcome` turns those\n// into a severity an operator can act on without reading the log. Ranking:\n// anything that leaves the app DOWN is `critical`; a safe rollback is\n// `warning`, not an error, because the site is still serving.\n\nexport type OutcomeSeverity = 'success' | 'info' | 'warning' | 'critical' | 'pending';\n\n/**\n * Synthetic exit code for a run that never reported one — the SSE handler's\n * 15-minute group-kill, or the reconciler giving up on a missing [EXIT] marker.\n * Outside the 0-255 range a real process can produce, so it can't collide.\n */\nexport const TIMED_OUT = -2;\n\nexport interface UpdateOutcome {\n\tseverity: OutcomeSeverity;\n\t/** Must be unambiguous about app up/down state. */\n\ttitle: string;\n\t/** What to do next when something is off. */\n\tdetail?: string;\n\tfrom?: string;\n\tto?: string;\n}\n\nfunction firstMatch(logs: string, re: RegExp): string | undefined {\n\tconst m = re.exec(logs);\n\treturn m ? m[1] : undefined;\n}\n\nfunction parseVersions(logs: string): { from?: string; to?: string } {\n\t// Pre-flight transition line, printed before npm runs — the only source of a\n\t// target version when the update fails early or is a no-op, e.g.\n\t// \"[INFO] Target (beta): 4.2.0 → 4.2.1-beta.1\". `Available:` is the\n\t// pre-channel spelling, kept so logs from an older runner still parse.\n\tconst version = String.raw`\\d+\\.\\d+\\.\\d+[^\\s]*`;\n\tconst transition = new RegExp(\n\t\tString.raw`(?:Target \\([^)]*\\)|Available):\\s*(${version})\\s*(?:→|->)\\s*(${version})`\n\t);\n\tconst arrow = transition.exec(logs);\n\n\t// The post-install lines are authoritative for what actually landed — prefer\n\t// them over the pre-flight target, which is only ever an intent.\n\tconst from = firstMatch(logs, /Current @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[1];\n\tconst to = firstMatch(logs, /New @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[2];\n\treturn { from, to };\n}\n\nfunction has(logs: string, needle: string): boolean {\n\treturn logs.includes(needle);\n}\n\nexport function deriveOutcome(exitCode: number | null, logs: string): UpdateOutcome {\n\tconst { from, to } = parseVersions(logs);\n\n\tif (exitCode === null) {\n\t\treturn { severity: 'pending', title: 'Update in progress…' };\n\t}\n\n\t// --- Critical: app is or may be DOWN. Rank these first. -------------------\n\tif (\n\t\texitCode === 6 ||\n\t\thas(logs, 'Manual recovery required') ||\n\t\thas(logs, 'manual intervention required')\n\t) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed AND rollback failed — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'Both the new version and the rollback failed their health check. ' +\n\t\t\t\t'SSH into the server and run: `pm2 logs selva-compute`, then ' +\n\t\t\t\t'`pm2 start ecosystem.config.cjs` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The SSE handler's 15-minute group-kill, and the reconciler's own poll cap.\n\t// Neither is an exit code the runner chose, so they carry no [EXIT] marker.\n\tif (exitCode === TIMED_OUT) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'App did not come back online within 15 minutes',\n\t\t\tdetail:\n\t\t\t\t'The update may still be finishing in the background, or the new ' +\n\t\t\t\t'process is crash-looping. Check `pm2 logs selva-compute`. Do not ' +\n\t\t\t\t're-run the update until you have confirmed the current state.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 4: the rollback's own npm install failed, so node_modules is\n\t// half-written and the EXIT trap's restart is the only thing that may have\n\t// brought the app back. Same urgency as a failed rollback restart.\n\tif (exitCode === 4) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed and the rollback could not reinstall — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'The previous version could not be restored from npm. SSH into the ' +\n\t\t\t\t'server and run `pm2 logs selva-compute`; if the app is down, reinstall ' +\n\t\t\t\t'explicitly with `npm install --prefer-online @selvajs/cli@<version> ' +\n\t\t\t\t'@selvajs/selva@<version>` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 3: unhealthy with no recorded prior version, so no rollback was even\n\t// attempted. The EXIT trap tried to restart whatever is on disk.\n\tif (exitCode === 3) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed its health check and could not be rolled back automatically',\n\t\t\tdetail:\n\t\t\t\t'No prior version was recorded, so the previous build could not be ' +\n\t\t\t\t'restored. Check `pm2 logs selva-compute` to confirm whether the app ' +\n\t\t\t\t'came back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// Killed mid-run (128+signal). Nothing was installed, and whether the app\n\t// came back depends on how far the EXIT trap got before it died too. Rank\n\t// with the criticals: an unattended half-update is worse than a clean\n\t// failure.\n\tif (exitCode === 143 || exitCode === 130 || exitCode === 129 || has(logs, 'KILLED')) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update was killed before it finished — nothing was installed',\n\t\t\tdetail:\n\t\t\t\t'The runner was terminated mid-update, most often by a systemd-supervised ' +\n\t\t\t\t'PM2 restarting its whole control group. The version on disk is unchanged. ' +\n\t\t\t\t'Check `pm2 logs selva-compute` and confirm the app is online before retrying; ' +\n\t\t\t\t'if a global pm2 owns the daemon, reconcile that first.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Warning: update did not fully succeed, but the app IS up. ------------\n\t// Aborted at the systemd guard, before `pm2 update` could recycle the\n\t// daemon and take this runner down with it.\n\tif (exitCode === 9 || has(logs, 'SYSTEMD_PM2')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — PM2 needs a resync that only a shell can do safely. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t\"This deployment's PM2 runs under systemd, where `pm2 update` restarts the \" +\n\t\t\t\t'unit and kills the update mid-run. Nothing was installed and the app is ' +\n\t\t\t\t'still serving. SSH in and run `./node_modules/.bin/pm2 update` from the ' +\n\t\t\t\t'deployment directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the pm2 skew check, before anything was stopped — nothing was\n\t// installed and the app never went down.\n\tif (exitCode === 8 || has(logs, 'PM2_SKEW')) {\n\t\tconst daemon = firstMatch(logs, /daemon \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\tconst local = firstMatch(logs, /deployment's pm2 \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\tdaemon && local\n\t\t\t\t\t? `Update cancelled — a global PM2 (v${daemon}) owns the daemon, not this deployment's (v${local}). The app is untouched.`\n\t\t\t\t\t: 'Update cancelled — a conflicting global PM2 owns the daemon. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t'Resyncing would have downgraded the daemon and dropped its process ' +\n\t\t\t\t'table, so the update stopped before taking the app down. On the server: ' +\n\t\t\t\t'`which -a pm2`, `pm2 -v`, `pm2 ping` — remove or align the global pm2, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// A rollback whose cause is the DATABASE, not the release. Ranked ahead of\n\t// the generic rollback case: \"review the log before retrying\" is actively\n\t// misleading here, because the log holds nothing about the new version —\n\t// it is fine, and retrying without touching the database repeats verbatim.\n\tif (has(logs, 'SCHEMA_SKEW')) {\n\t\tconst expected = firstMatch(logs, /expects database migration head (\\S+?),/);\n\t\tconst actual = firstMatch(logs, /this database is at (\\S+?)\\./);\n\t\tconst skew =\n\t\t\texpected && actual ? ` The database is at ${actual}; ${to ?? 'it'} needs ${expected}.` : '';\n\t\t// `latest` is the stable line, which ships none of a beta's migrations.\n\t\tconst providerTag =\n\t\t\tfirstMatch(logs, /@selvajs\\/supabase-provider@([\\w.-]+)/) ??\n\t\t\t(has(logs, 'channel: beta') ? 'beta' : 'latest');\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — the database migrations for ${to ?? 'the new version'} have not been applied.${skew} The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'Nothing is wrong with the new version. Selva does not apply migrations ' +\n\t\t\t\t'during an update, because they cannot be rolled back — auto-migrating ' +\n\t\t\t\t'and then rolling the code back would leave the app and database on ' +\n\t\t\t\t'different heads. Apply them on the server, then re-run this update: ' +\n\t\t\t\t`\\`npm install --prefer-online @selvajs/supabase-provider@${providerTag}\\`, then ` +\n\t\t\t\t'`npx selva-supabase`, then `npx supabase db push`. The provider install ' +\n\t\t\t\t'is not optional — the migration SQL ships inside that package, and the ' +\n\t\t\t\t'update only moves @selvajs/cli and @selvajs/selva, so a sync without it ' +\n\t\t\t\t'copies nothing and the push reports \"up to date\" having done nothing. ' +\n\t\t\t\t'Retrying without this will fail in exactly the same way.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Same shape: the rollback was caused by host configuration, not the release.\n\tif (has(logs, 'AT_REST_SECRETS')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — stored compute server keys do not decrypt under this host's SELVA_AT_REST_KEY. The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'This is a configuration problem on the server, not a fault in the new ' +\n\t\t\t\t'version, so retrying alone will fail identically. Re-enter the affected ' +\n\t\t\t\t'keys at /admin/compute, or restore the SELVA_AT_REST_KEY the values were ' +\n\t\t\t\t'encrypted with, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (exitCode === 5 || has(logs, 'Rolled back')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update failed — safely rolled back${from ? ` to ${from}` : ''}. The app is online.`,\n\t\t\tdetail:\n\t\t\t\t'The new version failed its health check, so the previous version ' +\n\t\t\t\t'was restored and is serving normally. Review the log below for why ' +\n\t\t\t\t'the new version failed before retrying.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The install completed and the app is up, but on a Node the release doesn't\n\t// support. The health probe passes (it exercises nothing version-specific),\n\t// so this would otherwise read as a clean success right up until a real\n\t// request hits a newer API and throws (issue #176).\n\tif (has(logs, 'ENGINE_MISMATCH') || has(logs, 'EBADENGINE')) {\n\t\tconst required = firstMatch(logs, /requires Node ([^\\s]+(?:\\s*[<>=]+\\s*[\\d.]+)*)/);\n\t\tconst running = firstMatch(logs, /this host runs v?(\\d+\\.\\d+\\.\\d+)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: running\n\t\t\t\t? `Updated${to ? ` to ${to}` : ''}, but this release needs Node ${required ?? '(newer)'} — the host runs v${running}. Expect runtime failures.`\n\t\t\t\t: `Updated${to ? ` to ${to}` : ''}, but this release requires a newer Node than the host provides. Expect runtime failures.`,\n\t\t\tdetail:\n\t\t\t\t'npm installed it anyway (engine-strict is off) and the health check ' +\n\t\t\t\t'passed, but it does not exercise the newer APIs — routes that do will ' +\n\t\t\t\t'throw at request time. Upgrade Node on the server, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The runner moved pm2 to the release's pin but could not swap the daemon\n\t// (refused under systemd, or `pm2 update` failed). The app runs; the next\n\t// pm2 command warns about the skew until someone runs the swap by hand.\n\tif (has(logs, 'PM2_RESYNC_NEEDED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but the pm2 daemon still runs the old pm2.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online. On the server, run `npx pm2 update` in the deployment ' +\n\t\t\t\t'directory, let it finish, then check `npx pm2 list` shows selva-compute online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'PM2_PIN_FAILED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but pm2 stayed on the previous version.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online on the old pm2. On the server, run `npx selva migrate` in ' +\n\t\t\t\t'the deployment directory to move it to the pinned version.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'npm cache may be stale') || has(logs, 'No version change')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: 'No version change — npm installed the same version.',\n\t\t\tdetail:\n\t\t\t\t'Your npm cache may be stale. On the server: `npm cache clean --force`, ' +\n\t\t\t\t'remove node_modules + package-lock.json, then `npm install --prefer-online`.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Success variants -----------------------------------------------------\n\tif (exitCode === 0) {\n\t\t// \"Already on the 'beta' channel version (4.2.0)\" — the channel name is\n\t\t// interpolated, so match the stable prefix rather than a whole line.\n\t\tif (has(logs, 'Already on the') || has(logs, 'Nothing to do')) {\n\t\t\treturn {\n\t\t\t\tseverity: 'info',\n\t\t\t\ttitle: `Already up to date${from ? ` (${from})` : ''} — nothing to install.`,\n\t\t\t\tdetail: 'No changes were made and the app was not restarted.',\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (from && to && from !== to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Updated ${from} → ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Update complete — now on ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tseverity: 'success',\n\t\t\ttitle: 'Update completed and the app is back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Anything else: a non-zero exit we don't have a named case for. -------\n\t// Be explicit that we couldn't classify it rather than implying success.\n\treturn {\n\t\tseverity: 'critical',\n\t\ttitle: `Update failed (exit code ${exitCode}).`,\n\t\tdetail:\n\t\t\t'The update did not complete cleanly. Review the log below, and check ' +\n\t\t\t'`pm2 logs selva-compute` to confirm whether the app is currently online.',\n\t\tfrom,\n\t\tto\n\t};\n}\n"],"mappings":"AA6BA,SAAS,WAAW,MAAc,IAAgC;CACjE,MAAM,IAAI,GAAG,KAAK,IAAI;CACtB,OAAO,IAAI,EAAE,KAAK,KAAA;AACnB;AAEA,SAAS,cAAc,MAA8C;CAKpE,MAAM,UAAU,OAAO,GAAG;CAI1B,MAAM,QAAQ,IAHS,OACtB,OAAO,GAAG,sCAAsC,QAAQ,kBAAkB,QAAQ,EAErE,CAAA,CAAW,KAAK,IAAI;CAMlC,OAAO;EAAE,MAFI,WAAW,MAAM,oDAAoD,KAAK,QAAQ;EAEhF,IADJ,WAAW,MAAM,gDAAgD,KAAK,QAAQ;CACvE;AACnB;AAEA,SAAS,IAAI,MAAc,QAAyB;CACnD,OAAO,KAAK,SAAS,MAAM;AAC5B;AAEA,SAAgB,cAA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;GACR;GACA;EACD;EAED,IAAI,QAAQ,MAAM,SAAS,IAC1B,OAAO;GACN,UAAU;GACV,OAAO,WAAW,KAAK,KAAK,GAAG;GAC/B;GACA;EACD;EAED,IAAI,IACH,OAAO;GACN,UAAU;GACV,OAAO,4BAA4B,GAAG;GACtC;GACA;EACD;EAED,OAAO;GACN,UAAU;GACV,OAAO;GACP;GACA;EACD;CACD;CAIA,OAAO;EACN,UAAU;EACV,OAAO,4BAA4B,SAAS;EAC5C,QACC;EAED;EACA;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"update-outcome.js","names":[],"sources":["../../../src/lib/update-outcome.ts"],"sourcesContent":["// ============================================================================\n// Update-outcome derivation\n// ============================================================================\n//\n// The update runner (admin/api/system/update/+server.ts) emits structured log\n// lines and a small set of meaningful exit codes; `deriveOutcome` turns those\n// into a severity an operator can act on without reading the log. Ranking:\n// anything that leaves the app DOWN is `critical`; a safe rollback is\n// `warning`, not an error, because the site is still serving.\n\nexport type OutcomeSeverity = 'success' | 'info' | 'warning' | 'critical' | 'pending';\n\n/**\n * Synthetic exit code for a run that never reported one — the SSE handler's\n * 15-minute group-kill, or the reconciler giving up on a missing [EXIT] marker.\n * Outside the 0-255 range a real process can produce, so it can't collide.\n */\nexport const TIMED_OUT = -2;\n\nexport interface UpdateOutcome {\n\tseverity: OutcomeSeverity;\n\t/** Must be unambiguous about app up/down state. */\n\ttitle: string;\n\t/** What to do next when something is off. */\n\tdetail?: string;\n\tfrom?: string;\n\tto?: string;\n}\n\nfunction firstMatch(logs: string, re: RegExp): string | undefined {\n\tconst m = re.exec(logs);\n\treturn m ? m[1] : undefined;\n}\n\nfunction parseVersions(logs: string): { from?: string; to?: string } {\n\t// Pre-flight transition line, printed before npm runs — the only source of a\n\t// target version when the update fails early or is a no-op, e.g.\n\t// \"[INFO] Target (beta): 4.2.0 → 4.2.1-beta.1\". `Available:` is the\n\t// pre-channel spelling, kept so logs from an older runner still parse.\n\tconst version = String.raw`\\d+\\.\\d+\\.\\d+[^\\s]*`;\n\tconst transition = new RegExp(\n\t\tString.raw`(?:Target \\([^)]*\\)|Available):\\s*(${version})\\s*(?:→|->)\\s*(${version})`\n\t);\n\tconst arrow = transition.exec(logs);\n\n\t// The post-install lines are authoritative for what actually landed — prefer\n\t// them over the pre-flight target, which is only ever an intent.\n\tconst from = firstMatch(logs, /Current @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[1];\n\tconst to = firstMatch(logs, /New @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[2];\n\treturn { from, to };\n}\n\nfunction has(logs: string, needle: string): boolean {\n\treturn logs.includes(needle);\n}\n\nexport function deriveOutcome(exitCode: number | null, logs: string): UpdateOutcome {\n\tconst { from, to } = parseVersions(logs);\n\n\tif (exitCode === null) {\n\t\treturn { severity: 'pending', title: 'Update in progress…' };\n\t}\n\n\t// --- Critical: app is or may be DOWN. Rank these first. -------------------\n\tif (\n\t\texitCode === 6 ||\n\t\thas(logs, 'Manual recovery required') ||\n\t\thas(logs, 'manual intervention required')\n\t) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed AND rollback failed — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'Both the new version and the rollback failed their health check. ' +\n\t\t\t\t'SSH into the server and run: `pm2 logs selva-compute`, then ' +\n\t\t\t\t'`pm2 start ecosystem.config.cjs` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The SSE handler's 15-minute group-kill, and the reconciler's own poll cap.\n\t// Neither is an exit code the runner chose, so they carry no [EXIT] marker.\n\tif (exitCode === TIMED_OUT) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'App did not come back online within 15 minutes',\n\t\t\tdetail:\n\t\t\t\t'The update may still be finishing in the background, or the new ' +\n\t\t\t\t'process is crash-looping. Check `pm2 logs selva-compute`. Do not ' +\n\t\t\t\t're-run the update until you have confirmed the current state.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 4: the rollback's own npm install failed, so node_modules is\n\t// half-written and the EXIT trap's restart is the only thing that may have\n\t// brought the app back. Same urgency as a failed rollback restart.\n\tif (exitCode === 4) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed and the rollback could not reinstall — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'The previous version could not be restored from npm. SSH into the ' +\n\t\t\t\t'server and run `pm2 logs selva-compute`; if the app is down, reinstall ' +\n\t\t\t\t'explicitly with `npm install --prefer-online @selvajs/cli@<version> ' +\n\t\t\t\t'@selvajs/selva@<version>` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 3: unhealthy with no recorded prior version, so no rollback was even\n\t// attempted. The EXIT trap tried to restart whatever is on disk.\n\tif (exitCode === 3) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed its health check and could not be rolled back automatically',\n\t\t\tdetail:\n\t\t\t\t'No prior version was recorded, so the previous build could not be ' +\n\t\t\t\t'restored. Check `pm2 logs selva-compute` to confirm whether the app ' +\n\t\t\t\t'came back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// Killed mid-run (128+signal). Nothing was installed, and whether the app\n\t// came back depends on how far the EXIT trap got before it died too. Rank\n\t// with the criticals: an unattended half-update is worse than a clean\n\t// failure.\n\tif (exitCode === 143 || exitCode === 130 || exitCode === 129 || has(logs, 'KILLED')) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update was killed before it finished — nothing was installed',\n\t\t\tdetail:\n\t\t\t\t'The runner was terminated mid-update, most often by a systemd-supervised ' +\n\t\t\t\t'PM2 restarting its whole control group. The version on disk is unchanged. ' +\n\t\t\t\t'Check `pm2 logs selva-compute` and confirm the app is online before retrying; ' +\n\t\t\t\t'if a global pm2 owns the daemon, reconcile that first.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Warning: update did not fully succeed, but the app IS up. ------------\n\t// Aborted at the systemd guard, before `pm2 update` could recycle the\n\t// daemon and take this runner down with it.\n\tif (exitCode === 9 || has(logs, 'SYSTEMD_PM2')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — PM2 needs a resync that only a shell can do safely. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t\"This deployment's PM2 runs under systemd, where `pm2 update` restarts the \" +\n\t\t\t\t'unit and kills the update mid-run. Nothing was installed and the app is ' +\n\t\t\t\t'still serving. SSH in and run `./node_modules/.bin/pm2 update` from the ' +\n\t\t\t\t'deployment directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the data format check, before anything was stopped.\n\tif (exitCode === 10 || has(logs, 'DATA_FORMAT:')) {\n\t\tconst target = firstMatch(logs, /reads data format (\\d+),/);\n\t\tconst installed = firstMatch(logs, /this deployment is on format (\\d+)\\./);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update cancelled — ${to ?? 'the target version'} cannot read this deployment's data. The app is untouched.`,\n\t\t\tdetail:\n\t\t\t\t(target && installed\n\t\t\t\t\t? `It reads data format ${target}; this deployment is on format ${installed}. `\n\t\t\t\t\t: '') +\n\t\t\t\t'Installing it would leave stored data, such as Compute API keys, unreadable. ' +\n\t\t\t\t'Switch the release channel back to stay on the installed version. To go back ' +\n\t\t\t\t'anyway, follow \"Going back to an older release\" in the admin guide.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the pm2 skew check, before anything was stopped — nothing was\n\t// installed and the app never went down.\n\tif (exitCode === 8 || has(logs, 'PM2_SKEW')) {\n\t\tconst daemon = firstMatch(logs, /daemon \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\tconst local = firstMatch(logs, /deployment's pm2 \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\tdaemon && local\n\t\t\t\t\t? `Update cancelled — a global PM2 (v${daemon}) owns the daemon, not this deployment's (v${local}). The app is untouched.`\n\t\t\t\t\t: 'Update cancelled — a conflicting global PM2 owns the daemon. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t'Resyncing would have downgraded the daemon and dropped its process ' +\n\t\t\t\t'table, so the update stopped before taking the app down. On the server: ' +\n\t\t\t\t'`which -a pm2`, `pm2 -v`, `pm2 ping` — remove or align the global pm2, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// A rollback whose cause is the DATABASE, not the release. Ranked ahead of\n\t// the generic rollback case: \"review the log before retrying\" is actively\n\t// misleading here, because the log holds nothing about the new version —\n\t// it is fine, and retrying without touching the database repeats verbatim.\n\tif (has(logs, 'SCHEMA_SKEW')) {\n\t\tconst expected = firstMatch(logs, /expects database migration head (\\S+?),/);\n\t\tconst actual = firstMatch(logs, /this database is at (\\S+?)\\./);\n\t\tconst skew =\n\t\t\texpected && actual ? ` The database is at ${actual}; ${to ?? 'it'} needs ${expected}.` : '';\n\t\t// `latest` is the stable line, which ships none of a beta's migrations.\n\t\tconst providerTag =\n\t\t\tfirstMatch(logs, /@selvajs\\/supabase-provider@([\\w.-]+)/) ??\n\t\t\t(has(logs, 'channel: beta') ? 'beta' : 'latest');\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — the database migrations for ${to ?? 'the new version'} have not been applied.${skew} The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'Nothing is wrong with the new version. Selva does not apply migrations ' +\n\t\t\t\t'during an update, because they cannot be rolled back — auto-migrating ' +\n\t\t\t\t'and then rolling the code back would leave the app and database on ' +\n\t\t\t\t'different heads. Apply them on the server, then re-run this update: ' +\n\t\t\t\t`\\`npm install --prefer-online @selvajs/supabase-provider@${providerTag}\\`, then ` +\n\t\t\t\t'`npx selva-supabase`, then `npx supabase db push`. The provider install ' +\n\t\t\t\t'is not optional — the migration SQL ships inside that package, and the ' +\n\t\t\t\t'update only moves @selvajs/cli and @selvajs/selva, so a sync without it ' +\n\t\t\t\t'copies nothing and the push reports \"up to date\" having done nothing. ' +\n\t\t\t\t'Retrying without this will fail in exactly the same way.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Same shape: the rollback was caused by host configuration, not the release.\n\tif (has(logs, 'AT_REST_SECRETS')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — stored compute server keys do not decrypt under this host's SELVA_AT_REST_KEY. The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'This is a configuration problem on the server, not a fault in the new ' +\n\t\t\t\t'version, so retrying alone will fail identically. Re-enter the affected ' +\n\t\t\t\t'keys at /admin/compute, or restore the SELVA_AT_REST_KEY the values were ' +\n\t\t\t\t'encrypted with, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (exitCode === 5 || has(logs, 'Rolled back')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update failed — safely rolled back${from ? ` to ${from}` : ''}. The app is online.`,\n\t\t\tdetail:\n\t\t\t\t'The new version failed its health check, so the previous version ' +\n\t\t\t\t'was restored and is serving normally. Review the log below for why ' +\n\t\t\t\t'the new version failed before retrying.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The install completed and the app is up, but on a Node the release doesn't\n\t// support. The health probe passes (it exercises nothing version-specific),\n\t// so this would otherwise read as a clean success right up until a real\n\t// request hits a newer API and throws (issue #176).\n\tif (has(logs, 'ENGINE_MISMATCH') || has(logs, 'EBADENGINE')) {\n\t\tconst required = firstMatch(logs, /requires Node ([^\\s]+(?:\\s*[<>=]+\\s*[\\d.]+)*)/);\n\t\tconst running = firstMatch(logs, /this host runs v?(\\d+\\.\\d+\\.\\d+)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: running\n\t\t\t\t? `Updated${to ? ` to ${to}` : ''}, but this release needs Node ${required ?? '(newer)'} — the host runs v${running}. Expect runtime failures.`\n\t\t\t\t: `Updated${to ? ` to ${to}` : ''}, but this release requires a newer Node than the host provides. Expect runtime failures.`,\n\t\t\tdetail:\n\t\t\t\t'npm installed it anyway (engine-strict is off) and the health check ' +\n\t\t\t\t'passed, but it does not exercise the newer APIs — routes that do will ' +\n\t\t\t\t'throw at request time. Upgrade Node on the server, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The runner moved pm2 to the release's pin but could not swap the daemon\n\t// (refused under systemd, or `pm2 update` failed). The app runs; the next\n\t// pm2 command warns about the skew until someone runs the swap by hand.\n\tif (has(logs, 'PM2_RESYNC_NEEDED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but the pm2 daemon still runs the old pm2.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online. On the server, run `npx pm2 update` in the deployment ' +\n\t\t\t\t'directory, let it finish, then check `npx pm2 list` shows selva-compute online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'PM2_PIN_FAILED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but pm2 stayed on the previous version.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online on the old pm2. On the server, run `npx selva migrate` in ' +\n\t\t\t\t'the deployment directory to move it to the pinned version.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'npm cache may be stale') || has(logs, 'No version change')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: 'No version change — npm installed the same version.',\n\t\t\tdetail:\n\t\t\t\t'Your npm cache may be stale. On the server: `npm cache clean --force`, ' +\n\t\t\t\t'remove node_modules + package-lock.json, then `npm install --prefer-online`.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Success variants -----------------------------------------------------\n\tif (exitCode === 0) {\n\t\t// \"Already on the 'beta' channel version (4.2.0)\" — the channel name is\n\t\t// interpolated, so match the stable prefix rather than a whole line.\n\t\tif (has(logs, 'Already on the') || has(logs, 'Nothing to do')) {\n\t\t\treturn {\n\t\t\t\tseverity: 'info',\n\t\t\t\ttitle: `Already up to date${from ? ` (${from})` : ''} — nothing to install.`,\n\t\t\t\tdetail: 'No changes were made and the app was not restarted.',\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (from && to && from !== to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Updated ${from} → ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Update complete — now on ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tseverity: 'success',\n\t\t\ttitle: 'Update completed and the app is back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Anything else: a non-zero exit we don't have a named case for. -------\n\t// Be explicit that we couldn't classify it rather than implying success.\n\treturn {\n\t\tseverity: 'critical',\n\t\ttitle: `Update failed (exit code ${exitCode}).`,\n\t\tdetail:\n\t\t\t'The update did not complete cleanly. Review the log below, and check ' +\n\t\t\t'`pm2 logs selva-compute` to confirm whether the app is currently online.',\n\t\tfrom,\n\t\tto\n\t};\n}\n"],"mappings":"AA6BA,SAAS,WAAW,MAAc,IAAgC;CACjE,MAAM,IAAI,GAAG,KAAK,IAAI;CACtB,OAAO,IAAI,EAAE,KAAK,KAAA;AACnB;AAEA,SAAS,cAAc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,UAAU,oBAAoB,QAAQ,8BAClH,UAAU,KAAK,OAAO,OAAO,GAAG;GACnC,QACC;GAGD;GACA;EACD;CACD;CAIA,IAAI,IAAI,MAAM,mBAAmB,GAChC,OAAO;EACN,UAAU;EACV,OAAO,UAAU,KAAK,OAAO,OAAO,GAAG;EACvC,QACC;EAED;EACA;CACD;CAED,IAAI,IAAI,MAAM,gBAAgB,GAC7B,OAAO;EACN,UAAU;EACV,OAAO,UAAU,KAAK,OAAO,OAAO,GAAG;EACvC,QACC;EAED;EACA;CACD;CAED,IAAI,IAAI,MAAM,wBAAwB,KAAK,IAAI,MAAM,mBAAmB,GACvE,OAAO;EACN,UAAU;EACV,OAAO;EACP,QACC;EAED;EACA;CACD;CAID,IAAI,aAAa,GAAG;EAGnB,IAAI,IAAI,MAAM,gBAAgB,KAAK,IAAI,MAAM,eAAe,GAC3D,OAAO;GACN,UAAU;GACV,OAAO,qBAAqB,OAAO,KAAK,KAAK,KAAK,GAAG;GACrD,QAAQ;GACR;GACA;EACD;EAED,IAAI,QAAQ,MAAM,SAAS,IAC1B,OAAO;GACN,UAAU;GACV,OAAO,WAAW,KAAK,KAAK,GAAG;GAC/B;GACA;EACD;EAED,IAAI,IACH,OAAO;GACN,UAAU;GACV,OAAO,4BAA4B,GAAG;GACtC;GACA;EACD;EAED,OAAO;GACN,UAAU;GACV,OAAO;GACP;GACA;EACD;CACD;CAIA,OAAO;EACN,UAAU;EACV,OAAO,4BAA4B,SAAS;EAC5C,QACC;EAED;EACA;CACD;AACD"}
|
|
@@ -101,7 +101,7 @@ function channelTag(channel) {
|
|
|
101
101
|
return channel === "beta" ? "beta" : "latest";
|
|
102
102
|
}
|
|
103
103
|
function channelRegistryUrl(channel) {
|
|
104
|
-
return
|
|
104
|
+
return `${(env.NPM_CONFIG_REGISTRY || "https://registry.npmjs.org").replace(/\/+$/, "")}/@selvajs%2Fselva/${channelTag(channel)}`;
|
|
105
105
|
}
|
|
106
106
|
function isChannel(v) {
|
|
107
107
|
return v === "stable" || v === "beta";
|
|
@@ -136,6 +136,12 @@ function writeChannel(channel) {
|
|
|
136
136
|
if (!isChannel(channel)) throw new Error(`Invalid release channel: ${channel}`);
|
|
137
137
|
writeFileSync(channelFilePath(), JSON.stringify({ channel }, null, 2) + "\n", "utf8");
|
|
138
138
|
}
|
|
139
|
+
// src/lib/server/dataFormat.server.ts
|
|
140
|
+
/** The format a published `package.json` declares. None means format 1. */
|
|
141
|
+
function declaredDataFormat(pkg) {
|
|
142
|
+
const value = pkg?.selva?.dataFormat;
|
|
143
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : 1;
|
|
144
|
+
}
|
|
139
145
|
// src/lib/server/updateCheck.server.ts
|
|
140
146
|
function readInstalledVersion() {
|
|
141
147
|
const dirs = [];
|
|
@@ -157,6 +163,11 @@ function readInstalledVersion() {
|
|
|
157
163
|
}
|
|
158
164
|
return null;
|
|
159
165
|
}
|
|
166
|
+
var UNREADABLE = {
|
|
167
|
+
version: null,
|
|
168
|
+
enginesNode: null,
|
|
169
|
+
dataFormat: null
|
|
170
|
+
};
|
|
160
171
|
async function fetchLatestManifest(fetchImpl, channel = "stable") {
|
|
161
172
|
const ctrl = new AbortController();
|
|
162
173
|
const timer = setTimeout(() => ctrl.abort(), 5e3);
|
|
@@ -165,27 +176,23 @@ async function fetchLatestManifest(fetchImpl, channel = "stable") {
|
|
|
165
176
|
headers: { Accept: "application/json" },
|
|
166
177
|
signal: ctrl.signal
|
|
167
178
|
});
|
|
168
|
-
if (!res.ok) return
|
|
169
|
-
version: null,
|
|
170
|
-
enginesNode: null
|
|
171
|
-
};
|
|
179
|
+
if (!res.ok) return UNREADABLE;
|
|
172
180
|
const body = await res.json();
|
|
181
|
+
const version = typeof body.version === "string" ? body.version : null;
|
|
173
182
|
return {
|
|
174
|
-
version
|
|
175
|
-
enginesNode: typeof body.engines?.node === "string" ? body.engines.node : null
|
|
183
|
+
version,
|
|
184
|
+
enginesNode: typeof body.engines?.node === "string" ? body.engines.node : null,
|
|
185
|
+
dataFormat: version ? declaredDataFormat(body) : null
|
|
176
186
|
};
|
|
177
187
|
} catch {
|
|
178
|
-
return
|
|
179
|
-
version: null,
|
|
180
|
-
enginesNode: null
|
|
181
|
-
};
|
|
188
|
+
return UNREADABLE;
|
|
182
189
|
} finally {
|
|
183
190
|
clearTimeout(timer);
|
|
184
191
|
}
|
|
185
192
|
}
|
|
186
193
|
async function checkForUpdate(fetchImpl, channel = "stable", runningNode = process.versions.node) {
|
|
187
194
|
const current = readInstalledVersion();
|
|
188
|
-
const { version: latest, enginesNode } = await fetchLatestManifest(fetchImpl, channel);
|
|
195
|
+
const { version: latest, enginesNode, dataFormat } = await fetchLatestManifest(fetchImpl, channel);
|
|
189
196
|
return {
|
|
190
197
|
channel,
|
|
191
198
|
current,
|
|
@@ -195,6 +202,11 @@ async function checkForUpdate(fetchImpl, channel = "stable", runningNode = proce
|
|
|
195
202
|
compatible: enginesNode ? satisfiesRange(runningNode, enginesNode) : null,
|
|
196
203
|
required: enginesNode,
|
|
197
204
|
running: runningNode
|
|
205
|
+
},
|
|
206
|
+
dataCompatibility: {
|
|
207
|
+
compatible: dataFormat === null ? null : dataFormat >= 3,
|
|
208
|
+
installed: 3,
|
|
209
|
+
target: dataFormat
|
|
198
210
|
}
|
|
199
211
|
};
|
|
200
212
|
}
|