@selvajs/selva 4.20.0 → 4.20.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/assets/0.2jDm0bqh.css +2 -0
  3. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
  4. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
  5. package/build/client/_app/immutable/assets/{21.CZQvs3vE.css → 21.DDgTnace.css} +1 -1
  6. package/build/client/_app/immutable/assets/21.DDgTnace.css.br +0 -0
  7. package/build/client/_app/immutable/assets/21.DDgTnace.css.gz +0 -0
  8. package/build/client/_app/immutable/chunks/{DbTdXFSI.js → BDYCH-_Q.js} +1 -1
  9. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
  10. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
  11. package/build/client/_app/immutable/chunks/{6oDkMEbX.js → D-SwRD80.js} +62 -39
  12. package/build/client/_app/immutable/chunks/D-SwRD80.js.br +0 -0
  13. package/build/client/_app/immutable/chunks/D-SwRD80.js.gz +0 -0
  14. package/build/client/_app/immutable/chunks/Dvq2vJj6.js +1 -0
  15. package/build/client/_app/immutable/chunks/Dvq2vJj6.js.br +1 -0
  16. package/build/client/_app/immutable/chunks/Dvq2vJj6.js.gz +0 -0
  17. package/build/client/_app/immutable/chunks/{DVcao28H.js → DzxE3j6C.js} +1 -1
  18. package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
  19. package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
  20. package/build/client/_app/immutable/chunks/{DyqtDkQe.js → qi43d-TM.js} +1 -1
  21. package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
  22. package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
  23. package/build/client/_app/immutable/chunks/zJ-SFdYZ.js +1 -0
  24. package/build/client/_app/immutable/chunks/zJ-SFdYZ.js.br +0 -0
  25. package/build/client/_app/immutable/chunks/zJ-SFdYZ.js.gz +0 -0
  26. package/build/client/_app/immutable/entry/{app.CN37JsEV.js → app.hg2qyLJU.js} +2 -2
  27. package/build/client/_app/immutable/entry/app.hg2qyLJU.js.br +0 -0
  28. package/build/client/_app/immutable/entry/app.hg2qyLJU.js.gz +0 -0
  29. package/build/client/_app/immutable/nodes/{2.c6X0ddnS.js → 2.CUNbzjI_.js} +1 -1
  30. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
  31. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
  32. package/build/client/_app/immutable/nodes/{20.CyrNl6i7.js → 20.9OIre0ah.js} +1 -1
  33. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
  34. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
  35. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js +1 -0
  36. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.br +1 -0
  37. package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.gz +0 -0
  38. package/build/client/_app/immutable/nodes/{30.Bz0cB9UL.js → 30.BBuL_XNB.js} +2 -2
  39. package/build/client/_app/immutable/nodes/30.BBuL_XNB.js.br +0 -0
  40. package/build/client/_app/immutable/nodes/30.BBuL_XNB.js.gz +0 -0
  41. package/build/client/_app/immutable/nodes/35.De6sleaH.js +5 -0
  42. package/build/client/_app/immutable/nodes/35.De6sleaH.js.br +0 -0
  43. package/build/client/_app/immutable/nodes/35.De6sleaH.js.gz +0 -0
  44. package/build/client/_app/immutable/nodes/{5.Ck6I7GRI.js → 5.DmA9lTA-.js} +1 -1
  45. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +1 -0
  46. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
  47. package/build/client/_app/immutable/nodes/{6.BiSiWLjz.js → 6.D6WLqCgl.js} +1 -1
  48. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
  49. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
  50. package/build/client/_app/immutable/nodes/{7.OTA16TkX.js → 7.CNuRjkv2.js} +1 -1
  51. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
  52. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.gz +0 -0
  53. package/build/client/_app/version.json +1 -1
  54. package/build/client/_app/version.json.br +0 -0
  55. package/build/client/_app/version.json.gz +0 -0
  56. package/build/runtime-meta.json +1 -1
  57. package/build/server/.vite/manifest.json +108 -89
  58. package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +2 -0
  59. package/build/server/_app/immutable/assets/{_page.BLIssNhc.css → _page.l97MEw0G.css} +1 -1
  60. package/build/server/chunks/SettingsMenu.js +2 -2
  61. package/build/server/chunks/SettingsMenu.js.map +1 -1
  62. package/build/server/chunks/{abort-CNJ8Sn4g.js → abort-Bfrdupaj.js} +10 -3
  63. package/build/server/chunks/{abort-CNJ8Sn4g.js.map → abort-Bfrdupaj.js.map} +1 -1
  64. package/build/server/chunks/access.js +608 -150
  65. package/build/server/chunks/access.js.map +1 -1
  66. package/build/server/chunks/access2.server.js +2 -2
  67. package/build/server/chunks/api-errors.js +1 -1
  68. package/build/server/chunks/api.js +66 -18
  69. package/build/server/chunks/api.js.map +1 -1
  70. package/build/server/chunks/auth-bootstrap.server.js +1 -1
  71. package/build/server/chunks/boot.server.js +12 -701
  72. package/build/server/chunks/boot.server.js.map +1 -1
  73. package/build/server/chunks/bootHealth.server.js.map +1 -1
  74. package/build/server/chunks/compute.js +1 -1
  75. package/build/server/chunks/computeLimits.js +1 -1
  76. package/build/server/chunks/computeRateLimit.server.js +1 -1
  77. package/build/server/chunks/context.js +9 -43
  78. package/build/server/chunks/context.js.map +1 -1
  79. package/build/server/chunks/create-project.js +2 -2
  80. package/build/server/chunks/delete-with-blobs.js +1 -1
  81. package/build/server/chunks/engine.server.js +2 -16
  82. package/build/server/chunks/engine.server.js.map +1 -1
  83. package/build/server/chunks/grasshopper.js +2 -1
  84. package/build/server/chunks/grasshopper.js.map +1 -1
  85. package/build/server/chunks/handlers.js +13 -29
  86. package/build/server/chunks/handlers.js.map +1 -1
  87. package/build/server/chunks/http.js +93 -6
  88. package/build/server/chunks/http.js.map +1 -1
  89. package/build/server/chunks/instance.js +3 -3
  90. package/build/server/chunks/instanceAdmins.server.js +1 -1
  91. package/build/server/chunks/internal.js +1 -1
  92. package/build/server/chunks/limits.js +71 -0
  93. package/build/server/chunks/limits.js.map +1 -0
  94. package/build/server/chunks/ops.js +1 -1
  95. package/build/server/chunks/package.js +1 -1
  96. package/build/server/chunks/package.js.map +1 -1
  97. package/build/server/chunks/permissions.server.js +1 -1
  98. package/build/server/chunks/presets.server.js +1 -1
  99. package/build/server/chunks/previous-key.js +18 -2
  100. package/build/server/chunks/previous-key.js.map +1 -1
  101. package/build/server/chunks/providers.server.js +808 -444
  102. package/build/server/chunks/providers.server.js.map +1 -1
  103. package/build/server/chunks/registry.js +4 -1
  104. package/build/server/chunks/registry.js.map +1 -1
  105. package/build/server/chunks/remote-definition.js +1 -1
  106. package/build/server/chunks/safe-url.js +1 -1
  107. package/build/server/chunks/schema.js.map +1 -1
  108. package/build/server/chunks/schemas.js +12 -61
  109. package/build/server/chunks/schemas.js.map +1 -1
  110. package/build/server/chunks/schemas2.js +80 -0
  111. package/build/server/chunks/schemas2.js.map +1 -0
  112. package/build/server/chunks/server-config-write.js +3 -8
  113. package/build/server/chunks/server-config-write.js.map +1 -1
  114. package/build/server/chunks/signInMaxAge.server.js +1 -1
  115. package/build/server/chunks/solve.server.js +4 -2
  116. package/build/server/chunks/solve.server.js.map +1 -1
  117. package/build/server/chunks/sveltekit.js +4 -4
  118. package/build/server/chunks/token2.server.js +1 -1
  119. package/build/server/chunks/tokens.js +2 -2
  120. package/build/server/chunks/types.js +9 -4
  121. package/build/server/chunks/types.js.map +1 -1
  122. package/build/server/chunks/types2.js +1 -2
  123. package/build/server/chunks/types2.js.map +1 -1
  124. package/build/server/chunks/visibility.js +1 -1
  125. package/build/server/chunks/visibility.js.map +1 -1
  126. package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +3 -3
  127. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +6 -5
  128. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js.map +1 -1
  129. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +2 -2
  130. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
  131. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
  132. package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
  133. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +1 -1
  134. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +1 -1
  135. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +2 -2
  136. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +2 -2
  137. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +2 -2
  138. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +2 -1
  139. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js.map +1 -1
  140. package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +1 -1
  141. package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +2 -2
  142. package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +2 -2
  143. package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +2 -2
  144. package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +2 -2
  145. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +2 -2
  146. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +2 -2
  147. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +2 -2
  148. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +2 -2
  149. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +2 -2
  150. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +2 -2
  151. package/build/server/entries/endpoints/api/v1/definitions/_server.ts.js +1 -1
  152. package/build/server/entries/endpoints/api/v1/me/_server.ts.js +1 -1
  153. package/build/server/entries/endpoints/api/v1/me/starred/_guid_/_server.ts.js +1 -1
  154. package/build/server/entries/endpoints/api/v1/me/token/_server.ts.js +1 -1
  155. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/_server.ts.js +1 -1
  156. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/assets/_kind_/_server.ts.js +1 -1
  157. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/compute/_server.ts.js +1 -1
  158. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_id_/_server.ts.js +1 -1
  159. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_id_/resend/_server.ts.js +1 -1
  160. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/invites/_server.ts.js +1 -1
  161. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_server.ts.js +1 -1
  162. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_userId_/_server.ts.js +1 -1
  163. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_server.ts.js +1 -1
  164. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_tokenId_/_server.ts.js +1 -1
  165. package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +2 -2
  166. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +2 -2
  167. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +2 -2
  168. package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +2 -2
  169. package/build/server/entries/endpoints/api/v1/projects/_server.ts.js +1 -1
  170. package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
  171. package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
  172. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  173. package/build/server/entries/endpoints/mcp/_server.ts.js +5 -4
  174. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  175. package/build/server/entries/hooks.server.js +3 -92
  176. package/build/server/entries/hooks.server.js.map +1 -1
  177. package/build/server/entries/pages/accept-invite/_page.server.ts.js +9 -6
  178. package/build/server/entries/pages/accept-invite/_page.server.ts.js.map +1 -1
  179. package/build/server/entries/pages/admin/_page.server.ts.js +1 -1
  180. package/build/server/entries/pages/admin/organizations/_page.server.ts.js +1 -1
  181. package/build/server/entries/pages/admin/projects/_id_/_page.server.ts.js +1 -1
  182. package/build/server/entries/pages/admin/projects/_page.server.ts.js +1 -1
  183. package/build/server/entries/pages/admin/system/_page.server.ts.js +2 -2
  184. package/build/server/entries/pages/admin/users/_page.server.ts.js +1 -1
  185. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +1 -1
  186. package/build/server/entries/pages/library/_guid_/_page.svelte.js +114 -43
  187. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  188. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +1 -1
  189. package/build/server/entries/pages/projects/_layout.server.ts.js +1 -1
  190. package/build/server/entries/pages/projects/_page.server.ts.js +2 -2
  191. package/build/server/entries/pages/setup/_page.server.ts.js +1 -1
  192. package/build/server/entries/pages/team/compute/_page.server.ts.js +1 -1
  193. package/build/server/entries/pages/team/members/_page.server.ts.js +1 -1
  194. package/build/server/entries/pages/team/members/_page.svelte.js +2 -2
  195. package/build/server/entries/pages/team/members/_page.svelte.js.map +1 -1
  196. package/build/server/entries/pages/team/projects/_page.server.ts.js +1 -1
  197. package/build/server/entries/pages/team/settings/_page.server.ts.js +1 -1
  198. package/build/server/entries/pages/team/shares/_page.server.ts.js +1 -1
  199. package/build/server/manifest-full.js +1 -1
  200. package/build/server/manifest.js +1 -1
  201. package/build/server/nodes/0.js +2 -2
  202. package/build/server/nodes/2.js +1 -1
  203. package/build/server/nodes/20.js +1 -1
  204. package/build/server/nodes/21.js +2 -2
  205. package/build/server/nodes/30.js +1 -1
  206. package/build/server/nodes/35.js +1 -1
  207. package/build/server/nodes/5.js +1 -1
  208. package/build/server/nodes/6.js +1 -1
  209. package/build/server/nodes/7.js +1 -1
  210. package/build/server/server.js +1 -1
  211. package/package.json +12 -12
  212. package/build/client/_app/immutable/assets/0.DwB0QWdx.css +0 -2
  213. package/build/client/_app/immutable/assets/0.DwB0QWdx.css.br +0 -0
  214. package/build/client/_app/immutable/assets/0.DwB0QWdx.css.gz +0 -0
  215. package/build/client/_app/immutable/assets/21.CZQvs3vE.css.br +0 -0
  216. package/build/client/_app/immutable/assets/21.CZQvs3vE.css.gz +0 -0
  217. package/build/client/_app/immutable/chunks/6oDkMEbX.js.br +0 -0
  218. package/build/client/_app/immutable/chunks/6oDkMEbX.js.gz +0 -0
  219. package/build/client/_app/immutable/chunks/B9IvNrzX.js +0 -1
  220. package/build/client/_app/immutable/chunks/B9IvNrzX.js.br +0 -1
  221. package/build/client/_app/immutable/chunks/B9IvNrzX.js.gz +0 -0
  222. package/build/client/_app/immutable/chunks/DVcao28H.js.br +0 -0
  223. package/build/client/_app/immutable/chunks/DVcao28H.js.gz +0 -0
  224. package/build/client/_app/immutable/chunks/DbTdXFSI.js.br +0 -0
  225. package/build/client/_app/immutable/chunks/DbTdXFSI.js.gz +0 -0
  226. package/build/client/_app/immutable/chunks/DyqtDkQe.js.br +0 -0
  227. package/build/client/_app/immutable/chunks/DyqtDkQe.js.gz +0 -0
  228. package/build/client/_app/immutable/chunks/I4bYfY0F.js +0 -1
  229. package/build/client/_app/immutable/chunks/I4bYfY0F.js.br +0 -0
  230. package/build/client/_app/immutable/chunks/I4bYfY0F.js.gz +0 -0
  231. package/build/client/_app/immutable/entry/app.CN37JsEV.js.br +0 -0
  232. package/build/client/_app/immutable/entry/app.CN37JsEV.js.gz +0 -0
  233. package/build/client/_app/immutable/nodes/2.c6X0ddnS.js.br +0 -0
  234. package/build/client/_app/immutable/nodes/2.c6X0ddnS.js.gz +0 -0
  235. package/build/client/_app/immutable/nodes/20.CyrNl6i7.js.br +0 -0
  236. package/build/client/_app/immutable/nodes/20.CyrNl6i7.js.gz +0 -0
  237. package/build/client/_app/immutable/nodes/21._AcAMXtP.js +0 -1
  238. package/build/client/_app/immutable/nodes/21._AcAMXtP.js.br +0 -0
  239. package/build/client/_app/immutable/nodes/21._AcAMXtP.js.gz +0 -0
  240. package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.br +0 -0
  241. package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.gz +0 -0
  242. package/build/client/_app/immutable/nodes/35.DFkalFgm.js +0 -5
  243. package/build/client/_app/immutable/nodes/35.DFkalFgm.js.br +0 -0
  244. package/build/client/_app/immutable/nodes/35.DFkalFgm.js.gz +0 -0
  245. package/build/client/_app/immutable/nodes/5.Ck6I7GRI.js.br +0 -0
  246. package/build/client/_app/immutable/nodes/5.Ck6I7GRI.js.gz +0 -0
  247. package/build/client/_app/immutable/nodes/6.BiSiWLjz.js.br +0 -0
  248. package/build/client/_app/immutable/nodes/6.BiSiWLjz.js.gz +0 -0
  249. package/build/client/_app/immutable/nodes/7.OTA16TkX.js.br +0 -0
  250. package/build/client/_app/immutable/nodes/7.OTA16TkX.js.gz +0 -0
  251. package/build/server/_app/immutable/assets/_layout.DwB0QWdx.css +0 -2
  252. /package/build/client/_app/immutable/nodes/{0.CC0wt5QB.js → 0.CYdyv5To.js} +0 -0
  253. /package/build/client/_app/immutable/nodes/{0.CC0wt5QB.js.br → 0.CYdyv5To.js.br} +0 -0
  254. /package/build/client/_app/immutable/nodes/{0.CC0wt5QB.js.gz → 0.CYdyv5To.js.gz} +0 -0
@@ -1,6 +1,6 @@
1
- import { E as MAX_SOLVE_DEADLINE_MS, T as providers, b as getSolveMetricSink, k as solveInputsFromSchema, w as lazyLogger, x as getStorageProvider } from "./providers.server.js";
1
+ import { F as postedServerSourcedIds, I as solveInputsFromSchema, M as MAX_SOLVE_DEADLINE_MS, T as providers, b as getSolveMetricSink, w as lazyLogger, x as getStorageProvider } from "./providers.server.js";
2
2
  import { E as scoped, M as isApiError, N as toErrorBody, O as ApiError, d as requireCanEditDefinition, h as requireCanSolve, k as ApiErrorCode } from "./access.js";
3
- import { A as assertScope, D as rateLimitedResponse, k as withRateLimitHeaders, w as chargeApiRateLimit } from "./api.js";
3
+ import { E as chargeApiRateLimit, M as assertScope, j as withRateLimitHeaders, k as rateLimitedResponse } from "./api.js";
4
4
  import { t as createRemoteDefinitionFetcher } from "./remote-definition.js";
5
5
  import { a as ComputeServerUnconfiguredError, r as fetchSchemaFromCompute } from "./schema-extraction.js";
6
6
  import "./compute.js";
@@ -229,6 +229,8 @@ async function runSolve(params) {
229
229
  }
230
230
  if (isLocal && !storedSchema) apiError(503, ApiErrorCode.COMPUTE_UNAVAILABLE, "This version's inputs could not be read. Retry shortly.");
231
231
  const solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : readRemoteInputs(inputs);
232
+ const serverOnly = postedServerSourcedIds(solveInputs, values);
233
+ if (serverOnly.length > 0) apiError(400, ApiErrorCode.VALIDATION_FAILED, `These inputs are filled on the server and may not be posted in values: ${serverOnly.join(", ")}.`);
232
234
  const live = bindLiveSolve({
233
235
  ownerKey: liveOwnerKey(access.kind === "user" ? access.ctx.userId : null),
234
236
  streamId,
@@ -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\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\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// 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\tconst solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : readRemoteInputs(inputs);\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;;;;;;;;;;;;;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AAQ,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/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\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// 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\tconst solveInputs = storedSchema ? solveInputsFromSchema(storedSchema) : 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\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,OAAO,YACpC,OAAQ,MAAqB,aAAa,QAC5C,IAEA,SACC,KACA,aAAa,mBACb,6EACD;CAED,OAAO;AACR;;;;;;;;AASA,eAAsB,SAAS,QAAwC;CACtE,MAAM,EACL,QACA,eACA,QACA,QACA,SACA,WAAW,mBACX,SACA,QACA,WACA,WACA,uBAAuB,OACvB,WAAW,MACX,eAAe,UACZ;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AK,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,7 +1,7 @@
1
- import { I as NoopEventSink, c as getDefinitionService, i as getBranding, m as getOrgAssetService, p as getNotificationProvider } from "./providers.server.js";
2
- import { O as ApiError, R as isFlagEnabled, j as codeForStatus, k as ApiErrorCode } from "./access.js";
3
- import { s as ProviderError } from "./context.js";
4
- import { D as rateLimitedResponse, _ as runHandler, k as withRateLimitHeaders, w as chargeApiRateLimit } from "./api.js";
1
+ import { H as NoopEventSink, c as getDefinitionService, i as getBranding, m as getOrgAssetService, p as getNotificationProvider } from "./providers.server.js";
2
+ import { O as ApiError, j as codeForStatus, k as ApiErrorCode, z as isFlagEnabled } from "./access.js";
3
+ import { i as ProviderError } from "./context.js";
4
+ import { E as chargeApiRateLimit, b as runHandler, j as withRateLimitHeaders, k as rateLimitedResponse } from "./api.js";
5
5
  import { a as ComputeServerUnconfiguredError, t as SchemaExtractionError } from "./schema-extraction.js";
6
6
  import { t as publicUrl } from "./origin.js";
7
7
  import { a as MAX_DEFINITION_FILE_SIZE, o as MAX_IMAGE_FILE_SIZE } from "./computeLimits.js";
@@ -1,6 +1,6 @@
1
1
  import { t as hmacKeys } from "./keys.server.js";
2
2
  import "./tokens.js";
3
- import { c as createApiTokenCodec, n as createApiTokenResolutionCache } from "./http.js";
3
+ import { l as createApiTokenCodec, r as createApiTokenResolutionCache } from "./http.js";
4
4
  // src/lib/server/apiTokens/token.server.ts
5
5
  var cached = null;
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { K as canCreateProject } from "./access.js";
1
+ import { q as canCreateProject } from "./access.js";
2
2
  import { o as parseApiScope } from "./types.js";
3
- import { o as hasPermission, t as SYSTEM_CONTEXT } from "./context.js";
3
+ import { r as hasPermission, t as SYSTEM_CONTEXT } from "./context.js";
4
4
  import { t as canCreateDefinitionInOrg } from "./visibility.js";
5
5
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
6
6
  function createTokenCodec(config) {
@@ -14,8 +14,11 @@ var ApiScopeActionSchema = z.enum([
14
14
  "upload",
15
15
  "create_projects"
16
16
  ]);
17
- var SCOPE_PATTERN = /^(read|write|solve|upload|create_projects):(all|(org|project|definition):([A-Za-z0-9_-]{1,128}))$/;
18
- /** `read:all`, `write:org:<id>`, `solve:project:<id>`, `read:definition:<guid>`. */
17
+ var SCOPE_PATTERN = new RegExp(`^(${ApiScopeActionSchema.options.join("|")}):(all|(org|project|definition):([A-Za-z0-9_-]{1,128}))$`);
18
+ /**
19
+ * `read:all`, `write:org:<id>`, `solve:project:<id>`, `read:definition:<guid>`.
20
+ * `create_projects` takes only `all` or `org`: a project-scoped one could create nothing.
21
+ */
19
22
  function parseApiScope(value) {
20
23
  const m = SCOPE_PATTERN.exec(value);
21
24
  if (!m) return null;
@@ -24,10 +27,12 @@ function parseApiScope(value) {
24
27
  action,
25
28
  resource: { kind: "all" }
26
29
  };
30
+ const kind = m[3];
31
+ if (action === "create_projects" && kind !== "org") return null;
27
32
  return {
28
33
  action,
29
34
  resource: {
30
- kind: m[3],
35
+ kind,
31
36
  id: m[4]
32
37
  }
33
38
  };
@@ -60,7 +65,7 @@ var ACTION_WORDS = {
60
65
  write: "Read and change",
61
66
  solve: "Read and run solves on",
62
67
  upload: "Read and upload definitions to",
63
- create_projects: "Create private projects in"
68
+ create_projects: "Read and create private projects in"
64
69
  };
65
70
  /** "Read and change everything in the org". Names no ids, so it suits an email. */
66
71
  function describeApiScope(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../../../platform/src/apiTokens/types.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Every action includes `read`, and `write` includes `upload` and\n * `create_projects`. `upload` covers only creating definitions, uploading\n * versions, checking a file's schema before upload and making a version live:\n * it can't edit metadata, delete or share. `create_projects` covers only\n * creating private projects, and only org-wide: the route names no project.\n */\nexport const ApiScopeActionSchema = z.enum(['read', 'write', 'solve', 'upload', 'create_projects']);\nexport type ApiScopeAction = z.infer<typeof ApiScopeActionSchema>;\n\n/**\n * What one scope covers. A token is bound to one org, so `all` and that org's\n * `org` resource reach the same rows; both exist so a host app can store\n * either without translating.\n */\nexport type ApiScopeResource =\n\t| { kind: 'all' }\n\t| { kind: 'org'; id: string }\n\t| { kind: 'project'; id: string }\n\t| { kind: 'definition'; id: string };\n\nexport interface ApiScope {\n\taction: ApiScopeAction;\n\tresource: ApiScopeResource;\n}\n\n// Ids are uuids or guids in practice; the charset only has to keep `:` out so\n// the string form stays unambiguous.\nconst SCOPE_PATTERN =\n\t/^(read|write|solve|upload|create_projects):(all|(org|project|definition):([A-Za-z0-9_-]{1,128}))$/;\n\n/** `read:all`, `write:org:<id>`, `solve:project:<id>`, `read:definition:<guid>`. */\nexport function parseApiScope(value: string): ApiScope | null {\n\tconst m = SCOPE_PATTERN.exec(value);\n\tif (!m) return null;\n\tconst action = m[1] as ApiScopeAction;\n\tif (m[2] === 'all') return { action, resource: { kind: 'all' } };\n\treturn { action, resource: { kind: m[3] as 'org' | 'project' | 'definition', id: m[4]! } };\n}\n\nexport function formatApiScope(scope: ApiScope): string {\n\tconst { action, resource } = scope;\n\treturn resource.kind === 'all' ? `${action}:all` : `${action}:${resource.kind}:${resource.id}`;\n}\n\n/**\n * Scopes are stored as strings so a new action or resource kind needs no\n * migration. Parsing rejects anything this version doesn't understand, so an\n * unknown scope grants nothing rather than being guessed at.\n */\nexport const ApiScopeStringSchema = z\n\t.string()\n\t.refine((s) => parseApiScope(s) !== null, { message: 'Unknown scope' });\n\n/**\n * A long-lived bearer credential acting as `userId` inside `orgId`, narrowed by\n * `scopes`. The raw key is shown once at mint; the store holds only its HMAC.\n */\nexport interface ApiToken {\n\tid: string;\n\t/** The user the token acts as. Erasing them deletes the token. */\n\tuserId: string;\n\t/**\n\t * Who minted it. Equal to `userId` until service accounts exist; null once\n\t * the minting user is erased.\n\t */\n\tcreatedBy: string | null;\n\torgId: string;\n\t/** Free text the owner chose. Personal data in practice (\"Felix laptop\"), so never logged or audited. */\n\tname: string;\n\t/** `HMAC-SHA256(SELVA_HMAC_KEY, rawToken)`, base64url. */\n\ttokenHash: string;\n\t/** String form, see {@link parseApiScope}. At least one. */\n\tscopes: string[];\n\tcreatedAt: string;\n\texpiresAt: string;\n\tlastUsedAt: string | null;\n\t/** Revoked rows stay so a `tokenId` in the audit log still resolves to a name. */\n\trevokedAt: string | null;\n}\n\n/** What listing returns: the hash never leaves the store on a read path. */\nexport type ApiTokenSummary = Omit<ApiToken, 'tokenHash'>;\n\nexport const ApiTokenRevokeReasonSchema = z.enum([\n\t'owner',\n\t'admin',\n\t'member_removed',\n\t'user_disabled',\n\t'sign_in_lapsed'\n]);\nexport type ApiTokenRevokeReason = z.infer<typeof ApiTokenRevokeReasonSchema>;\n\n/** The only lifetimes offered. Expiry is never optional. */\nexport const API_TOKEN_LIFETIME_DAYS = [30, 90, 180] as const;\nexport type ApiTokenLifetimeDays = (typeof API_TOKEN_LIFETIME_DAYS)[number];\n\nconst ACTION_WORDS: Record<ApiScopeAction, string> = {\n\tread: 'Read',\n\twrite: 'Read and change',\n\tsolve: 'Read and run solves on',\n\tupload: 'Read and upload definitions to',\n\tcreate_projects: 'Create private projects in'\n};\n\n/** \"Read and change everything in the org\". Names no ids, so it suits an email. */\nexport function describeApiScope(value: string): string {\n\tconst scope = parseApiScope(value);\n\tif (!scope) return `Unknown scope (${value})`;\n\tconst what =\n\t\tscope.resource.kind === 'project'\n\t\t\t? 'one project'\n\t\t\t: scope.resource.kind === 'definition'\n\t\t\t\t? 'one definition'\n\t\t\t\t: 'everything in the org';\n\treturn `${ACTION_WORDS[scope.action]} ${what}`;\n}\n"],"mappings":";;;;;;;;;AASA,IAAa,uBAAuB,EAAE,KAAK;CAAC;CAAQ;CAAS;CAAS;CAAU;AAAiB,CAAC;AAqBlG,IAAM,gBACL;;AAGD,SAAgB,cAAc,OAAgC;CAC7D,MAAM,IAAI,cAAc,KAAK,KAAK;CAClC,IAAI,CAAC,GAAG,OAAO;CACf,MAAM,SAAS,EAAE;CACjB,IAAI,EAAE,OAAO,OAAO,OAAO;EAAE;EAAQ,UAAU,EAAE,MAAM,MAAM;CAAE;CAC/D,OAAO;EAAE;EAAQ,UAAU;GAAE,MAAM,EAAE;GAAwC,IAAI,EAAE;EAAI;CAAE;AAC1F;AAEA,SAAgB,eAAe,OAAyB;CACvD,MAAM,EAAE,QAAQ,aAAa;CAC7B,OAAO,SAAS,SAAS,QAAQ,GAAG,OAAO,QAAQ,GAAG,OAAO,GAAG,SAAS,KAAK,GAAG,SAAS;AAC3F;;;;;;AAOA,IAAa,uBAAuB,EAClC,OAAO,CAAC,CACR,QAAQ,MAAM,cAAc,CAAC,MAAM,MAAM,EAAE,SAAS,gBAAgB,CAAC;AAgC7B,EAAE,KAAK;CAChD;CACA;CACA;CACA;CACA;AACD,CAAC;;AAID,IAAa,0BAA0B;CAAC;CAAI;CAAI;AAAG;AAGnD,IAAM,eAA+C;CACpD,MAAM;CACN,OAAO;CACP,OAAO;CACP,QAAQ;CACR,iBAAiB;AAClB;;AAGA,SAAgB,iBAAiB,OAAuB;CACvD,MAAM,QAAQ,cAAc,KAAK;CACjC,IAAI,CAAC,OAAO,OAAO,kBAAkB,MAAM;CAC3C,MAAM,OACL,MAAM,SAAS,SAAS,YACrB,gBACA,MAAM,SAAS,SAAS,eACvB,mBACA;CACL,OAAO,GAAG,aAAa,MAAM,QAAQ,GAAG;AACzC"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../../../platform/src/apiTokens/types.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Every action includes `read`, and `write` includes `upload` and\n * `create_projects`. `upload` covers only creating definitions, uploading\n * versions, checking a file's schema before upload and making a version live:\n * it can't edit metadata, delete or share. `create_projects` covers only\n * creating private projects, and only org-wide: the route names no project.\n */\nexport const ApiScopeActionSchema = z.enum(['read', 'write', 'solve', 'upload', 'create_projects']);\nexport type ApiScopeAction = z.infer<typeof ApiScopeActionSchema>;\n\n/**\n * What one scope covers. A token is bound to one org, so `all` and that org's\n * `org` resource reach the same rows; both exist so a host app can store\n * either without translating.\n */\nexport type ApiScopeResource =\n\t| { kind: 'all' }\n\t| { kind: 'org'; id: string }\n\t| { kind: 'project'; id: string }\n\t| { kind: 'definition'; id: string };\n\nexport interface ApiScope {\n\taction: ApiScopeAction;\n\tresource: ApiScopeResource;\n}\n\n// Ids are uuids or guids in practice; the charset only has to keep `:` out so\n// the string form stays unambiguous.\nconst SCOPE_PATTERN = new RegExp(\n\t`^(${ApiScopeActionSchema.options.join('|')}):(all|(org|project|definition):([A-Za-z0-9_-]{1,128}))$`\n);\n\n/**\n * `read:all`, `write:org:<id>`, `solve:project:<id>`, `read:definition:<guid>`.\n * `create_projects` takes only `all` or `org`: a project-scoped one could create nothing.\n */\nexport function parseApiScope(value: string): ApiScope | null {\n\tconst m = SCOPE_PATTERN.exec(value);\n\tif (!m) return null;\n\tconst action = m[1] as ApiScopeAction;\n\tif (m[2] === 'all') return { action, resource: { kind: 'all' } };\n\tconst kind = m[3] as 'org' | 'project' | 'definition';\n\tif (action === 'create_projects' && kind !== 'org') return null;\n\treturn { action, resource: { kind, id: m[4]! } };\n}\n\nexport function formatApiScope(scope: ApiScope): string {\n\tconst { action, resource } = scope;\n\treturn resource.kind === 'all' ? `${action}:all` : `${action}:${resource.kind}:${resource.id}`;\n}\n\n/**\n * Scopes are stored as strings so a new action or resource kind needs no\n * migration. Parsing rejects anything this version doesn't understand, so an\n * unknown scope grants nothing rather than being guessed at.\n */\nexport const ApiScopeStringSchema = z\n\t.string()\n\t.refine((s) => parseApiScope(s) !== null, { message: 'Unknown scope' });\n\n/**\n * A long-lived bearer credential acting as `userId` inside `orgId`, narrowed by\n * `scopes`. The raw key is shown once at mint; the store holds only its HMAC.\n */\nexport interface ApiToken {\n\tid: string;\n\t/** The user the token acts as. Erasing them deletes the token. */\n\tuserId: string;\n\t/**\n\t * Who minted it. Equal to `userId` until service accounts exist; null once\n\t * the minting user is erased.\n\t */\n\tcreatedBy: string | null;\n\torgId: string;\n\t/** Free text the owner chose. Personal data in practice (\"Felix laptop\"), so never logged or audited. */\n\tname: string;\n\t/** `HMAC-SHA256(SELVA_HMAC_KEY, rawToken)`, base64url. */\n\ttokenHash: string;\n\t/** String form, see {@link parseApiScope}. At least one. */\n\tscopes: string[];\n\tcreatedAt: string;\n\texpiresAt: string;\n\tlastUsedAt: string | null;\n\t/** Revoked rows stay so a `tokenId` in the audit log still resolves to a name. */\n\trevokedAt: string | null;\n}\n\n/** What listing returns: the hash never leaves the store on a read path. */\nexport type ApiTokenSummary = Omit<ApiToken, 'tokenHash'>;\n\nexport const ApiTokenRevokeReasonSchema = z.enum([\n\t'owner',\n\t'admin',\n\t'member_removed',\n\t'user_disabled',\n\t'sign_in_lapsed'\n]);\nexport type ApiTokenRevokeReason = z.infer<typeof ApiTokenRevokeReasonSchema>;\n\n/** The only lifetimes offered. Expiry is never optional. */\nexport const API_TOKEN_LIFETIME_DAYS = [30, 90, 180] as const;\nexport type ApiTokenLifetimeDays = (typeof API_TOKEN_LIFETIME_DAYS)[number];\n\nconst ACTION_WORDS: Record<ApiScopeAction, string> = {\n\tread: 'Read',\n\twrite: 'Read and change',\n\tsolve: 'Read and run solves on',\n\tupload: 'Read and upload definitions to',\n\tcreate_projects: 'Read and create private projects in'\n};\n\n/** \"Read and change everything in the org\". Names no ids, so it suits an email. */\nexport function describeApiScope(value: string): string {\n\tconst scope = parseApiScope(value);\n\tif (!scope) return `Unknown scope (${value})`;\n\tconst what =\n\t\tscope.resource.kind === 'project'\n\t\t\t? 'one project'\n\t\t\t: scope.resource.kind === 'definition'\n\t\t\t\t? 'one definition'\n\t\t\t\t: 'everything in the org';\n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,QAAQ,GAAG;AACzC"}
@@ -1,5 +1,4 @@
1
- // ../platform/src/definitions/types.ts
2
- var GH_EXTENSIONS = [".gh", ".ghx"];
1
+ var GH_EXTENSIONS = ["gh", "ghx"].map((ext) => `.${ext}`);
3
2
  var COVER_IMAGE_CONTENT_TYPES = {
4
3
  ".jpg": "image/jpeg",
5
4
  ".jpeg": "image/jpeg",
@@ -1 +1 @@
1
- {"version":3,"file":"types2.js","names":[],"sources":["../../../../platform/src/definitions/types.ts"],"sourcesContent":["import type { UISchema } from '@selvajs/schemas';\nimport type { z } from 'zod';\nimport type { DefinitionChannelSchema } from './schemas.js';\n\nexport type DefinitionFileExt = 'gh' | 'ghx';\n\nexport const GH_EXTENSIONS: string[] = ['.gh', '.ghx'];\n\nexport const COVER_IMAGE_CONTENT_TYPES: Record<string, string> = {\n\t'.jpg': 'image/jpeg',\n\t'.jpeg': 'image/jpeg',\n\t'.png': 'image/png',\n\t'.webp': 'image/webp',\n\t'.gif': 'image/gif'\n};\n\n/**\n * - `pending` — internal: metadata written, blob upload may be in flight.\n * - `draft` — work in progress, not visible to runners.\n * - `published` — live, visible to all with solve access.\n * - `archived` — retired but preserved; restore via `update({ status: 'draft' | 'published' })`.\n *\n * List endpoints filter out `pending` and `archived` by default (opt in via\n * `DefinitionListOptions.includePending`/`includeArchived`, or an explicit `statuses` filter).\n */\nexport type DefinitionStatus = 'pending' | 'draft' | 'published' | 'archived';\n\n/**\n * Immutable snapshot of a definition's `.gh` file at a point in time. New\n * uploads create new versions; rollback re-points the parent's\n * `liveVersionId` rather than mutating the version itself.\n */\nexport interface DefinitionVersion {\n\tid: string;\n\tdefinitionId: string;\n\t/** Allocated from `DefinitionRecord.nextVersionNumber`; see that field for the numbering guarantee. */\n\tversionNumber: number;\n\tfileExt: DefinitionFileExt;\n\t/** Full storage key. Opaque to callers. */\n\tfileKey: string;\n\toriginalFilename?: string;\n\tuploadedBy: string;\n\tuploadedAt: string;\n\t/** Free-form note describing what changed in this version. */\n\tchangeNote?: string;\n\t/**\n\t * Compute-extracted UI schema, cached at upload so the render path doesn't\n\t * re-fetch it from Rhino.Compute on every load. Optional only for the\n\t * lazy-backfill bridge on pre-existing versions; new uploads always set it.\n\t */\n\tschema?: UISchema;\n\t/** ISO timestamp of when `schema` was extracted. */\n\tschemaExtractedAt?: string;\n}\n\nexport interface DefinitionRecord {\n\tguid: string;\n\tprojectId: string;\n\t/** Current owner — separate from `createdBy` so ownership can transfer. */\n\townerId: string;\n\tcreatedBy: string;\n\tupdatedBy: string;\n\t/** Falls back to the org default, then the platform default. */\n\tcomputeServerId?: string;\n\t/**\n\t * Per-definition quota for a shared solve-result cache: `0` = caching off,\n\t * `N` = keep at most N cached solves, absent = inherit the backend default.\n\t *\n\t * **Dormant.** No shared backend ships today (see `ISolveResultCache`), so\n\t * this affects nothing at solve time yet. Kept as a persisted column rather\n\t * than removed, since it's the right knob once a backend exists.\n\t */\n\tsolveCacheLimit?: number;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\t/** Provider-dependent public URL — must be safe to send to clients. */\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\t/**\n\t * Monotonic version-number allocator, never decremented: the next upload\n\t * reserves this value then advances the counter, so a delete-latest-then-reupload\n\t * mints a fresh number and `fileKey` instead of reusing one — otherwise a stale\n\t * storage blob could serve the old version's bytes under the new content's key.\n\t * Starts at 2 after v1 is created.\n\t */\n\tnextVersionNumber: number;\n\t/**\n\t * Both null only during the brief `pending` window between metadata create\n\t * and v1 upload; otherwise both reference live `DefinitionVersion` rows.\n\t */\n\tliveVersionId: string | null;\n\tdraftVersionId: string | null;\n\t/**\n\t * The Grasshopper document GUID (lowercase) from the schema Compute\n\t * extracted at the last upload that carried one. A copied `.gh` keeps its\n\t * GUID, so this suggests a match and never proves one.\n\t */\n\tsourceDocumentId?: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\t/** Soft-delete marker, independent of `status`: a store filters this out regardless of `archived`. */\n\tdeletedAt?: string | null;\n}\n\n/**\n * List-row projection of a `DefinitionRecord`; the shape `GET /api/v1/definitions` returns.\n *\n * Deliberately narrower than the full record — `ownerId`, `createdBy`,\n * `updatedBy`, `solveCacheLimit` are internal. v1 is additive-only, so a field\n * published here can only be removed in v2: narrowing later is not an option.\n *\n * `liveVersionId` is the pointer, not a version number — the number isn't a\n * native column, so resolving it would cost a query per row.\n */\nexport interface DefinitionListItem {\n\tguid: string;\n\tprojectId: string;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\tliveVersionId: string | null;\n\t/** See {@link DefinitionRecord.sourceDocumentId}. */\n\tsourceDocumentId: string | null;\n\tupdatedAt: string;\n}\n\nexport function toDefinitionListItem(r: DefinitionRecord): DefinitionListItem {\n\treturn {\n\t\tguid: r.guid,\n\t\tprojectId: r.projectId,\n\t\tdisplayName: r.displayName,\n\t\tdescription: r.description,\n\t\tcategory: r.category,\n\t\ttags: r.tags,\n\t\tcoverImage: r.coverImage,\n\t\tstatus: r.status,\n\t\tsolveCount: r.solveCount,\n\t\tliveVersionId: r.liveVersionId,\n\t\tsourceDocumentId: r.sourceDocumentId ?? null,\n\t\tupdatedAt: r.updatedAt\n\t};\n}\n\n/**\n * Omits immutable fields and provider-managed ones (use\n * `setLiveVersion`/`setDraftVersion` for channel pointers).\n *\n * - `undefined` — leave unchanged\n * - `null` — clear (only on nullable fields)\n * - value — set\n *\n * Use `incrementSolveCount` for atomic +1 bumps instead of patching `solveCount`.\n */\nexport interface DefinitionRecordPatch {\n\tdisplayName?: string;\n\tdescription?: string | null;\n\tcategory?: string | null;\n\ttags?: string[] | null;\n\tcoverImage?: string | null;\n\tprojectId?: string;\n\tcomputeServerId?: string | null;\n\t/** L2 cache quota (see {@link DefinitionRecord.solveCacheLimit}); `null` clears to inherit. */\n\tsolveCacheLimit?: number | null;\n\tstatus?: DefinitionStatus;\n\townerId?: string;\n\tsourceDocumentId?: string | null;\n}\n\nexport type DefinitionChannel = z.infer<typeof DefinitionChannelSchema>;\n"],"mappings":";AAMA,IAAa,gBAA0B,CAAC,OAAO,MAAM;AAErD,IAAa,4BAAoD;CAChE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;AACT;AAuHA,SAAgB,qBAAqB,GAAyC;CAC7E,OAAO;EACN,MAAM,EAAE;EACR,WAAW,EAAE;EACb,aAAa,EAAE;EACf,aAAa,EAAE;EACf,UAAU,EAAE;EACZ,MAAM,EAAE;EACR,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,YAAY,EAAE;EACd,eAAe,EAAE;EACjB,kBAAkB,EAAE,oBAAoB;EACxC,WAAW,EAAE;CACd;AACD"}
1
+ {"version":3,"file":"types2.js","names":[],"sources":["../../../../platform/src/definitions/types.ts"],"sourcesContent":["import type { UISchema } from '@selvajs/schemas';\nimport type { z } from 'zod';\nimport type { ListOptions } from '../pagination.js';\nimport type { DefinitionChannelSchema, DefinitionStatusSchema } from './schemas.js';\n\nconst DEFINITION_FILE_EXTS = ['gh', 'ghx'] as const;\n\nexport type DefinitionFileExt = (typeof DEFINITION_FILE_EXTS)[number];\n\nexport const GH_EXTENSIONS: string[] = DEFINITION_FILE_EXTS.map((ext) => `.${ext}`);\n\nexport const COVER_IMAGE_CONTENT_TYPES: Record<string, string> = {\n\t'.jpg': 'image/jpeg',\n\t'.jpeg': 'image/jpeg',\n\t'.png': 'image/png',\n\t'.webp': 'image/webp',\n\t'.gif': 'image/gif'\n};\n\n/**\n * - `pending` — internal: metadata written, blob upload may be in flight.\n * - `draft` — work in progress, not visible to runners.\n * - `published` — live, visible to all with solve access.\n * - `archived` — retired but preserved; restore via `update({ status: 'draft' | 'published' })`.\n *\n * List endpoints filter out `pending` and `archived` by default (opt in via\n * `DefinitionListOptions.includePending`/`includeArchived`, or an explicit `statuses` filter).\n */\nexport type DefinitionStatus = z.infer<typeof DefinitionStatusSchema> | 'pending';\n\n/** Definition-specific filtering on top of `ListOptions`. */\nexport interface DefinitionListOptions extends Omit<ListOptions, 'orderBy'> {\n\torderBy?: 'createdAt' | 'updatedAt' | 'name' | 'solveCount';\n\t/** Include `status='pending'` records. Default false. */\n\tincludePending?: boolean;\n\t/** Include `status='archived'` records. Default false. */\n\tincludeArchived?: boolean;\n\t/**\n\t * Filter to specific editorial statuses. Omit for the default view (all\n\t * non-pending, non-archived). When set, `includePending` / `includeArchived`\n\t * are ignored.\n\t */\n\tstatuses?: DefinitionStatus[];\n\t/**\n\t * Restrict to definitions in these projects. An empty array matches nothing,\n\t * distinct from omitting the filter.\n\t *\n\t * Applying this in the adapter query — rather than filtering a fetched page\n\t * afterwards — is what keeps `limit` and `nextCursor` accurate: filtering\n\t * post-fetch can return a page of 50 with 3 items.\n\t */\n\tprojectIds?: readonly string[];\n\t/** Only definitions whose `sourceDocumentId` equals this lowercase GUID. */\n\tsourceDocumentId?: string;\n}\n\n/**\n * Immutable snapshot of a definition's `.gh` file at a point in time. New\n * uploads create new versions; rollback re-points the parent's\n * `liveVersionId` rather than mutating the version itself.\n */\nexport interface DefinitionVersion {\n\tid: string;\n\tdefinitionId: string;\n\t/** Allocated from `DefinitionRecord.nextVersionNumber`; see that field for the numbering guarantee. */\n\tversionNumber: number;\n\tfileExt: DefinitionFileExt;\n\t/** Full storage key. Opaque to callers. */\n\tfileKey: string;\n\toriginalFilename?: string;\n\tuploadedBy: string;\n\tuploadedAt: string;\n\t/** Free-form note describing what changed in this version. */\n\tchangeNote?: string;\n\t/**\n\t * Compute-extracted UI schema, cached at upload so the render path doesn't\n\t * re-fetch it from Rhino.Compute on every load. Optional only for the\n\t * lazy-backfill bridge on pre-existing versions; new uploads always set it.\n\t */\n\tschema?: UISchema;\n\t/** ISO timestamp of when `schema` was extracted. */\n\tschemaExtractedAt?: string;\n}\n\nexport interface DefinitionRecord {\n\tguid: string;\n\tprojectId: string;\n\t/** Current owner — separate from `createdBy` so ownership can transfer. */\n\townerId: string;\n\tcreatedBy: string;\n\tupdatedBy: string;\n\t/** Falls back to the org default, then the platform default. */\n\tcomputeServerId?: string;\n\t/**\n\t * Per-definition quota for the shared solve-result cache (`ISolveResultCache`):\n\t * `0` = caching off, `N` = keep at most N cached solves, absent = inherit the\n\t * backend default.\n\t */\n\tsolveCacheLimit?: number;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\t/** Provider-dependent public URL — must be safe to send to clients. */\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\t/**\n\t * Monotonic version-number allocator, never decremented: the next upload\n\t * reserves this value then advances the counter, so a delete-latest-then-reupload\n\t * mints a fresh number and `fileKey` instead of reusing one — otherwise a stale\n\t * storage blob could serve the old version's bytes under the new content's key.\n\t * Starts at 2 after v1 is created.\n\t */\n\tnextVersionNumber: number;\n\t/**\n\t * Both null only during the brief `pending` window between metadata create\n\t * and v1 upload; otherwise both reference live `DefinitionVersion` rows.\n\t */\n\tliveVersionId: string | null;\n\tdraftVersionId: string | null;\n\t/**\n\t * The Grasshopper document GUID (lowercase) from the schema Compute\n\t * extracted at the last upload that carried one. A copied `.gh` keeps its\n\t * GUID, so this suggests a match and never proves one.\n\t */\n\tsourceDocumentId?: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\t/** Soft-delete marker, independent of `status`: a store filters this out regardless of `archived`. */\n\tdeletedAt?: string | null;\n}\n\n/**\n * List-row projection of a `DefinitionRecord`; the shape `GET /api/v1/definitions` returns.\n *\n * Deliberately narrower than the full record — `ownerId`, `createdBy`,\n * `updatedBy`, `solveCacheLimit` are internal. v1 is additive-only, so a field\n * published here can only be removed in v2: narrowing later is not an option.\n *\n * `liveVersionId` is the pointer, not a version number — the number isn't a\n * native column, so resolving it would cost a query per row.\n */\nexport interface DefinitionListItem {\n\tguid: string;\n\tprojectId: string;\n\tdisplayName: string;\n\tdescription?: string;\n\tcategory?: string;\n\ttags?: string[];\n\tcoverImage?: string;\n\tstatus: DefinitionStatus;\n\tsolveCount: number;\n\tliveVersionId: string | null;\n\t/** See {@link DefinitionRecord.sourceDocumentId}. */\n\tsourceDocumentId: string | null;\n\tupdatedAt: string;\n}\n\nexport function toDefinitionListItem(r: DefinitionRecord): DefinitionListItem {\n\treturn {\n\t\tguid: r.guid,\n\t\tprojectId: r.projectId,\n\t\tdisplayName: r.displayName,\n\t\tdescription: r.description,\n\t\tcategory: r.category,\n\t\ttags: r.tags,\n\t\tcoverImage: r.coverImage,\n\t\tstatus: r.status,\n\t\tsolveCount: r.solveCount,\n\t\tliveVersionId: r.liveVersionId,\n\t\tsourceDocumentId: r.sourceDocumentId ?? null,\n\t\tupdatedAt: r.updatedAt\n\t};\n}\n\n/**\n * Omits immutable fields and provider-managed ones (use\n * `setLiveVersion`/`setDraftVersion` for channel pointers).\n *\n * - `undefined` — leave unchanged\n * - `null` — clear (only on nullable fields)\n * - value — set\n *\n * Use `incrementSolveCount` for atomic +1 bumps instead of patching `solveCount`.\n */\nexport interface DefinitionRecordPatch {\n\tdisplayName?: string;\n\tdescription?: string | null;\n\tcategory?: string | null;\n\ttags?: string[] | null;\n\tcoverImage?: string | null;\n\tprojectId?: string;\n\tcomputeServerId?: string | null;\n\t/** L2 cache quota (see {@link DefinitionRecord.solveCacheLimit}); `null` clears to inherit. */\n\tsolveCacheLimit?: number | null;\n\tstatus?: DefinitionStatus;\n\townerId?: string;\n\tsourceDocumentId?: string | null;\n}\n\nexport type DefinitionChannel = z.infer<typeof DefinitionChannelSchema>;\n"],"mappings":"AASA,IAAa,gBAA0B,CAJT,MAAM,KAIG,CAAA,CAAqB,KAAK,QAAQ,IAAI,KAAK;AAElF,IAAa,4BAAoD;CAChE,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,QAAQ;AACT;AA8IA,SAAgB,qBAAqB,GAAyC;CAC7E,OAAO;EACN,MAAM,EAAE;EACR,WAAW,EAAE;EACb,aAAa,EAAE;EACf,aAAa,EAAE;EACf,UAAU,EAAE;EACZ,MAAM,EAAE;EACR,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,YAAY,EAAE;EACd,eAAe,EAAE;EACjB,kBAAkB,EAAE,oBAAoB;EACxC,WAAW,EAAE;CACd;AACD"}
@@ -1,4 +1,4 @@
1
- import { G as canCreateDefinition, H as outsideTokenOrg, J as canEditDefinition, U as scopeAllows, Z as canView, o as projectAccessInputFromRowsWith } from "./access.js";
1
+ import { K as canCreateDefinition, Q as canView, U as outsideTokenOrg, W as scopeAllows, Y as canEditDefinition, o as projectAccessInputFromRowsWith } from "./access.js";
2
2
  import { t as SYSTEM_CONTEXT } from "./context.js";
3
3
  /** For adapters paging by offset. Junk and negatives read as the first page. */
4
4
  function decodeOffsetCursor(cursor) {
@@ -1 +1 @@
1
- {"version":3,"file":"visibility.js","names":[],"sources":["../../../../platform/src/pagination.ts","../../../../server/src/definitions/visibility.ts"],"sourcesContent":["import type { DefinitionStatus } from './definitions/types.js';\n\n/**\n * Cursor-paginated list options. Adapters default to limit=50 and clamp limit to\n * `MAX_PAGE_LIMIT`. Order is `createdAt` desc unless a store says otherwise: local\n * definitions default to `name` asc, and the Supabase member, invite and token\n * lists have one fixed order and ignore `orderBy`.\n *\n * Cursors are opaque — adapters may use row ids, offsets, or keyset encodings.\n * Callers must not inspect them.\n */\nexport interface ListOptions {\n\tlimit?: number;\n\tcursor?: string;\n\torderBy?: 'createdAt' | 'updatedAt' | 'name';\n\t/** Default: 'desc'. */\n\torderDir?: 'asc' | 'desc';\n}\n\n/** Definition-specific filtering on top of `ListOptions`. */\nexport interface DefinitionListOptions extends Omit<ListOptions, 'orderBy'> {\n\torderBy?: 'createdAt' | 'updatedAt' | 'name' | 'solveCount';\n\t/** Include `status='pending'` records. Default false. */\n\tincludePending?: boolean;\n\t/** Include `status='archived'` records. Default false. */\n\tincludeArchived?: boolean;\n\t/**\n\t * Filter to specific editorial statuses. Omit for the default view (all\n\t * non-pending, non-archived). When set, `includePending` / `includeArchived`\n\t * are ignored.\n\t */\n\tstatuses?: DefinitionStatus[];\n\t/**\n\t * Restrict to definitions in these projects. An empty array matches nothing,\n\t * distinct from omitting the filter.\n\t *\n\t * Applying this in the adapter query — rather than filtering a fetched page\n\t * afterwards — is what keeps `limit` and `nextCursor` accurate: filtering\n\t * post-fetch can return a page of 50 with 3 items.\n\t */\n\tprojectIds?: readonly string[];\n\t/** Only definitions whose `sourceDocumentId` equals this lowercase GUID. */\n\tsourceDocumentId?: string;\n}\n\nexport interface Page<T> {\n\titems: T[];\n\tnextCursor?: string;\n}\n\nexport const DEFAULT_PAGE_LIMIT = 50;\nexport const MAX_PAGE_LIMIT = 200;\n\n/** For adapters paging by offset. Junk and negatives read as the first page. */\nexport function decodeOffsetCursor(cursor: string | undefined): number {\n\tconst offset = cursor ? parseInt(cursor, 10) : 0;\n\treturn Number.isFinite(offset) && offset >= 0 ? offset : 0;\n}\n\nexport function encodeOffsetCursor(offset: number): string {\n\treturn String(offset);\n}\n\ntype PageFetcher<T> = (page: { limit: number; cursor?: string }) => Promise<Page<T>>;\n\n/**\n * Every page of a list, in order. One call stops at `MAX_PAGE_LIMIT` without saying so, which is\n * fatal for a read that must see every row. Break out of the loop to stop reading.\n */\nexport async function* walkPages<T>(fetchPage: PageFetcher<T>): AsyncGenerator<Page<T>> {\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst page = await fetchPage({ limit: MAX_PAGE_LIMIT, cursor });\n\t\tyield page;\n\t\tcursor = page.nextCursor;\n\t} while (cursor);\n}\n\n/** Every row of a list, across all its pages. */\nexport async function listAll<T>(fetchPage: PageFetcher<T>): Promise<T[]> {\n\tconst items: T[] = [];\n\tfor await (const page of walkPages(fetchPage)) items.push(...page.items);\n\treturn items;\n}\n\n/** The effective page size for a requested limit. */\nexport function clampPageLimit(limit: number | undefined): number {\n\tconst requested = limit ?? DEFAULT_PAGE_LIMIT;\n\tif (!Number.isFinite(requested)) return DEFAULT_PAGE_LIMIT;\n\treturn Math.min(Math.max(1, Math.floor(requested)), MAX_PAGE_LIMIT);\n}\n","/**\n * Visibility-filtered definition reads, shared by the library page load and\n * `GET /api/v1/definitions`.\n *\n * **This is a tenancy boundary.** The project scan runs as `SYSTEM_CONTEXT` so\n * cross-org `public` projects are reachable when `ALLOW_CROSS_ORG_PUBLIC` is on;\n * `canView` over the fetched membership rows is the only thing keeping another\n * org's projects out of the result. The definition list itself is then filtered\n * *in the query* via `projectIds`, so the cursor is applied after visibility\n * rather than over a page that gets thinned afterwards.\n *\n * Cost is constant in the number of orgs and projects: three bulk membership\n * reads regardless of N. Anything added here must keep that property — a\n * per-project `await` inside a loop reintroduces the N+1 this replaced.\n */\n\nimport {\n\tSYSTEM_CONTEXT,\n\tcanCreateDefinition,\n\tcanEditDefinition,\n\tcanView,\n\toutsideTokenOrg,\n\tscopeAllows,\n\twalkPages\n} from '@selvajs/platform';\nimport type {\n\tDefinitionListOptions,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tOrgMember,\n\tPage,\n\tPlatformProjectGrant,\n\tProject,\n\tProjectMember,\n\tRequestContext\n} from '@selvajs/platform';\nimport { projectAccessInputFromRowsWith } from '../access/index.js';\nimport type { SelvaDeps } from '../api/deps.js';\n\n/** Upper bound on the org/project scan. Visibility needs the whole set. */\nconst SCAN_LIMIT = 200;\n\n/**\n * The stores this module reads. Required at every call site.\n *\n * These used to fall back to a host's composition root, which welded this\n * tenancy boundary to one app's boot — anything importing it started the whole\n * application. Handlers pass `req.deps`; page loads pass their own equivalent.\n * That is what lets a second host on a different provider set reuse this\n * boundary instead of rebuilding it.\n */\nexport type VisibilityDeps = Pick<\n\tSelvaDeps,\n\t'orgs' | 'projects' | 'platformProjectGrants' | 'definitionMeta' | 'flag'\n>;\n\n/**\n * The caller's accessible project set plus the membership rows it was derived\n * from, so a caller needing a second rule (`canEdit` on the projects page)\n * can evaluate it with no further I/O.\n */\nexport interface AccessibleProjectSet {\n\tprojects: Project[];\n\t/** Every project the scan saw, keyed by id — for name lookups on rows. */\n\tallById: Map<string, Project>;\n\t/** The caller's project-membership row per scanned project (`null` = not a member). */\n\tmemberByProjectId: Map<string, ProjectMember | null>;\n\t/** The caller's org-membership row per scanned org (`null` = not a member). */\n\torgMemberByOrgId: Map<string, OrgMember | null>;\n\t/** Grants per scanned `platform` project; absent for every other visibility. */\n\tgrantsByProjectId: Map<string, PlatformProjectGrant[]>;\n}\n\n/**\n * Resolve the caller's accessible project set in a constant number of queries.\n * Platform grants are fetched only for `platform`-visibility projects —\n * `canView` short-circuits before reading them for every other visibility.\n */\nexport async function resolveAccessibleProjects(\n\tctx: RequestContext,\n\tdeps: VisibilityDeps\n): Promise<AccessibleProjectSet> {\n\tconst orgs = deps.orgs;\n\tconst projectStore = deps.projects;\n\tconst grantStore = deps.platformProjectGrants;\n\n\tconst orgsPage = await orgs.listOrgs(SYSTEM_CONTEXT, { limit: SCAN_LIMIT });\n\t// An API token sees its own org only, cross-org public projects included.\n\tconst orgIds = orgsPage.items.map((o) => o.id).filter((id) => !outsideTokenOrg(ctx, id));\n\n\tconst projectPages = await Promise.all(\n\t\torgIds.map((orgId) => projectStore.listProjects(SYSTEM_CONTEXT, orgId, { limit: SCAN_LIMIT }))\n\t);\n\tconst allProjects = projectPages.flatMap((p) => p.items);\n\tconst projectIds = allProjects.map((p) => p.id);\n\tconst platformProjectIds = allProjects\n\t\t.filter((p) => p.visibility === 'platform')\n\t\t.map((p) => p.id);\n\n\tconst [orgMemberByOrgId, memberByProjectId, grantsByProjectId] = await Promise.all([\n\t\torgs.getOrgMembersFor(SYSTEM_CONTEXT, orgIds, ctx.userId),\n\t\tprojectStore.getProjectMembersFor(SYSTEM_CONTEXT, projectIds, ctx.userId),\n\t\tplatformProjectIds.length\n\t\t\t? grantStore.listByProjects(SYSTEM_CONTEXT, platformProjectIds)\n\t\t\t: Promise.resolve(new Map<string, PlatformProjectGrant[]>())\n\t]);\n\n\tconst projects = allProjects.filter((project) =>\n\t\tcanView(\n\t\t\tprojectAccessInputFromRowsWith({ deps }, ctx, project, {\n\t\t\t\tmember: memberByProjectId.get(project.id) ?? null,\n\t\t\t\torgMember: orgMemberByOrgId.get(project.orgId) ?? null,\n\t\t\t\tplatformGrants: grantsByProjectId.get(project.id) ?? []\n\t\t\t})\n\t\t)\n\t);\n\n\treturn {\n\t\tprojects,\n\t\tallById: new Map(allProjects.map((p) => [p.id, p])),\n\t\tmemberByProjectId,\n\t\torgMemberByOrgId,\n\t\tgrantsByProjectId\n\t};\n}\n\n/**\n * Whether the caller may create a definition in at least one project of\n * `orgId`, by the same rule `requireCanCreateDefinition` applies. Reads the\n * org's projects a page at a time and stops at the first that passes.\n */\nexport async function canCreateDefinitionInOrg(\n\tctx: RequestContext,\n\torgId: string,\n\tdeps: VisibilityDeps\n): Promise<boolean> {\n\tconst orgMember =\n\t\t(await deps.orgs.getOrgMembersFor(SYSTEM_CONTEXT, [orgId], ctx.userId)).get(orgId) ?? null;\n\tconst pages = walkPages((page) => deps.projects.listProjects(SYSTEM_CONTEXT, orgId, page));\n\tfor await (const page of pages) {\n\t\tconst platformIds = page.items.filter((p) => p.visibility === 'platform').map((p) => p.id);\n\t\tconst [members, grants] = await Promise.all([\n\t\t\tdeps.projects.getProjectMembersFor(\n\t\t\t\tSYSTEM_CONTEXT,\n\t\t\t\tpage.items.map((p) => p.id),\n\t\t\t\tctx.userId\n\t\t\t),\n\t\t\tplatformIds.length\n\t\t\t\t? deps.platformProjectGrants.listByProjects(SYSTEM_CONTEXT, platformIds)\n\t\t\t\t: Promise.resolve(new Map<string, PlatformProjectGrant[]>())\n\t\t]);\n\t\tconst allowed = page.items.some((project) =>\n\t\t\tcanCreateDefinition(\n\t\t\t\tprojectAccessInputFromRowsWith({ deps }, ctx, project, {\n\t\t\t\t\tmember: members.get(project.id) ?? null,\n\t\t\t\t\torgMember,\n\t\t\t\t\tplatformGrants: grants.get(project.id) ?? []\n\t\t\t\t})\n\t\t\t)\n\t\t);\n\t\tif (allowed) return true;\n\t}\n\treturn false;\n}\n\nexport interface ListVisibleDefinitionsResult extends Page<DefinitionRecord> {\n\t/** For resolving a definition's `projectId` to a name. */\n\tprojects: Project[];\n}\n\n/**\n * `opts.projectId` narrows to one project; a caller who cannot view it gets an\n * empty page rather than a 403, so this never reveals that a project exists.\n */\nexport async function listVisibleDefinitions(\n\tctx: RequestContext,\n\topts: DefinitionListOptions & { projectId?: string } = {},\n\tdeps: VisibilityDeps\n): Promise<ListVisibleDefinitionsResult> {\n\tconst { projectId, ...listOpts } = opts;\n\tconst { projects } = await resolveAccessibleProjects(ctx, deps);\n\n\tconst scoped = projectId ? projects.filter((p) => p.id === projectId) : projects;\n\t// An empty id set matches nothing, which is what a caller with no visible\n\t// projects should get — not an unfiltered listing.\n\tconst page = await deps.definitionMeta.list(ctx, {\n\t\t...listOpts,\n\t\tprojectIds: scoped.map((p) => p.id)\n\t});\n\n\treturn { items: page.items, nextCursor: page.nextCursor, projects: scoped };\n}\n\n/**\n * Editable definitions whose `sourceDocumentId` is `documentId`: the ones the\n * caller could upload a new version of, by {@link mayUploadToDefinition}.\n *\n * Commons projects are scanned too, since a caller owns their own uploads there\n * without edit rights on the project; rows they can't edit are dropped after\n * the query, so a page can come back short while `nextCursor` stays valid.\n */\nexport async function listEditableDefinitionsByDocument(\n\tctx: RequestContext,\n\tdocumentId: string,\n\topts: DefinitionListOptions & { projectId?: string },\n\tdeps: VisibilityDeps\n): Promise<Page<DefinitionRecord>> {\n\tconst { projectId, ...listOpts } = opts;\n\tconst set = await resolveAccessibleProjects(ctx, deps);\n\tconst rowsFor = (project: Project) => ({\n\t\tmember: set.memberByProjectId.get(project.id) ?? null,\n\t\torgMember: set.orgMemberByOrgId.get(project.orgId) ?? null,\n\t\tplatformGrants: set.grantsByProjectId.get(project.id) ?? []\n\t});\n\tconst candidates = set.projects.filter(\n\t\t(p) =>\n\t\t\t(!projectId || p.id === projectId) &&\n\t\t\tcanCreateDefinition(projectAccessInputFromRowsWith({ deps }, ctx, p, rowsFor(p)))\n\t);\n\n\tconst page = await deps.definitionMeta.list(ctx, {\n\t\t...listOpts,\n\t\tsourceDocumentId: documentId,\n\t\tprojectIds: candidates.map((p) => p.id)\n\t});\n\tconst items = page.items.filter((record) => {\n\t\tconst project = set.allById.get(record.projectId);\n\t\treturn project\n\t\t\t? mayUploadToDefinition(ctx, { record, project, ...rowsFor(project) }, deps)\n\t\t\t: false;\n\t});\n\treturn { items, nextCursor: page.nextCursor };\n}\n\n/** A visible definition and the caller's rows that decided it. */\nexport interface VisibleDefinition {\n\trecord: DefinitionRecord;\n\tproject: Project;\n\tmember: ProjectMember | null;\n\torgMember: OrgMember | null;\n}\n\n/**\n * One definition, or `null` when the caller cannot view its project.\n *\n * Returns `null` rather than throwing 403 so callers surface a 404: a public\n * API that answers \"forbidden\" for a guid the caller cannot see turns\n * `/definitions/{guid}` into a cross-tenant existence oracle.\n */\nexport async function getVisibleDefinition(\n\tctx: RequestContext,\n\tguid: string,\n\tdeps: VisibilityDeps\n): Promise<DefinitionRecord | null> {\n\treturn (await loadVisibleDefinition(ctx, guid, deps))?.record ?? null;\n}\n\n/** {@link getVisibleDefinition} with the rows it read, for a second rule over the same caller. */\nexport async function loadVisibleDefinition(\n\tctx: RequestContext,\n\tguid: string,\n\tdeps: VisibilityDeps\n): Promise<VisibleDefinition | null> {\n\tconst meta = deps.definitionMeta;\n\tconst projectStore = deps.projects;\n\n\tconst record = await meta.get(ctx, guid);\n\tif (!record) return null;\n\n\tconst project = await projectStore.getProject(SYSTEM_CONTEXT, record.projectId);\n\tif (!project || outsideTokenOrg(ctx, project.orgId)) return null;\n\n\tconst [orgMembers, projectMembers, grants] = await Promise.all([\n\t\tdeps.orgs.getOrgMembersFor(SYSTEM_CONTEXT, [project.orgId], ctx.userId),\n\t\tprojectStore.getProjectMembersFor(SYSTEM_CONTEXT, [project.id], ctx.userId),\n\t\tproject.visibility === 'platform'\n\t\t\t? deps.platformProjectGrants.listByProject(SYSTEM_CONTEXT, project.id)\n\t\t\t: Promise.resolve([] as PlatformProjectGrant[])\n\t]);\n\n\tconst member = projectMembers.get(project.id) ?? null;\n\tconst orgMember = orgMembers.get(project.orgId) ?? null;\n\tconst allowed = canView(\n\t\tprojectAccessInputFromRowsWith({ deps }, ctx, project, {\n\t\t\tmember,\n\t\t\torgMember,\n\t\t\tplatformGrants: grants\n\t\t})\n\t);\n\treturn allowed ? { record, project, member, orgMember } : null;\n}\n\n/**\n * May the caller upload a version of this definition and make one live? The\n * rule `requireEditableDefinition` applies, and for an API token its `upload`\n * scope on the definition, which is what those routes check.\n */\nexport function mayUploadToDefinition(\n\tctx: RequestContext,\n\t{ record, project, member, orgMember }: VisibleDefinition,\n\tdeps: Pick<VisibilityDeps, 'flag'>\n): boolean {\n\treturn (\n\t\tscopeAllows(ctx, 'upload', { definitionId: record.guid, projectId: project.id }) &&\n\t\tcanEditDefinition({\n\t\t\tproject,\n\t\t\tdefinition: record,\n\t\t\tmember,\n\t\t\torgMember,\n\t\t\tuserId: ctx.userId,\n\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\tenablePlatformProjects: deps.flag('ENABLE_PLATFORM_PROJECTS')\n\t\t})\n\t);\n}\n\n/**\n * One version of a definition the caller can view, including its cached\n * `schema`. `null` when the definition is invisible, the version is missing, or\n * the version belongs to a different definition — a caller must not be able to\n * read an arbitrary version by pairing it with a guid they can see.\n */\nexport async function loadVisibleVersion(\n\tctx: RequestContext,\n\tguid: string,\n\tversionId: string,\n\tdeps: VisibilityDeps\n): Promise<DefinitionVersion | null> {\n\tconst record = await getVisibleDefinition(ctx, guid, deps);\n\tif (!record) return null;\n\n\tconst version = await deps.definitionMeta.getVersion(ctx, versionId);\n\tif (!version || version.definitionId !== record.guid) return null;\n\treturn version;\n}\n"],"mappings":";;;AAsDA,SAAgB,mBAAmB,QAAoC;CACtE,MAAM,SAAS,SAAS,SAAS,QAAQ,EAAE,IAAI;CAC/C,OAAO,OAAO,SAAS,MAAM,KAAK,UAAU,IAAI,SAAS;AAC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,KAAK,UAAU;EAAE,cAAc,OAAO;EAAM,WAAW,QAAQ;CAAG,CAAC,KAC/E,kBAAkB;EACjB;EACA,YAAY;EACZ;EACA;EACA,QAAQ,IAAI;EACZ,qBAAqB,IAAI;EACzB,wBAAwB,KAAK,KAAK,0BAA0B;CAC7D,CAAC;AAEH;;;;;;;AAQA,eAAsB,mBACrB,KACA,MACA,WACA,MACoC;CACpC,MAAM,SAAS,MAAM,qBAAqB,KAAK,MAAM,IAAI;CACzD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,UAAU,MAAM,KAAK,eAAe,WAAW,KAAK,SAAS;CACnE,IAAI,CAAC,WAAW,QAAQ,iBAAiB,OAAO,MAAM,OAAO;CAC7D,OAAO;AACR"}
1
+ {"version":3,"file":"visibility.js","names":[],"sources":["../../../../platform/src/pagination.ts","../../../../server/src/definitions/visibility.ts"],"sourcesContent":["/**\n * Cursor-paginated list options. Adapters default `limit` to `DEFAULT_PAGE_LIMIT` and\n * clamp it to `MAX_PAGE_LIMIT` (`clampPageLimit`). Order is `createdAt` desc unless the\n * store documents another; a store with one fixed order may ignore `orderBy`.\n *\n * Cursors are opaque — adapters may use row ids, offsets, or keyset encodings.\n * Callers must not inspect them.\n */\nexport interface ListOptions {\n\tlimit?: number;\n\tcursor?: string;\n\torderBy?: 'createdAt' | 'updatedAt' | 'name';\n\t/** Default: 'desc'. */\n\torderDir?: 'asc' | 'desc';\n}\n\nexport interface Page<T> {\n\titems: T[];\n\tnextCursor?: string;\n}\n\nexport const DEFAULT_PAGE_LIMIT = 50;\nexport const MAX_PAGE_LIMIT = 200;\n\n/** For adapters paging by offset. Junk and negatives read as the first page. */\nexport function decodeOffsetCursor(cursor: string | undefined): number {\n\tconst offset = cursor ? parseInt(cursor, 10) : 0;\n\treturn Number.isFinite(offset) && offset >= 0 ? offset : 0;\n}\n\nexport function encodeOffsetCursor(offset: number): string {\n\treturn String(offset);\n}\n\ntype PageFetcher<T> = (page: { limit: number; cursor?: string }) => Promise<Page<T>>;\n\n/**\n * Every page of a list, in order. One call stops at `MAX_PAGE_LIMIT` without saying so, which is\n * fatal for a read that must see every row. Break out of the loop to stop reading.\n */\nexport async function* walkPages<T>(fetchPage: PageFetcher<T>): AsyncGenerator<Page<T>> {\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst page = await fetchPage({ limit: MAX_PAGE_LIMIT, cursor });\n\t\tyield page;\n\t\tcursor = page.nextCursor;\n\t} while (cursor);\n}\n\n/** Every row of a list, across all its pages. */\nexport async function listAll<T>(fetchPage: PageFetcher<T>): Promise<T[]> {\n\tconst items: T[] = [];\n\tfor await (const page of walkPages(fetchPage)) items.push(...page.items);\n\treturn items;\n}\n\n/** The effective page size for a requested limit. */\nexport function clampPageLimit(limit: number | undefined): number {\n\tconst requested = limit ?? DEFAULT_PAGE_LIMIT;\n\tif (!Number.isFinite(requested)) return DEFAULT_PAGE_LIMIT;\n\treturn Math.min(Math.max(1, Math.floor(requested)), MAX_PAGE_LIMIT);\n}\n","/**\n * Visibility-filtered definition reads, shared by the library page load and\n * `GET /api/v1/definitions`.\n *\n * **This is a tenancy boundary.** The project scan runs as `SYSTEM_CONTEXT` so\n * cross-org `public` projects are reachable when `ALLOW_CROSS_ORG_PUBLIC` is on;\n * `canView` over the fetched membership rows is the only thing keeping another\n * org's projects out of the result. The definition list itself is then filtered\n * *in the query* via `projectIds`, so the cursor is applied after visibility\n * rather than over a page that gets thinned afterwards.\n *\n * Cost is constant in the number of orgs and projects: three bulk membership\n * reads regardless of N. Anything added here must keep that property — a\n * per-project `await` inside a loop reintroduces the N+1 this replaced.\n */\n\nimport {\n\tSYSTEM_CONTEXT,\n\tcanCreateDefinition,\n\tcanEditDefinition,\n\tcanView,\n\toutsideTokenOrg,\n\tscopeAllows,\n\twalkPages\n} from '@selvajs/platform';\nimport type {\n\tDefinitionListOptions,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tOrgMember,\n\tPage,\n\tPlatformProjectGrant,\n\tProject,\n\tProjectMember,\n\tRequestContext\n} from '@selvajs/platform';\nimport { projectAccessInputFromRowsWith } from '../access/index.js';\nimport type { SelvaDeps } from '../api/deps.js';\n\n/** Upper bound on the org/project scan. Visibility needs the whole set. */\nconst SCAN_LIMIT = 200;\n\n/**\n * The stores this module reads. Required at every call site.\n *\n * These used to fall back to a host's composition root, which welded this\n * tenancy boundary to one app's boot — anything importing it started the whole\n * application. Handlers pass `req.deps`; page loads pass their own equivalent.\n * That is what lets a second host on a different provider set reuse this\n * boundary instead of rebuilding it.\n */\nexport type VisibilityDeps = Pick<\n\tSelvaDeps,\n\t'orgs' | 'projects' | 'platformProjectGrants' | 'definitionMeta' | 'flag'\n>;\n\n/**\n * The caller's accessible project set plus the membership rows it was derived\n * from, so a caller needing a second rule (`canEdit` on the projects page)\n * can evaluate it with no further I/O.\n */\nexport interface AccessibleProjectSet {\n\tprojects: Project[];\n\t/** Every project the scan saw, keyed by id — for name lookups on rows. */\n\tallById: Map<string, Project>;\n\t/** The caller's project-membership row per scanned project (`null` = not a member). */\n\tmemberByProjectId: Map<string, ProjectMember | null>;\n\t/** The caller's org-membership row per scanned org (`null` = not a member). */\n\torgMemberByOrgId: Map<string, OrgMember | null>;\n\t/** Grants per scanned `platform` project; absent for every other visibility. */\n\tgrantsByProjectId: Map<string, PlatformProjectGrant[]>;\n}\n\n/**\n * Resolve the caller's accessible project set in a constant number of queries.\n * Platform grants are fetched only for `platform`-visibility projects —\n * `canView` short-circuits before reading them for every other visibility.\n */\nexport async function resolveAccessibleProjects(\n\tctx: RequestContext,\n\tdeps: VisibilityDeps\n): Promise<AccessibleProjectSet> {\n\tconst orgs = deps.orgs;\n\tconst projectStore = deps.projects;\n\tconst grantStore = deps.platformProjectGrants;\n\n\tconst orgsPage = await orgs.listOrgs(SYSTEM_CONTEXT, { limit: SCAN_LIMIT });\n\t// An API token sees its own org only, cross-org public projects included.\n\tconst orgIds = orgsPage.items.map((o) => o.id).filter((id) => !outsideTokenOrg(ctx, id));\n\n\tconst projectPages = await Promise.all(\n\t\torgIds.map((orgId) => projectStore.listProjects(SYSTEM_CONTEXT, orgId, { limit: SCAN_LIMIT }))\n\t);\n\tconst allProjects = projectPages.flatMap((p) => p.items);\n\tconst projectIds = allProjects.map((p) => p.id);\n\tconst platformProjectIds = allProjects\n\t\t.filter((p) => p.visibility === 'platform')\n\t\t.map((p) => p.id);\n\n\tconst [orgMemberByOrgId, memberByProjectId, grantsByProjectId] = await Promise.all([\n\t\torgs.getOrgMembersFor(SYSTEM_CONTEXT, orgIds, ctx.userId),\n\t\tprojectStore.getProjectMembersFor(SYSTEM_CONTEXT, projectIds, ctx.userId),\n\t\tplatformProjectIds.length\n\t\t\t? grantStore.listByProjects(SYSTEM_CONTEXT, platformProjectIds)\n\t\t\t: Promise.resolve(new Map<string, PlatformProjectGrant[]>())\n\t]);\n\n\tconst projects = allProjects.filter((project) =>\n\t\tcanView(\n\t\t\tprojectAccessInputFromRowsWith({ deps }, ctx, project, {\n\t\t\t\tmember: memberByProjectId.get(project.id) ?? null,\n\t\t\t\torgMember: orgMemberByOrgId.get(project.orgId) ?? null,\n\t\t\t\tplatformGrants: grantsByProjectId.get(project.id) ?? []\n\t\t\t})\n\t\t)\n\t);\n\n\treturn {\n\t\tprojects,\n\t\tallById: new Map(allProjects.map((p) => [p.id, p])),\n\t\tmemberByProjectId,\n\t\torgMemberByOrgId,\n\t\tgrantsByProjectId\n\t};\n}\n\n/**\n * Whether the caller may create a definition in at least one project of\n * `orgId`, by the same rule `requireCanCreateDefinition` applies. Reads the\n * org's projects a page at a time and stops at the first that passes.\n */\nexport async function canCreateDefinitionInOrg(\n\tctx: RequestContext,\n\torgId: string,\n\tdeps: VisibilityDeps\n): Promise<boolean> {\n\tconst orgMember =\n\t\t(await deps.orgs.getOrgMembersFor(SYSTEM_CONTEXT, [orgId], ctx.userId)).get(orgId) ?? null;\n\tconst pages = walkPages((page) => deps.projects.listProjects(SYSTEM_CONTEXT, orgId, page));\n\tfor await (const page of pages) {\n\t\tconst platformIds = page.items.filter((p) => p.visibility === 'platform').map((p) => p.id);\n\t\tconst [members, grants] = await Promise.all([\n\t\t\tdeps.projects.getProjectMembersFor(\n\t\t\t\tSYSTEM_CONTEXT,\n\t\t\t\tpage.items.map((p) => p.id),\n\t\t\t\tctx.userId\n\t\t\t),\n\t\t\tplatformIds.length\n\t\t\t\t? deps.platformProjectGrants.listByProjects(SYSTEM_CONTEXT, platformIds)\n\t\t\t\t: Promise.resolve(new Map<string, PlatformProjectGrant[]>())\n\t\t]);\n\t\tconst allowed = page.items.some((project) =>\n\t\t\tcanCreateDefinition(\n\t\t\t\tprojectAccessInputFromRowsWith({ deps }, ctx, project, {\n\t\t\t\t\tmember: members.get(project.id) ?? null,\n\t\t\t\t\torgMember,\n\t\t\t\t\tplatformGrants: grants.get(project.id) ?? []\n\t\t\t\t})\n\t\t\t)\n\t\t);\n\t\tif (allowed) return true;\n\t}\n\treturn false;\n}\n\nexport interface ListVisibleDefinitionsResult extends Page<DefinitionRecord> {\n\t/** For resolving a definition's `projectId` to a name. */\n\tprojects: Project[];\n}\n\n/**\n * `opts.projectId` narrows to one project; a caller who cannot view it gets an\n * empty page rather than a 403, so this never reveals that a project exists.\n */\nexport async function listVisibleDefinitions(\n\tctx: RequestContext,\n\topts: DefinitionListOptions & { projectId?: string } = {},\n\tdeps: VisibilityDeps\n): Promise<ListVisibleDefinitionsResult> {\n\tconst { projectId, ...listOpts } = opts;\n\tconst { projects } = await resolveAccessibleProjects(ctx, deps);\n\n\tconst scoped = projectId ? projects.filter((p) => p.id === projectId) : projects;\n\t// An empty id set matches nothing, which is what a caller with no visible\n\t// projects should get — not an unfiltered listing.\n\tconst page = await deps.definitionMeta.list(ctx, {\n\t\t...listOpts,\n\t\tprojectIds: scoped.map((p) => p.id)\n\t});\n\n\treturn { items: page.items, nextCursor: page.nextCursor, projects: scoped };\n}\n\n/**\n * Editable definitions whose `sourceDocumentId` is `documentId`: the ones the\n * caller could upload a new version of, by {@link mayUploadToDefinition}.\n *\n * Commons projects are scanned too, since a caller owns their own uploads there\n * without edit rights on the project; rows they can't edit are dropped after\n * the query, so a page can come back short while `nextCursor` stays valid.\n */\nexport async function listEditableDefinitionsByDocument(\n\tctx: RequestContext,\n\tdocumentId: string,\n\topts: DefinitionListOptions & { projectId?: string },\n\tdeps: VisibilityDeps\n): Promise<Page<DefinitionRecord>> {\n\tconst { projectId, ...listOpts } = opts;\n\tconst set = await resolveAccessibleProjects(ctx, deps);\n\tconst rowsFor = (project: Project) => ({\n\t\tmember: set.memberByProjectId.get(project.id) ?? null,\n\t\torgMember: set.orgMemberByOrgId.get(project.orgId) ?? null,\n\t\tplatformGrants: set.grantsByProjectId.get(project.id) ?? []\n\t});\n\tconst candidates = set.projects.filter(\n\t\t(p) =>\n\t\t\t(!projectId || p.id === projectId) &&\n\t\t\tcanCreateDefinition(projectAccessInputFromRowsWith({ deps }, ctx, p, rowsFor(p)))\n\t);\n\n\tconst page = await deps.definitionMeta.list(ctx, {\n\t\t...listOpts,\n\t\tsourceDocumentId: documentId,\n\t\tprojectIds: candidates.map((p) => p.id)\n\t});\n\tconst items = page.items.filter((record) => {\n\t\tconst project = set.allById.get(record.projectId);\n\t\treturn project\n\t\t\t? mayUploadToDefinition(ctx, { record, project, ...rowsFor(project) }, deps)\n\t\t\t: false;\n\t});\n\treturn { items, nextCursor: page.nextCursor };\n}\n\n/** A visible definition and the caller's rows that decided it. */\nexport interface VisibleDefinition {\n\trecord: DefinitionRecord;\n\tproject: Project;\n\tmember: ProjectMember | null;\n\torgMember: OrgMember | null;\n}\n\n/**\n * One definition, or `null` when the caller cannot view its project.\n *\n * Returns `null` rather than throwing 403 so callers surface a 404: a public\n * API that answers \"forbidden\" for a guid the caller cannot see turns\n * `/definitions/{guid}` into a cross-tenant existence oracle.\n */\nexport async function getVisibleDefinition(\n\tctx: RequestContext,\n\tguid: string,\n\tdeps: VisibilityDeps\n): Promise<DefinitionRecord | null> {\n\treturn (await loadVisibleDefinition(ctx, guid, deps))?.record ?? null;\n}\n\n/** {@link getVisibleDefinition} with the rows it read, for a second rule over the same caller. */\nexport async function loadVisibleDefinition(\n\tctx: RequestContext,\n\tguid: string,\n\tdeps: VisibilityDeps\n): Promise<VisibleDefinition | null> {\n\tconst meta = deps.definitionMeta;\n\tconst projectStore = deps.projects;\n\n\tconst record = await meta.get(ctx, guid);\n\tif (!record) return null;\n\n\tconst project = await projectStore.getProject(SYSTEM_CONTEXT, record.projectId);\n\tif (!project || outsideTokenOrg(ctx, project.orgId)) return null;\n\n\tconst [orgMembers, projectMembers, grants] = await Promise.all([\n\t\tdeps.orgs.getOrgMembersFor(SYSTEM_CONTEXT, [project.orgId], ctx.userId),\n\t\tprojectStore.getProjectMembersFor(SYSTEM_CONTEXT, [project.id], ctx.userId),\n\t\tproject.visibility === 'platform'\n\t\t\t? deps.platformProjectGrants.listByProject(SYSTEM_CONTEXT, project.id)\n\t\t\t: Promise.resolve([] as PlatformProjectGrant[])\n\t]);\n\n\tconst member = projectMembers.get(project.id) ?? null;\n\tconst orgMember = orgMembers.get(project.orgId) ?? null;\n\tconst allowed = canView(\n\t\tprojectAccessInputFromRowsWith({ deps }, ctx, project, {\n\t\t\tmember,\n\t\t\torgMember,\n\t\t\tplatformGrants: grants\n\t\t})\n\t);\n\treturn allowed ? { record, project, member, orgMember } : null;\n}\n\n/**\n * May the caller upload a version of this definition and make one live? The\n * rule `requireEditableDefinition` applies, and for an API token its `upload`\n * scope on the definition, which is what those routes check.\n */\nexport function mayUploadToDefinition(\n\tctx: RequestContext,\n\t{ record, project, member, orgMember }: VisibleDefinition,\n\tdeps: Pick<VisibilityDeps, 'flag'>\n): boolean {\n\treturn (\n\t\tscopeAllows(ctx, 'upload', { definitionId: record.guid, projectId: project.id }) &&\n\t\tcanEditDefinition({\n\t\t\tproject,\n\t\t\tdefinition: record,\n\t\t\tmember,\n\t\t\torgMember,\n\t\t\tuserId: ctx.userId,\n\t\t\tplatformPermissions: ctx.platformPermissions,\n\t\t\tenablePlatformProjects: deps.flag('ENABLE_PLATFORM_PROJECTS')\n\t\t})\n\t);\n}\n\n/**\n * One version of a definition the caller can view, including its cached\n * `schema`. `null` when the definition is invisible, the version is missing, or\n * the version belongs to a different definition — a caller must not be able to\n * read an arbitrary version by pairing it with a guid they can see.\n */\nexport async function loadVisibleVersion(\n\tctx: RequestContext,\n\tguid: string,\n\tversionId: string,\n\tdeps: VisibilityDeps\n): Promise<DefinitionVersion | null> {\n\tconst record = await getVisibleDefinition(ctx, guid, deps);\n\tif (!record) return null;\n\n\tconst version = await deps.definitionMeta.getVersion(ctx, versionId);\n\tif (!version || version.definitionId !== record.guid) return null;\n\treturn version;\n}\n"],"mappings":";;;AAyBA,SAAgB,mBAAmB,QAAoC;CACtE,MAAM,SAAS,SAAS,SAAS,QAAQ,EAAE,IAAI;CAC/C,OAAO,OAAO,SAAS,MAAM,KAAK,UAAU,IAAI,SAAS;AAC1D;AAEA,SAAgB,mBAAmB,QAAwB;CAC1D,OAAO,OAAO,MAAM;AACrB;;;;;AAQA,gBAAuB,UAAa,WAAoD;CACvF,IAAI;CACJ,GAAG;EACF,MAAM,OAAO,MAAM,UAAU;GAAE,OAAA;GAAuB;EAAO,CAAC;EAC9D,MAAM;EACN,SAAS,KAAK;CACf,SAAS;AACV;;AAGA,eAAsB,QAAW,WAAyC;CACzE,MAAM,QAAa,CAAC;CACpB,WAAW,MAAM,QAAQ,UAAU,SAAS,GAAG,MAAM,KAAK,GAAG,KAAK,KAAK;CACvE,OAAO;AACR;;AAGA,SAAgB,eAAe,OAAmC;CACjE,MAAM,YAAY,SAAA;CAClB,IAAI,CAAC,OAAO,SAAS,SAAS,GAAG,OAAA;CACjC,OAAO,KAAK,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,CAAC,GAAA,GAAiB;AACnE;;;;;;;;;;;;;;;;;;ACrBA,IAAM,aAAa;;;;;;AAsCnB,eAAsB,0BACrB,KACA,MACgC;CAChC,MAAM,OAAO,KAAK;CAClB,MAAM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BAAiB,gBAAgB,CAAC,QAAQ,KAAK,GAAG,IAAI,MAAM;EACtE,aAAa,qBAAqB,gBAAgB,CAAC,QAAQ,EAAE,GAAG,IAAI,MAAM;EAC1E,QAAQ,eAAe,aACpB,KAAK,sBAAsB,cAAc,gBAAgB,QAAQ,EAAE,IACnE,QAAQ,QAAQ,CAAC,CAA2B;CAChD,CAAC;CAED,MAAM,SAAS,eAAe,IAAI,QAAQ,EAAE,KAAK;CACjD,MAAM,YAAY,WAAW,IAAI,QAAQ,KAAK,KAAK;CAQnD,OAPgB,QACf,+BAA+B,EAAE,KAAK,GAAG,KAAK,SAAS;EACtD;EACA;EACA,gBAAgB;CACjB,CAAC,CAEK,IAAU;EAAE;EAAQ;EAAS;EAAQ;CAAU,IAAI;AAC3D;;;;;;AAOA,SAAgB,sBACf,KACA,EAAE,QAAQ,SAAS,QAAQ,aAC3B,MACU;CACV,OACC,YAAY,KAAK,UAAU;EAAE,cAAc,OAAO;EAAM,WAAW,QAAQ;CAAG,CAAC,KAC/E,kBAAkB;EACjB;EACA,YAAY;EACZ;EACA;EACA,QAAQ,IAAI;EACZ,qBAAqB,IAAI;EACzB,wBAAwB,KAAK,KAAK,0BAA0B;CAC7D,CAAC;AAEH;;;;;;;AAQA,eAAsB,mBACrB,KACA,MACA,WACA,MACoC;CACpC,MAAM,SAAS,MAAM,qBAAqB,KAAK,MAAM,IAAI;CACzD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,UAAU,MAAM,KAAK,eAAe,WAAW,KAAK,SAAS;CACnE,IAAI,CAAC,WAAW,QAAQ,iBAAiB,OAAO,MAAM,OAAO;CAC7D,OAAO;AACR"}
@@ -1,8 +1,8 @@
1
1
  import { h as getOrganizationProvider, s as getDefinitionMeta, v as getProjectProvider, x as getStorageProvider } from "../../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, v as requireInstanceAdmin } from "../../../../../../chunks/access.js";
3
- import { s as ProviderError } from "../../../../../../chunks/context.js";
4
- import { u as UpdateOrgSchema } from "../../../../../../chunks/schemas.js";
5
- import { B as requireParams, I as parseBody } from "../../../../../../chunks/api.js";
3
+ import { i as ProviderError } from "../../../../../../chunks/context.js";
4
+ import { H as requireParams, R as parseBody } from "../../../../../../chunks/api.js";
5
+ import { u as UpdateOrgSchema } from "../../../../../../chunks/schemas2.js";
6
6
  import { t as apiError } from "../../../../../../chunks/api-errors.js";
7
7
  import "../../../../../../chunks/access2.server.js";
8
8
  import { r as noContent, t as apiRoute } from "../../../../../../chunks/http2.js";
@@ -1,8 +1,9 @@
1
1
  import { h as getOrganizationProvider } from "../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, v as requireInstanceAdmin } from "../../../../../chunks/access.js";
3
- import { s as ProviderError } from "../../../../../chunks/context.js";
4
- import { r as CreateOrgSchema } from "../../../../../chunks/schemas.js";
5
- import { I as parseBody } from "../../../../../chunks/api.js";
3
+ import { i as ProviderError } from "../../../../../chunks/context.js";
4
+ import { R as parseBody } from "../../../../../chunks/api.js";
5
+ import { r as CreateOrgSchema } from "../../../../../chunks/schemas2.js";
6
+ import { l as clampPageLimit } from "../../../../../chunks/visibility.js";
6
7
  import { t as apiError } from "../../../../../chunks/api-errors.js";
7
8
  import "../../../../../chunks/access2.server.js";
8
9
  import { n as created, t as apiRoute } from "../../../../../chunks/http2.js";
@@ -16,8 +17,8 @@ import { randomUUID } from "node:crypto";
16
17
  */
17
18
  var GET = apiRoute("Failed to list orgs", async ({ locals, url }) => {
18
19
  requireInstanceAdmin(locals);
19
- const rawLimit = Number(url.searchParams.get("limit") ?? 200);
20
- const limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), 200) : 200;
20
+ const raw = url.searchParams.get("limit");
21
+ const limit = clampPageLimit(raw === null ? 200 : Number(raw));
21
22
  const cursor = url.searchParams.get("cursor") ?? void 0;
22
23
  const page = await getOrganizationProvider().listOrgs(locals.ctx, {
23
24
  limit,
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/admin/orgs/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport type { RequestHandler } from './$types';\nimport { randomUUID } from 'node:crypto';\nimport { getOrganizationProvider } from '#lib/server/providers.server.js';\nimport { requireInstanceAdmin } from '#lib/server/access.server.js';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { apiRoute, created, parseBody } from '#lib/server/api/http.js';\nimport {\n\tCreateOrgSchema,\n\tMAX_PAGE_LIMIT,\n\tProviderError,\n\ttype Organization\n} from '@selvajs/platform';\n\n/**\n * Spec §8 — instance-admin-only org management. Multi-tenant deployments use\n * this to create / list orgs out of band of the per-org invite flow. Self-\n * hosted single-tenant instances rarely call these.\n */\n\nexport const GET: RequestHandler = apiRoute('Failed to list orgs', async ({ locals, url }) => {\n\trequireInstanceAdmin(locals);\n\n\tconst rawLimit = Number(url.searchParams.get('limit') ?? 200);\n\tconst limit = Number.isFinite(rawLimit) ? Math.min(Math.max(rawLimit, 1), MAX_PAGE_LIMIT) : 200;\n\tconst cursor = url.searchParams.get('cursor') ?? undefined;\n\n\tconst page = await getOrganizationProvider().listOrgs(locals.ctx!, { limit, cursor });\n\treturn json({ orgs: page.items, nextCursor: page.nextCursor });\n});\n\nexport const POST: RequestHandler = apiRoute(\n\t'Failed to create org',\n\tasync ({ request, locals }) => {\n\t\tconst user = requireInstanceAdmin(locals);\n\n\t\tconst input = await parseBody(request, CreateOrgSchema);\n\n\t\tconst now = new Date().toISOString();\n\t\tconst org: Organization = {\n\t\t\tid: randomUUID(),\n\t\t\tname: input.name,\n\t\t\tslug: input.slug,\n\t\t\townerId: user.id,\n\t\t\tcreatedBy: user.id,\n\t\t\tupdatedBy: user.id,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t};\n\n\t\ttry {\n\t\t\tawait getOrganizationProvider().createOrg(locals.ctx!, org);\n\t\t} catch (err) {\n\t\t\t// Slug collision is the most likely failure mode — surface it cleanly.\n\t\t\tif (err instanceof ProviderError && err.statusCode === 409) {\n\t\t\t\tapiError(409, ApiErrorCode.CONFLICT, err.message);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\n\t\treturn created(org);\n\t}\n);\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,IAAa,MAAsB,SAAS,uBAAuB,OAAO,EAAE,QAAQ,UAAU;CAC7F,qBAAqB,MAAM;CAE3B,MAAM,WAAW,OAAO,IAAI,aAAa,IAAI,OAAO,KAAK,GAAG;CAC5D,MAAM,QAAQ,OAAO,SAAS,QAAQ,IAAI,KAAK,IAAI,KAAK,IAAI,UAAU,CAAC,GAAA,GAAiB,IAAI;CAC5F,MAAM,SAAS,IAAI,aAAa,IAAI,QAAQ,KAAK,KAAA;CAEjD,MAAM,OAAO,MAAM,wBAAwB,CAAC,CAAC,SAAS,OAAO,KAAM;EAAE;EAAO;CAAO,CAAC;CACpF,OAAO,KAAK;EAAE,MAAM,KAAK;EAAO,YAAY,KAAK;CAAW,CAAC;AAC9D,CAAC;AAED,IAAa,OAAuB,SACnC,wBACA,OAAO,EAAE,SAAS,aAAa;CAC9B,MAAM,OAAO,qBAAqB,MAAM;CAExC,MAAM,QAAQ,MAAM,UAAU,SAAS,eAAe;CAEtD,MAAM,uBAAM,IAAI,KAAK,EAAA,CAAE,YAAY;CACnC,MAAM,MAAoB;EACzB,IAAI,WAAW;EACf,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,SAAS,KAAK;EACd,WAAW,KAAK;EAChB,WAAW,KAAK;EAChB,WAAW;EACX,WAAW;EACX,WAAW;CACZ;CAEA,IAAI;EACH,MAAM,wBAAwB,CAAC,CAAC,UAAU,OAAO,KAAM,GAAG;CAC3D,SAAS,KAAK;EAEb,IAAI,eAAe,iBAAiB,IAAI,eAAe,KACtD,SAAS,KAAK,aAAa,UAAU,IAAI,OAAO;EAEjD,MAAM;CACP;CAEA,OAAO,QAAQ,GAAG;AACnB,CACD"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/admin/orgs/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport type { RequestHandler } from './$types';\nimport { randomUUID } from 'node:crypto';\nimport { getOrganizationProvider } from '#lib/server/providers.server.js';\nimport { requireInstanceAdmin } from '#lib/server/access.server.js';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { apiRoute, created, parseBody } from '#lib/server/api/http.js';\nimport {\n\tclampPageLimit,\n\tCreateOrgSchema,\n\tMAX_PAGE_LIMIT,\n\tProviderError,\n\ttype Organization\n} from '@selvajs/platform';\n\n/**\n * Spec §8 — instance-admin-only org management. Multi-tenant deployments use\n * this to create / list orgs out of band of the per-org invite flow. Self-\n * hosted single-tenant instances rarely call these.\n */\n\nexport const GET: RequestHandler = apiRoute('Failed to list orgs', async ({ locals, url }) => {\n\trequireInstanceAdmin(locals);\n\n\t// Unset is deliberately a full page, not `DEFAULT_PAGE_LIMIT`.\n\tconst raw = url.searchParams.get('limit');\n\tconst limit = clampPageLimit(raw === null ? MAX_PAGE_LIMIT : Number(raw));\n\tconst cursor = url.searchParams.get('cursor') ?? undefined;\n\n\tconst page = await getOrganizationProvider().listOrgs(locals.ctx!, { limit, cursor });\n\treturn json({ orgs: page.items, nextCursor: page.nextCursor });\n});\n\nexport const POST: RequestHandler = apiRoute(\n\t'Failed to create org',\n\tasync ({ request, locals }) => {\n\t\tconst user = requireInstanceAdmin(locals);\n\n\t\tconst input = await parseBody(request, CreateOrgSchema);\n\n\t\tconst now = new Date().toISOString();\n\t\tconst org: Organization = {\n\t\t\tid: randomUUID(),\n\t\t\tname: input.name,\n\t\t\tslug: input.slug,\n\t\t\townerId: user.id,\n\t\t\tcreatedBy: user.id,\n\t\t\tupdatedBy: user.id,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t\tdeletedAt: null\n\t\t};\n\n\t\ttry {\n\t\t\tawait getOrganizationProvider().createOrg(locals.ctx!, org);\n\t\t} catch (err) {\n\t\t\t// Slug collision is the most likely failure mode — surface it cleanly.\n\t\t\tif (err instanceof ProviderError && err.statusCode === 409) {\n\t\t\t\tapiError(409, ApiErrorCode.CONFLICT, err.message);\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\n\t\treturn created(org);\n\t}\n);\n"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,IAAa,MAAsB,SAAS,uBAAuB,OAAO,EAAE,QAAQ,UAAU;CAC7F,qBAAqB,MAAM;CAG3B,MAAM,MAAM,IAAI,aAAa,IAAI,OAAO;CACxC,MAAM,QAAQ,eAAe,QAAQ,OAAA,MAAwB,OAAO,GAAG,CAAC;CACxE,MAAM,SAAS,IAAI,aAAa,IAAI,QAAQ,KAAK,KAAA;CAEjD,MAAM,OAAO,MAAM,wBAAwB,CAAC,CAAC,SAAS,OAAO,KAAM;EAAE;EAAO;CAAO,CAAC;CACpF,OAAO,KAAK;EAAE,MAAM,KAAK;EAAO,YAAY,KAAK;CAAW,CAAC;AAC9D,CAAC;AAED,IAAa,OAAuB,SACnC,wBACA,OAAO,EAAE,SAAS,aAAa;CAC9B,MAAM,OAAO,qBAAqB,MAAM;CAExC,MAAM,QAAQ,MAAM,UAAU,SAAS,eAAe;CAEtD,MAAM,uBAAM,IAAI,KAAK,EAAA,CAAE,YAAY;CACnC,MAAM,MAAoB;EACzB,IAAI,WAAW;EACf,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,SAAS,KAAK;EACd,WAAW,KAAK;EAChB,WAAW,KAAK;EAChB,WAAW;EACX,WAAW;EACX,WAAW;CACZ;CAEA,IAAI;EACH,MAAM,wBAAwB,CAAC,CAAC,UAAU,OAAO,KAAM,GAAG;CAC3D,SAAS,KAAK;EAEb,IAAI,eAAe,iBAAiB,IAAI,eAAe,KACtD,SAAS,KAAK,aAAa,UAAU,IAAI,OAAO;EAEjD,MAAM;CACP;CAEA,OAAO,QAAQ,GAAG;AACnB,CACD"}
@@ -1,8 +1,8 @@
1
1
  import { s as getDefinitionMeta, v as getProjectProvider, x as getStorageProvider } from "../../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, v as requireInstanceAdmin } from "../../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../../chunks/context.js";
4
- import { f as slugify } from "../../../../../../chunks/schemas.js";
5
- import { B as requireParams, I as parseBody } from "../../../../../../chunks/api.js";
4
+ import { H as requireParams, R as parseBody } from "../../../../../../chunks/api.js";
5
+ import { f as slugify } from "../../../../../../chunks/schemas2.js";
6
6
  import { t as apiError } from "../../../../../../chunks/api-errors.js";
7
7
  import "../../../../../../chunks/access2.server.js";
8
8
  import { r as noContent, t as apiRoute } from "../../../../../../chunks/http2.js";
@@ -1,7 +1,7 @@
1
1
  import { _ as getPlatformProjectGrantStore, t as flag } from "../../../../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, v as requireInstanceAdmin } from "../../../../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../../../../chunks/context.js";
4
- import { B as requireParams } from "../../../../../../../../chunks/api.js";
4
+ import { H as requireParams } from "../../../../../../../../chunks/api.js";
5
5
  import { t as apiError } from "../../../../../../../../chunks/api-errors.js";
6
6
  import "../../../../../../../../chunks/access2.server.js";
7
7
  import { r as noContent, t as apiRoute } from "../../../../../../../../chunks/http2.js";
@@ -1,7 +1,7 @@
1
1
  import { C as getUserProfileStore, _ as getPlatformProjectGrantStore, h as getOrganizationProvider, t as flag, v as getProjectProvider } from "../../../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, v as requireInstanceAdmin } from "../../../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../../../chunks/context.js";
4
- import { B as requireParams, I as parseBody } from "../../../../../../../chunks/api.js";
4
+ import { H as requireParams, R as parseBody } from "../../../../../../../chunks/api.js";
5
5
  import { t as apiError } from "../../../../../../../chunks/api-errors.js";
6
6
  import "../../../../../../../chunks/access2.server.js";
7
7
  import { n as created, t as apiRoute } from "../../../../../../../chunks/http2.js";
@@ -1,7 +1,7 @@
1
1
  import { h as getOrganizationProvider, t as flag, v as getProjectProvider } from "../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, v as requireInstanceAdmin } from "../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../chunks/context.js";
4
- import { I as parseBody } from "../../../../../chunks/api.js";
4
+ import { R as parseBody } from "../../../../../chunks/api.js";
5
5
  import { t as apiError } from "../../../../../chunks/api-errors.js";
6
6
  import "../../../../../chunks/access2.server.js";
7
7
  import { n as created, t as apiRoute } from "../../../../../chunks/http2.js";
@@ -1,4 +1,4 @@
1
- import { T as providers, a as getComputeServerConfigStore, j as LocalComputeServerStore } from "../../../../../../chunks/providers.server.js";
1
+ import { L as LocalComputeServerStore, T as providers, a as getComputeServerConfigStore } from "../../../../../../chunks/providers.server.js";
2
2
  import { n as env } from "../../../../../../chunks/previous-key.js";
3
3
  import { C as requirePermission } from "../../../../../../chunks/access.js";
4
4
  import { n as findServerById } from "../../../../../../chunks/utils.js";
@@ -1,4 +1,4 @@
1
- import { L as actorFrom, l as getErrorReporter, u as getEventSink } from "../../../../../../chunks/providers.server.js";
1
+ import { U as actorFrom, l as getErrorReporter, u as getEventSink } from "../../../../../../chunks/providers.server.js";
2
2
  import { n as env } from "../../../../../../chunks/previous-key.js";
3
3
  import { C as requirePermission } from "../../../../../../chunks/access.js";
4
4
  import { n as renderThrown } from "../../../../../../chunks/definitions.js";
@@ -1,8 +1,8 @@
1
- import { L as actorFrom, g as getPermissionStore, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../../chunks/providers.server.js";
1
+ import { U as actorFrom, g as getPermissionStore, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode, r as assertCanGrantPlatformPermissions } from "../../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../../chunks/context.js";
4
+ import { H as requireParams, R as parseBody } from "../../../../../../chunks/api.js";
4
5
  import { r as PlatformPermissionSchema } from "../../../../../../chunks/types3.js";
5
- import { B as requireParams, I as parseBody } from "../../../../../../chunks/api.js";
6
6
  import { t as apiError } from "../../../../../../chunks/api-errors.js";
7
7
  import "../../../../../../chunks/access2.server.js";
8
8
  import { r as noContent, t as apiRoute } from "../../../../../../chunks/http2.js";