gemi 0.124.0 → 0.125.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/dist/ai/AgentController.d.ts +185 -3
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/client/index.d.ts +1 -1
  4. package/dist/ai/client/index.d.ts.map +1 -1
  5. package/dist/ai/client/index.js +38 -9
  6. package/dist/ai/client/index.js.map +1 -1
  7. package/dist/ai/client/reducer.d.ts.map +1 -1
  8. package/dist/ai/index.d.ts +2 -2
  9. package/dist/ai/index.d.ts.map +1 -1
  10. package/dist/ai/index.js +31 -48
  11. package/dist/ai/index.js.map +6 -15
  12. package/dist/ai/types.d.ts +26 -0
  13. package/dist/ai/types.d.ts.map +1 -1
  14. package/dist/ai/useChat.d.ts +35 -2
  15. package/dist/ai/useChat.d.ts.map +1 -1
  16. package/dist/app/index.js +1 -1
  17. package/dist/auth/AuthController.d.ts.map +1 -1
  18. package/dist/auth/AuthManager.d.ts +11 -0
  19. package/dist/auth/AuthManager.d.ts.map +1 -1
  20. package/dist/auth/AuthServiceProvider.d.ts +2 -0
  21. package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
  22. package/dist/auth/config.d.ts +71 -2
  23. package/dist/auth/config.d.ts.map +1 -1
  24. package/dist/auth/oauth/providers.d.ts +10 -0
  25. package/dist/auth/oauth/providers.d.ts.map +1 -0
  26. package/dist/bun/plugin.js +1 -1
  27. package/dist/bun/preload.js +1 -1
  28. package/dist/{chunk-a3g7y70h.js → chunk-0x1s02r1.js} +3 -3
  29. package/dist/{chunk-a3g7y70h.js.map → chunk-0x1s02r1.js.map} +1 -1
  30. package/dist/{chunk-yzhv93b0.js → chunk-1jcngq6w.js} +3 -3
  31. package/dist/{chunk-yzhv93b0.js.map → chunk-1jcngq6w.js.map} +1 -1
  32. package/dist/{chunk-mrswc6qw.js → chunk-1mxb44n9.js} +2 -2
  33. package/dist/{chunk-mrswc6qw.js.map → chunk-1mxb44n9.js.map} +1 -1
  34. package/dist/{chunk-9tr92nwy.js → chunk-1n40bdxf.js} +2 -2
  35. package/dist/{chunk-9tr92nwy.js.map → chunk-1n40bdxf.js.map} +1 -1
  36. package/dist/chunk-1xmh61fg.js +5 -0
  37. package/dist/{chunk-70nnh0y7.js.map → chunk-1xmh61fg.js.map} +1 -1
  38. package/dist/{chunk-bt9qv2jj.js → chunk-3br5zr7a.js} +3 -3
  39. package/dist/{chunk-bt9qv2jj.js.map → chunk-3br5zr7a.js.map} +1 -1
  40. package/dist/{chunk-w61sphn5.js → chunk-3kxe9geg.js} +3 -3
  41. package/dist/{chunk-w61sphn5.js.map → chunk-3kxe9geg.js.map} +1 -1
  42. package/dist/{chunk-bnt8kx6x.js → chunk-5fh4pvyt.js} +2 -2
  43. package/dist/{chunk-bnt8kx6x.js.map → chunk-5fh4pvyt.js.map} +1 -1
  44. package/dist/{chunk-rpyczdta.js → chunk-6gwxvmjv.js} +3 -3
  45. package/dist/{chunk-rpyczdta.js.map → chunk-6gwxvmjv.js.map} +1 -1
  46. package/dist/{chunk-65s834td.js → chunk-6q6bhkyf.js} +1 -1
  47. package/dist/{chunk-fn2qfwgx.js → chunk-6vz75swk.js} +2 -2
  48. package/dist/{chunk-fn2qfwgx.js.map → chunk-6vz75swk.js.map} +1 -1
  49. package/dist/chunk-6wgh7nk6.js +15 -0
  50. package/dist/{chunk-n0r5xyk2.js.map → chunk-6wgh7nk6.js.map} +6 -5
  51. package/dist/chunk-7vrrgxwm.js +22 -0
  52. package/dist/chunk-7vrrgxwm.js.map +21 -0
  53. package/dist/{chunk-kzsjyvvc.js → chunk-7zj6bk9a.js} +2 -2
  54. package/dist/{chunk-kzsjyvvc.js.map → chunk-7zj6bk9a.js.map} +1 -1
  55. package/dist/{chunk-3hqwz48c.js → chunk-8tvfmy1a.js} +4 -4
  56. package/dist/{chunk-3hqwz48c.js.map → chunk-8tvfmy1a.js.map} +1 -1
  57. package/dist/{chunk-6bgb1nhq.js → chunk-910p6ne6.js} +2 -2
  58. package/dist/{chunk-6bgb1nhq.js.map → chunk-910p6ne6.js.map} +1 -1
  59. package/dist/{chunk-96a1459v.js → chunk-ap3g6rbw.js} +2 -2
  60. package/dist/{chunk-96a1459v.js.map → chunk-ap3g6rbw.js.map} +1 -1
  61. package/dist/{chunk-3j6s5bmx.js → chunk-ayfjjgv2.js} +1 -1
  62. package/dist/chunk-b4x1dt3s.js +10 -0
  63. package/dist/chunk-b4x1dt3s.js.map +43 -0
  64. package/dist/{chunk-f29pktad.js → chunk-b7a22evs.js} +3 -3
  65. package/dist/{chunk-f29pktad.js.map → chunk-b7a22evs.js.map} +1 -1
  66. package/dist/{chunk-qdj8ek8z.js → chunk-bny9s44t.js} +2 -2
  67. package/dist/{chunk-qdj8ek8z.js.map → chunk-bny9s44t.js.map} +1 -1
  68. package/dist/{chunk-1rnh9qrp.js → chunk-by5gwr8x.js} +2 -2
  69. package/dist/{chunk-1rnh9qrp.js.map → chunk-by5gwr8x.js.map} +1 -1
  70. package/dist/{chunk-nn2jeat2.js → chunk-c0qpv8x7.js} +2 -2
  71. package/dist/{chunk-17dndh5z.js.map → chunk-c0qpv8x7.js.map} +1 -1
  72. package/dist/{chunk-f4cmz31h.js → chunk-cpem1j1x.js} +2 -2
  73. package/dist/{chunk-f4cmz31h.js.map → chunk-cpem1j1x.js.map} +1 -1
  74. package/dist/{chunk-019wz697.js → chunk-crnfxn9n.js} +2 -2
  75. package/dist/{chunk-019wz697.js.map → chunk-crnfxn9n.js.map} +1 -1
  76. package/dist/{chunk-s5jxc63j.js → chunk-cwt8e782.js} +3 -3
  77. package/dist/{chunk-s5jxc63j.js.map → chunk-cwt8e782.js.map} +1 -1
  78. package/dist/{chunk-fw7ds23a.js → chunk-dxyxd7b3.js} +2 -2
  79. package/dist/{chunk-fw7ds23a.js.map → chunk-dxyxd7b3.js.map} +1 -1
  80. package/dist/{chunk-qhz0x97z.js → chunk-dy58aztm.js} +2 -2
  81. package/dist/{chunk-qhz0x97z.js.map → chunk-dy58aztm.js.map} +1 -1
  82. package/dist/{chunk-skf89vrv.js → chunk-entpqjyn.js} +2 -2
  83. package/dist/{chunk-skf89vrv.js.map → chunk-entpqjyn.js.map} +1 -1
  84. package/dist/{chunk-7gfdts60.js → chunk-eq5svwca.js} +2 -2
  85. package/dist/{chunk-7gfdts60.js.map → chunk-eq5svwca.js.map} +1 -1
  86. package/dist/{chunk-n1a2zj5z.js → chunk-erzfs4t2.js} +2 -2
  87. package/dist/{chunk-n1a2zj5z.js.map → chunk-erzfs4t2.js.map} +3 -3
  88. package/dist/{chunk-3y294mb8.js → chunk-ex41d03h.js} +2 -2
  89. package/dist/{chunk-3y294mb8.js.map → chunk-ex41d03h.js.map} +1 -1
  90. package/dist/{chunk-v2ggafz1.js → chunk-ey1xrbaz.js} +2 -2
  91. package/dist/{chunk-v2ggafz1.js.map → chunk-ey1xrbaz.js.map} +1 -1
  92. package/dist/chunk-eyptwf54.js +57 -0
  93. package/dist/{chunk-5j50q4g8.js.map → chunk-eyptwf54.js.map} +22 -19
  94. package/dist/{chunk-zsfwcdqn.js → chunk-g52fcwca.js} +2 -2
  95. package/dist/{chunk-zsfwcdqn.js.map → chunk-g52fcwca.js.map} +1 -1
  96. package/dist/{chunk-rttrpjqk.js → chunk-ghcvztxn.js} +2 -2
  97. package/dist/{chunk-rttrpjqk.js.map → chunk-ghcvztxn.js.map} +1 -1
  98. package/dist/{chunk-wbg2tza5.js → chunk-gp00enrk.js} +1 -1
  99. package/dist/{chunk-92sk56n0.js → chunk-h8w9mzjj.js} +6 -6
  100. package/dist/{chunk-92sk56n0.js.map → chunk-h8w9mzjj.js.map} +7 -7
  101. package/dist/{chunk-cfdwsvtx.js → chunk-hff9w6rt.js} +2 -2
  102. package/dist/{chunk-cfdwsvtx.js.map → chunk-hff9w6rt.js.map} +1 -1
  103. package/dist/{chunk-17dndh5z.js → chunk-hxn0s3zh.js} +2 -2
  104. package/dist/{chunk-nn2jeat2.js.map → chunk-hxn0s3zh.js.map} +1 -1
  105. package/dist/{chunk-8m2htvjn.js → chunk-hzen9gh4.js} +2 -2
  106. package/dist/{chunk-8m2htvjn.js.map → chunk-hzen9gh4.js.map} +1 -1
  107. package/dist/{chunk-c4jnxmf2.js → chunk-j10a0m7q.js} +1 -1
  108. package/dist/{chunk-5e22tm7m.js → chunk-j12hpdxk.js} +1 -1
  109. package/dist/{chunk-ykz38t0t.js → chunk-j5rwv09s.js} +2 -2
  110. package/dist/{chunk-ykz38t0t.js.map → chunk-j5rwv09s.js.map} +1 -1
  111. package/dist/{chunk-w4z6x54b.js → chunk-jykkqwcy.js} +3 -3
  112. package/dist/{chunk-w4z6x54b.js.map → chunk-jykkqwcy.js.map} +1 -1
  113. package/dist/{chunk-w3812s34.js → chunk-k1ebt28j.js} +2 -2
  114. package/dist/{chunk-w3812s34.js.map → chunk-k1ebt28j.js.map} +1 -1
  115. package/dist/{chunk-h3p8qzft.js → chunk-kcsa57km.js} +2 -2
  116. package/dist/{chunk-h3p8qzft.js.map → chunk-kcsa57km.js.map} +1 -1
  117. package/dist/{chunk-1qwhty9p.js → chunk-khdkrfxp.js} +2 -2
  118. package/dist/{chunk-1qwhty9p.js.map → chunk-khdkrfxp.js.map} +1 -1
  119. package/dist/{chunk-b5afy6k9.js → chunk-knq4ack4.js} +2 -2
  120. package/dist/{chunk-b5afy6k9.js.map → chunk-knq4ack4.js.map} +1 -1
  121. package/dist/{chunk-121p4g9j.js → chunk-m7pghdcy.js} +2 -2
  122. package/dist/{chunk-121p4g9j.js.map → chunk-m7pghdcy.js.map} +1 -1
  123. package/dist/{chunk-rtawbqec.js → chunk-mmqnq1qh.js} +3 -3
  124. package/dist/{chunk-rtawbqec.js.map → chunk-mmqnq1qh.js.map} +1 -1
  125. package/dist/{chunk-34fkx6kb.js → chunk-n3z83qhq.js} +2 -2
  126. package/dist/{chunk-34fkx6kb.js.map → chunk-n3z83qhq.js.map} +1 -1
  127. package/dist/{chunk-mvkz22p4.js → chunk-npbf06c1.js} +2 -2
  128. package/dist/{chunk-mvkz22p4.js.map → chunk-npbf06c1.js.map} +1 -1
  129. package/dist/{chunk-2affxmkn.js → chunk-p5df4pn7.js} +2 -2
  130. package/dist/{chunk-2affxmkn.js.map → chunk-p5df4pn7.js.map} +1 -1
  131. package/dist/{chunk-y434jc1c.js → chunk-p6jbmcrg.js} +2 -2
  132. package/dist/{chunk-y434jc1c.js.map → chunk-p6jbmcrg.js.map} +1 -1
  133. package/dist/{chunk-jctb7v53.js → chunk-p7mvp5nf.js} +2 -2
  134. package/dist/{chunk-jctb7v53.js.map → chunk-p7mvp5nf.js.map} +1 -1
  135. package/dist/{chunk-jys8y39p.js → chunk-q6ah4yjg.js} +2 -2
  136. package/dist/{chunk-jys8y39p.js.map → chunk-q6ah4yjg.js.map} +1 -1
  137. package/dist/{chunk-pmyh33v5.js → chunk-r923001x.js} +2 -2
  138. package/dist/{chunk-pmyh33v5.js.map → chunk-r923001x.js.map} +1 -1
  139. package/dist/{chunk-mqtfaqx5.js → chunk-rany5zgk.js} +2 -2
  140. package/dist/{chunk-mqtfaqx5.js.map → chunk-rany5zgk.js.map} +1 -1
  141. package/dist/{chunk-30xxc6r7.js → chunk-rmgkc3a2.js} +2 -2
  142. package/dist/{chunk-30xxc6r7.js.map → chunk-rmgkc3a2.js.map} +1 -1
  143. package/dist/{chunk-v8v5qfnh.js → chunk-rvspb96n.js} +3 -3
  144. package/dist/{chunk-v8v5qfnh.js.map → chunk-rvspb96n.js.map} +1 -1
  145. package/dist/{chunk-zsvav1dk.js → chunk-rwmja4zs.js} +2 -2
  146. package/dist/{chunk-zsvav1dk.js.map → chunk-rwmja4zs.js.map} +1 -1
  147. package/dist/{chunk-j7v7dft7.js → chunk-s4semb89.js} +1 -1
  148. package/dist/{chunk-szn2n976.js → chunk-s4xg69r9.js} +2 -2
  149. package/dist/{chunk-szn2n976.js.map → chunk-s4xg69r9.js.map} +1 -1
  150. package/dist/{chunk-4drnyymm.js → chunk-stn0a56e.js} +2 -2
  151. package/dist/{chunk-4drnyymm.js.map → chunk-stn0a56e.js.map} +1 -1
  152. package/dist/{chunk-pe46a5a5.js → chunk-sv125fqq.js} +2 -2
  153. package/dist/{chunk-pe46a5a5.js.map → chunk-sv125fqq.js.map} +1 -1
  154. package/dist/{chunk-dxfhhw5h.js → chunk-t2t63wa0.js} +2 -2
  155. package/dist/{chunk-dxfhhw5h.js.map → chunk-t2t63wa0.js.map} +1 -1
  156. package/dist/{chunk-675kzd7z.js → chunk-t6qpm2j7.js} +2 -2
  157. package/dist/{chunk-675kzd7z.js.map → chunk-t6qpm2j7.js.map} +1 -1
  158. package/dist/chunk-tabsxzg9.js +5 -0
  159. package/dist/chunk-tabsxzg9.js.map +13 -0
  160. package/dist/{chunk-qycwjzsv.js → chunk-vhvvjaj3.js} +3 -3
  161. package/dist/{chunk-qycwjzsv.js.map → chunk-vhvvjaj3.js.map} +1 -1
  162. package/dist/{chunk-sd0c2001.js → chunk-x2j84d06.js} +2 -2
  163. package/dist/{chunk-sd0c2001.js.map → chunk-x2j84d06.js.map} +1 -1
  164. package/dist/{chunk-75ewjc4a.js → chunk-xe2pm36q.js} +2 -2
  165. package/dist/{chunk-75ewjc4a.js.map → chunk-xe2pm36q.js.map} +1 -1
  166. package/dist/{chunk-z5jydj5r.js → chunk-xfvegbxn.js} +2 -2
  167. package/dist/{chunk-z5jydj5r.js.map → chunk-xfvegbxn.js.map} +1 -1
  168. package/dist/{chunk-2n4490pk.js → chunk-y9f2see3.js} +3 -3
  169. package/dist/{chunk-2n4490pk.js.map → chunk-y9f2see3.js.map} +1 -1
  170. package/dist/{chunk-nkzmk7v3.js → chunk-yhht1j7f.js} +2 -2
  171. package/dist/{chunk-nkzmk7v3.js.map → chunk-yhht1j7f.js.map} +1 -1
  172. package/dist/{chunk-nnarmbjv.js → chunk-z5nfve1k.js} +2 -2
  173. package/dist/chunk-z5nfve1k.js.map +10 -0
  174. package/dist/{chunk-fvrmptd0.js → chunk-zq5375wd.js} +3 -3
  175. package/dist/{chunk-fvrmptd0.js.map → chunk-zq5375wd.js.map} +1 -1
  176. package/dist/chunks/{ThemeProvider-CbOx8IRl.js → ThemeProvider-CS2a1snV.js} +27 -1
  177. package/dist/chunks/ThemeProvider-CS2a1snV.js.map +1 -0
  178. package/dist/client/Mutation.d.ts +7 -6
  179. package/dist/client/Mutation.d.ts.map +1 -1
  180. package/dist/client/MutationError.d.ts +53 -1
  181. package/dist/client/MutationError.d.ts.map +1 -1
  182. package/dist/client/QueryResource.d.ts +9 -0
  183. package/dist/client/QueryResource.d.ts.map +1 -1
  184. package/dist/client/auth/useEmailCode.d.ts +3 -3
  185. package/dist/client/auth/useForgotPassword.d.ts +1 -1
  186. package/dist/client/auth/useResetPassword.d.ts +1 -1
  187. package/dist/client/auth/useSignIn.d.ts +1 -1
  188. package/dist/client/auth/useSignOut.d.ts +1 -1
  189. package/dist/client/auth/useSignUp.d.ts +1 -1
  190. package/dist/client/index.d.ts +4 -2
  191. package/dist/client/index.d.ts.map +1 -1
  192. package/dist/client/index.js +136 -9
  193. package/dist/client/index.js.map +1 -1
  194. package/dist/client/useMutation.d.ts +18 -8
  195. package/dist/client/useMutation.d.ts.map +1 -1
  196. package/dist/client/useSetQueryData.d.ts +69 -0
  197. package/dist/client/useSetQueryData.d.ts.map +1 -0
  198. package/dist/config/index.js +1 -1
  199. package/dist/console/run.js +2 -2
  200. package/dist/console/run.js.map +1 -1
  201. package/dist/container/index.js +2 -2
  202. package/dist/container/index.js.map +1 -1
  203. package/dist/database/index.js +2 -2
  204. package/dist/database/index.js.map +1 -1
  205. package/dist/email/index.js +2 -2
  206. package/dist/email/index.js.map +1 -1
  207. package/dist/facades/Auth.d.ts +29 -2
  208. package/dist/facades/Auth.d.ts.map +1 -1
  209. package/dist/facades/RateLimiter.d.ts +16 -1
  210. package/dist/facades/RateLimiter.d.ts.map +1 -1
  211. package/dist/facades/index.js +2 -2
  212. package/dist/facades/index.js.map +1 -1
  213. package/dist/foundation/index.js +2 -2
  214. package/dist/foundation/index.js.map +1 -1
  215. package/dist/http/HttpRequest.d.ts +14 -0
  216. package/dist/http/HttpRequest.d.ts.map +1 -1
  217. package/dist/http/McpRouter.d.ts +121 -2
  218. package/dist/http/McpRouter.d.ts.map +1 -1
  219. package/dist/http/RateLimitExceededError.d.ts +24 -0
  220. package/dist/http/RateLimitExceededError.d.ts.map +1 -0
  221. package/dist/http/RateLimitMiddleware.d.ts +2 -5
  222. package/dist/http/RateLimitMiddleware.d.ts.map +1 -1
  223. package/dist/http/index.d.ts +2 -1
  224. package/dist/http/index.d.ts.map +1 -1
  225. package/dist/http/index.js +2 -2
  226. package/dist/http/index.js.map +1 -1
  227. package/dist/http/refusal.d.ts +6 -1
  228. package/dist/http/refusal.d.ts.map +1 -1
  229. package/dist/http/requestContext.d.ts +3 -1
  230. package/dist/http/requestContext.d.ts.map +1 -1
  231. package/dist/http/requestState.d.ts +57 -0
  232. package/dist/http/requestState.d.ts.map +1 -0
  233. package/dist/i18n/dictionaryRuntime.js +2 -2
  234. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  235. package/dist/i18n/index.js +2 -2
  236. package/dist/i18n/index.js.map +1 -1
  237. package/dist/kernel/index.js +2 -2
  238. package/dist/kernel/index.js.map +1 -1
  239. package/dist/orm/index.js +2 -2
  240. package/dist/orm/index.js.map +1 -1
  241. package/dist/server/Server.d.ts.map +1 -1
  242. package/dist/server/health.d.ts +67 -0
  243. package/dist/server/health.d.ts.map +1 -0
  244. package/dist/server/index.d.ts +1 -0
  245. package/dist/server/index.d.ts.map +1 -1
  246. package/dist/server/index.js +2 -2
  247. package/dist/server/index.js.map +5 -4
  248. package/dist/server/shutdown.d.ts +3 -4
  249. package/dist/server/shutdown.d.ts.map +1 -1
  250. package/dist/services/features/gate.d.ts +11 -0
  251. package/dist/services/features/gate.d.ts.map +1 -0
  252. package/dist/services/index.d.ts +4 -4
  253. package/dist/services/index.d.ts.map +1 -1
  254. package/dist/services/index.js +3 -3
  255. package/dist/services/index.js.map +2 -2
  256. package/dist/services/logging/LogManager.d.ts +1 -0
  257. package/dist/services/logging/LogManager.d.ts.map +1 -1
  258. package/dist/services/logging/config.d.ts +23 -1
  259. package/dist/services/logging/config.d.ts.map +1 -1
  260. package/dist/services/logging/consoleSink.d.ts +25 -0
  261. package/dist/services/logging/consoleSink.d.ts.map +1 -0
  262. package/dist/services/mcp/McpRegistry.d.ts +106 -14
  263. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  264. package/dist/services/mcp/http/McpHttpServer.d.ts +41 -2
  265. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
  266. package/dist/services/mcp/toAgentTools.d.ts +21 -3
  267. package/dist/services/mcp/toAgentTools.d.ts.map +1 -1
  268. package/dist/services/queue/work.js +2 -2
  269. package/dist/services/queue/work.js.map +1 -1
  270. package/dist/services/rate-limiter/RateLimiter.d.ts +12 -0
  271. package/dist/services/rate-limiter/RateLimiter.d.ts.map +1 -1
  272. package/dist/services/router/globalMiddleware.d.ts +4 -3
  273. package/dist/services/router/globalMiddleware.d.ts.map +1 -1
  274. package/dist/stats/route-table.js +1 -1
  275. package/dist/support/index.js +2 -2
  276. package/dist/support/index.js.map +1 -1
  277. package/dist/testing/index.js +1 -1
  278. package/dist/vitest/index.js +1 -1
  279. package/package.json +1 -1
  280. package/skills/gemi-react-best-practices/SKILL.md +1 -1
  281. package/skills/gemi-react-best-practices/rules/query-mutate-over-refetch.md +14 -0
  282. package/skills/gemi-react-best-practices/rules/routing-middleware-dsl.md +2 -1
  283. package/dist/chunk-5j50q4g8.js +0 -57
  284. package/dist/chunk-70nnh0y7.js +0 -5
  285. package/dist/chunk-kc924zjz.js +0 -5
  286. package/dist/chunk-kc924zjz.js.map +0 -12
  287. package/dist/chunk-n0r5xyk2.js +0 -14
  288. package/dist/chunk-nnarmbjv.js.map +0 -10
  289. package/dist/chunk-pya4rqm2.js +0 -5
  290. package/dist/chunk-pya4rqm2.js.map +0 -12
  291. package/dist/chunk-zmf3vhex.js +0 -10
  292. package/dist/chunk-zmf3vhex.js.map +0 -43
  293. package/dist/chunks/ThemeProvider-CbOx8IRl.js.map +0 -1
  294. /package/dist/{chunk-65s834td.js.map → chunk-6q6bhkyf.js.map} +0 -0
  295. /package/dist/{chunk-3j6s5bmx.js.map → chunk-ayfjjgv2.js.map} +0 -0
  296. /package/dist/{chunk-wbg2tza5.js.map → chunk-gp00enrk.js.map} +0 -0
  297. /package/dist/{chunk-c4jnxmf2.js.map → chunk-j10a0m7q.js.map} +0 -0
  298. /package/dist/{chunk-5e22tm7m.js.map → chunk-j12hpdxk.js.map} +0 -0
  299. /package/dist/{chunk-j7v7dft7.js.map → chunk-s4semb89.js.map} +0 -0
@@ -5,6 +5,6 @@
5
5
  "import type { SQL, TransactionSQL } from \"bun\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { SLOW_TRANSACTION_THRESHOLD } from \"../database/config\";\nimport {\n CrossConnectionTransactionError,\n DEFAULT_CONNECTION,\n} from \"../database/Connection\";\n\n/**\n * The ambient transaction: the ORM's own `AsyncLocalStorage`, holding nothing\n * but the open handle and how deep the nesting is.\n *\n * One store per scope with one owner, which is the pattern the framework\n * already follows — `kernel/context.ts` holds the Application,\n * `http/requestContext.ts` the request and its user. The reasoning for\n * not folding this into the kernel's is written up beside it, and the short\n * version is that a transaction scope has to *nest inside* an Application scope\n * without replacing it, and `foundation/app.ts` must keep reading exactly one\n * shape out of the kernel store or resolving a service becomes a transaction\n * concern.\n *\n * What makes an ALS the right home rather than a field somewhere: two concurrent\n * requests each in their own transaction must never see each other's handle.\n * Anything reachable from the Application — which is one object shared by every\n * in-flight request — fails that by construction, and fails it as silently\n * written data, not as an error. \"two concurrent transactions never see each\n * other's handle\" in `context.test.ts` is the test that would catch it.\n */\nexport interface OrmScope {\n /**\n * Bun's transaction handle. Every ORM statement in scope runs on it, which\n * means they all run on one reserved connection — so nothing here may issue\n * two statements concurrently. `Model.$exec` already runs its nested writes\n * and its relation reads sequentially, for exactly this reason.\n */\n tx?: TransactionSQL;\n /** 0 for the outermost transaction, 1+ for each savepoint inside it. */\n depth: number;\n /**\n * Which named connection this subtree's queries run on, and — when `tx` is\n * set — which connection the open transaction belongs to.\n *\n * Ambient rather than an argument threaded through `$exec`, for the same\n * reason the handle above is: a relation read resolves its target through the\n * registry and calls that class's `$exec`, so an argument would have to be\n * carried by every intermediate that has no interest in it, and the one that\n * forgot would silently read a nested `include` off the *other* pool. There\n * is no error that shape produces; there are just rows from the wrong place.\n *\n * `undefined` means the default connection. Kept as absent-rather-than-\n * `\"default\"` so that entering a scope on the default connection is\n * indistinguishable from not entering one, which is what makes the\n * cross-connection check below cost a comparison of two `undefined`s on every\n * application that never declares a second connection.\n */\n connection?: string;\n /**\n * Whether policies are suspended for this scope. Set only by\n * `Model.asSystem`, and never by anything ambient — the whole point is that\n * unscoped access is a decision visible at the call site, not the accidental\n * result of a missing user.\n */\n system?: boolean;\n /**\n * The user policies should scope to, when there is no request to read one\n * from. Set only by `Model.asUser`.\n *\n * A sentinel wrapper rather than the bare value, so that \"a scope was entered\n * with `null`\" stays distinguishable from \"no scope was entered\" — the two\n * mean different things under deny-by-default.\n */\n actor?: { user: unknown };\n /**\n * Work that must not happen unless this transaction commits — an event whose\n * `static afterCommit` is set, today, and nothing else.\n *\n * **Created by the outermost `withTransaction` and never by a savepoint.** A\n * savepoint's scope is a spread of its parent's (`{ ...current, tx: nested }`),\n * so the array arrives here already shared by reference with the transaction\n * that opened it — which is the behaviour wanted rather than a leak. A\n * dispatch made inside a savepoint that commits, in a transaction that then\n * rolls back, must not run: rolling back the outermost transaction discards\n * the list whole, savepoint entries included, because nothing ever drains it.\n *\n * The inverse — a savepoint that rolls back under a transaction that commits\n * — is the case sharing gets wrong on its own, and `withTransaction`'s\n * savepoint branch is where it is put right.\n *\n * Absent, rather than an empty array, on every scope that is not a\n * transaction: `runAsSystem`, `runAsUser` and `runOnConnection` spread\n * whatever they are given, so \"there is a list here\" and \"there is an open\n * transaction here\" have to stay the same question. `deferUntilCommit`\n * answers `false` when either half is missing and the caller runs the work\n * now, which is what keeps a hand-built scope carrying a `tx` — the shape\n * tests write — from swallowing a dispatch into a list nothing drains.\n */\n afterCommit?: AfterCommitCallback[];\n /**\n * Statements written on `tx` that the commit must wait for and must not\n * outlive — today, a job row the database queue driver wrote on the\n * transaction (#563), and nothing else. See `commitDependsOn`.\n *\n * Created and shared exactly as `afterCommit` is, and truncated with it\n * when a savepoint rolls back.\n */\n commitDependsOn?: Promise<unknown>[];\n /**\n * Models whose soft-delete scope (`static $softDeletes`) is lifted or\n * inverted for this async subtree, by name — set only by\n * `Model.withTrashed(fn)` / `Model.onlyTrashed(fn)`.\n *\n * Keyed by model name rather than class because a nested relation read\n * resolves its target through the registry by name, and the block has to\n * reach those reads too. A fresh map per block, never mutated, so an inner\n * block cannot leak its entry back into the enclosing one.\n */\n trashed?: ReadonlyMap<string, TrashedMode>;\n}\n\n/**\n * How a soft-deleted model's trashed rows are treated: `\"with\"` includes them,\n * `\"only\"` reads nothing else. Absent means the default — they are hidden.\n */\nexport type TrashedMode = \"with\" | \"only\";\n\n/**\n * Work deferred to a transaction's commit.\n *\n * Awaited when it is drained, and its rejection is caught there: a callback is\n * a side effect that the transaction is not waiting on and cannot be told\n * about, so the only thing left to do with a failure is report it.\n *\n * Not exported: a caller passes a lambda and never names this, and an export\n * nothing outside this file uses is what `orm/architecture.test.ts` is pointed\n * at. The declaration emit carries it along regardless, so `OrmScope` stays\n * readable from a `.d.ts`.\n */\ntype AfterCommitCallback = () => void | Promise<void>;\n\n/**\n * One ambient scope for the ORM, not one per feature.\n *\n * Transactions (iteration 5) and system access (iteration 6) are both\n * \"something is true for this async subtree and every query in it\", so they\n * share a store rather than minting a second `AsyncLocalStorage` each. The\n * inventory note in `kernel/context.ts` sets the bar for adding one; two\n * booleans-worth of ORM state does not clear it.\n */\nexport const ormContext = new AsyncLocalStorage<OrmScope>();\n\n/**\n * The open transaction, or `undefined` outside one. This is what `Model.$exec`\n * consults to decide which connection a statement runs on.\n *\n * Exported as the escape hatch for code that genuinely needs the handle — a raw\n * query that must join the surrounding transaction, say. **Do not store what it\n * returns.** Bun's handle stays callable after its `begin` resolves: queries on\n * it then run on the pooled connection, outside any transaction, and succeed.\n * Verified against both dialects, and it is the reason `Model.transaction`'s\n * callback takes no argument.\n */\nexport function currentTransaction(): TransactionSQL | undefined {\n return ormContext.getStore()?.tx;\n}\n\n/**\n * The connection every query in this scope runs on unless it names another.\n *\n * `\"default\"` outside any scope, so callers get a name rather than a\n * `string | undefined` to normalise themselves — the store keeps it absent,\n * which is not the same distinction and is nobody else's business.\n */\nexport function currentConnectionName(): string {\n return ormContext.getStore()?.connection ?? DEFAULT_CONNECTION;\n}\n\n/**\n * Run `fn` with `name` as the ambient connection.\n *\n * Merged into the current scope rather than replacing it, exactly as\n * `runAsSystem` and `runAsUser` are: naming a connection must not drop an open\n * transaction handle or re-enable policies underneath it.\n *\n * Deliberately absent from `orm/index.ts`, so it is not part of what an\n * application can reach — `Model.on(name)` and `DB.connection(name)` are the\n * two doors, and both funnel through here so that a nested relation read,\n * which resolves its own class out of the registry and calls its `$exec`,\n * inherits the connection without anything having to pass it along.\n */\nexport function runOnConnection<T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n if (currentConnectionName() === name) return fn();\n\n // ENTERING A CONNECTION IS WHERE THE CROSS-CONNECTION CHECK BELONGS, not at\n // each door — and it has to be *here*, before the scope is entered, because\n // entering it is what makes the check impossible afterwards.\n //\n // The scope carries `tx` and `connection` together, so overwriting the name\n // while an open handle stays in place produces a store that says \"a\n // transaction on analytics\" while holding the *default* connection's handle.\n // Every check downstream then agrees with itself and the statement runs on\n // the wrong connection's transaction. `Model.save` found this: it routes to\n // the row's own connection, so it is the one caller that switches connections\n // with a transaction already open.\n assertConnectionUsable(name);\n\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n },\n fn,\n );\n}\n\n/**\n * Refuse a statement that names one connection while a transaction is open on\n * another.\n *\n * The check `withTransaction`'s single-connection note asked for, and the\n * reasoning for refusing rather than routing is on\n * `CrossConnectionTransactionError`. Both doors call it — `Model.$exec` for\n * every model operation, `DB` for a raw fragment — because either one alone\n * leaves the other free to straddle the two connections, and a raw `DB.execute`\n * escaping a transaction is the more damaging of the two.\n *\n * Only ever fires on a query that *names* a connection: an unqualified one\n * resolves to the ambient name, which is the transaction's own.\n */\nexport function assertConnectionUsable(name: string): void {\n const store = ormContext.getStore();\n if (store?.tx === undefined) return;\n\n const open = store.connection ?? DEFAULT_CONNECTION;\n if (open === name) return;\n\n throw new CrossConnectionTransactionError(open, name);\n}\n\n/**\n * Hold `callback` until the open transaction commits, and say whether that\n * happened.\n *\n * `false` means there was nothing to wait for — no transaction is open, or the\n * scope was entered by hand rather than by `withTransaction` — and the caller\n * must run the work itself, now. That return value is the whole contract: a\n * caller that ignores it turns \"no transaction here\" into a side effect queued\n * on a list nothing will ever drain, which is a dispatch that silently never\n * happens.\n *\n * `true` means the callback is on the outermost scope's list and will run after\n * `begin` resolves, outside the transaction, whatever the caller does next. It\n * will not run at all if the transaction rolls back, or if a savepoint it was\n * registered inside rolls back — both of which are the point.\n *\n * Nothing here is ordered against anything but the other deferred callbacks:\n * they run in registration order, one at a time, after the commit round-trip.\n */\nexport function deferUntilCommit(callback: AfterCommitCallback): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.afterCommit === undefined) return false;\n\n // Async work started inside a transaction and not awaited by it — a sync\n // listener still awaiting, an un-awaited emit — can reach here after the\n // transaction settled, through a scope that still carries its handle and its\n // list. Pushing then would queue onto a list already drained (or discarded),\n // and the work would silently never run. A committed list answers \"run it\n // now\"; a rolled-back one keeps the promise that nothing runs.\n const settled = settledLists.get(store.afterCommit);\n if (settled === \"committed\") return false;\n if (settled === \"rolled_back\") return true;\n\n store.afterCommit.push(callback);\n return true;\n}\n\n/**\n * How each outermost transaction's after-commit list ended, once it has. Keyed\n * by the list itself, which every savepoint and every lingering async scope of\n * that transaction shares by reference.\n */\nconst settledLists = new WeakMap<AfterCommitCallback[], \"committed\" | \"rolled_back\">();\n\n/**\n * Run `callback` once the open transaction commits, or now when none is open.\n * Never when the transaction rolls back, nor when a savepoint it was\n * registered inside rolls back.\n *\n * The application-facing form of `deferUntilCommit`, exported from `gemi/orm`\n * (#786). The difference is the `false` branch: `deferUntilCommit` hands the\n * \"no transaction\" case back to the caller, who must remember to run the work\n * itself, and this runs it. A caller that wants a side effect only once its\n * writes are durable — waking a long-poll, notifying another process — has\n * nothing left to get wrong.\n *\n * Inside a transaction the callback joins the same list `static afterCommit`\n * events use, so it is drained after `begin` resolves, outside the\n * transaction, in registration order with them.\n *\n * The returned promise resolves once the callback has run (no transaction) or\n * been queued (inside one). It never rejects: a callback that throws is\n * reported on stderr, as a deferred one is at the drain, so a caller that does\n * not await — the usual case — cannot leave an unhandled rejection behind, and\n * the two branches fail the same way. A sync callback outside a transaction\n * runs before this returns.\n */\nexport function afterCommit(\n callback: () => void | Promise<void>,\n): Promise<void> {\n if (deferUntilCommit(callback)) return Promise.resolve();\n\n const report = (error: unknown) => {\n console.error(\n `An after-commit callback threw. No transaction was open, so it ran ` +\n `immediately.`,\n error,\n );\n };\n try {\n return Promise.resolve(callback()).catch(report);\n } catch (error) {\n report(error);\n return Promise.resolve();\n }\n}\n\n/**\n * Make the open transaction's commit depend on `write`, a statement issued on\n * its handle: the transaction does not commit until `write` settles, and\n * rolls back — rejecting with `TransactionDependencyError` — if it rejected.\n *\n * For a write the caller may not await. A queued listener's dispatch never is\n * (`EventManager` pushes it and moves on), and on Postgres a statement that\n * fails aborts the whole transaction: every statement after it is refused and\n * Bun's `COMMIT` quietly becomes a rollback. Without this, the callback's\n * promise resolved, `begin` resolved, and the rows the caller wrote were gone\n * with nothing to say so. MySQL does not abort on a failed statement, and is\n * failed here anyway, so that a joined write means the same thing on both:\n * it commits with the transaction or the transaction does not commit.\n *\n * `false` when there is no transaction to depend on, as for\n * `deferUntilCommit`.\n */\nexport function commitDependsOn(write: Promise<unknown>): boolean {\n const store = ormContext.getStore();\n if (store?.tx === undefined || store.commitDependsOn === undefined) {\n return false;\n }\n store.commitDependsOn.push(write);\n return true;\n}\n\n/**\n * A write the transaction's commit depended on failed, so the transaction —\n * or the savepoint the write was made in — rolled back. `cause` is the write's\n * own error.\n */\nexport class TransactionDependencyError extends Error {\n constructor(cause: unknown) {\n super(\n `A statement this transaction depended on failed after being issued on ` +\n `it, so the transaction rolled back instead of committing: ` +\n `${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"TransactionDependencyError\";\n }\n}\n\n/**\n * Wait for the writes registered from `mark` on, and throw if one failed.\n *\n * Called at the end of a transaction's or savepoint's callback, *inside*\n * `begin`/`savepoint`, so a throw is what makes Bun roll back rather than\n * commit — after `begin` has resolved it is too late to do anything but\n * report. Every write is settled before throwing, so none is still running on\n * the handle when the rollback is issued.\n */\nasync function awaitDependencies(\n writes: Promise<unknown>[],\n mark: number,\n): Promise<void> {\n if (writes.length === mark) return;\n const settled = await Promise.allSettled(writes.slice(mark));\n const failed = settled.find(\n (outcome): outcome is PromiseRejectedResult => outcome.status === \"rejected\",\n );\n if (failed) throw new TransactionDependencyError(failed.reason);\n}\n\n/** How deeply nested the current transaction is; `null` outside one. */\nexport function transactionDepth(): number | null {\n const store = ormContext.getStore();\n return store?.tx === undefined ? null : store.depth;\n}\n\n/** Whether policies are suspended for the current async scope. */\nexport function isSystemScope(): boolean {\n return ormContext.getStore()?.system === true;\n}\n\n/**\n * Run `fn` with policies suspended.\n *\n * The escape hatch the deny-by-default rule needs to be usable: a cron tick, a\n * queue worker or a seed script has no user, and under deny-by-default every\n * policied model would refuse it. This makes that intent explicit *at the call\n * site*, which is the property that matters — unscoped access must never be\n * what happens when a user simply fails to turn up.\n *\n * It nests inside a transaction and a transaction nests inside it: the scope is\n * merged rather than replaced, so `asSystem` does not silently drop an open\n * handle.\n */\nexport function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run({ ...current, depth: current?.depth ?? 0, system: true }, fn);\n}\n\n/**\n * How `model`'s trashed rows are treated in this async scope, or `undefined`\n * for the default (hidden). See `OrmScope.trashed`.\n */\nexport function trashedMode(model: string): TrashedMode | undefined {\n return ormContext.getStore()?.trashed?.get(model);\n}\n\n/**\n * Run `fn` with `model`'s soft-delete scope lifted (`\"with\"`) or inverted\n * (`\"only\"`). Merged into the current scope like `runAsSystem`, so it keeps an\n * open transaction, the system flag and the actor — and every other policy.\n */\nexport function runWithTrashed<T>(\n model: string,\n mode: TrashedMode,\n fn: () => Promise<T>,\n): Promise<T> {\n const current = ormContext.getStore();\n const trashed = new Map(current?.trashed);\n trashed.set(model, mode);\n return ormContext.run(\n { ...current, depth: current?.depth ?? 0, trashed },\n fn,\n );\n}\n\n/** The explicitly-set actor, or `undefined` when none was. */\nexport function currentActor(): { user: unknown } | undefined {\n return ormContext.getStore()?.actor;\n}\n\n/**\n * Run `fn` with policies scoped to `user`, for code with no request to read one\n * from.\n *\n * The counterpart to `runAsSystem`, and the reason that one is not the only\n * escape hatch. A queue worker processing \"send the invoice for organisation 7\"\n * genuinely acts *as somebody*; giving it `asSystem` would suspend policies\n * entirely and leave it hand-scoping every query — which is precisely the\n * unscoped-by-accident failure the deny-by-default rule exists to prevent. The\n * narrow tool should be the easy one.\n *\n * It is also what makes policies testable without reaching into\n * `RequestContext`'s internals.\n *\n * Takes precedence over the request store, so a job that says who it is acting\n * as is not quietly overridden by an ambient request that happens to enclose it.\n *\n * It also **clears `system`**, which is the more surprising half. Acting as a\n * user is strictly narrower than acting as the system, so naming one inside an\n * `asSystem` block has to narrow back — and the spread would otherwise carry\n * `system: true` forward, leaving `$exec` to skip policies entirely while\n * `currentUser()` cheerfully returned the actor. Silently unscoped, from the\n * realistic shape: a worker enters `asSystem` to read its job queue, then\n * narrows to the job's owner for the work itself. The reverse nesting —\n * `asSystem` inside `asUser` — suspends policies, which is what it should do.\n */\nexport function runAsUser<T>(user: unknown, fn: () => Promise<T>): Promise<T> {\n const current = ormContext.getStore();\n return ormContext.run(\n {\n ...current,\n depth: current?.depth ?? 0,\n system: false,\n actor: { user: user ?? null },\n },\n fn,\n );\n}\n\n/**\n * The warning threshold in milliseconds, or `null` when the warning is off.\n *\n * `configured` is `database.slowTransactionThreshold` — see `DatabaseConfig`.\n * It arrives as a value rather than being read from here so that this file\n * keeps knowing nothing about the container: `withTransaction` is reachable\n * with a bare pool, and its tests use one.\n *\n * Exported for its own tests. The behaviour worth pinning is the fallback —\n * that a malformed threshold lands on the default rather than disabling — and\n * that cannot be observed through `withTransaction`: \"no warning fired\" is what\n * a disabled warning looks like too, so a behavioural test of it passes just as\n * happily when the fallback is gone. Asserting the number directly is the only\n * form of that test that can fail.\n */\nexport function slowTransactionThreshold(\n configured?: number | false,\n): number | null {\n // Read per call, never cached at module scope. `scripts/build.ts` rewrites\n // `process.env.NODE_ENV` to `Bun.env.NODE_ENV` precisely so mode stays a\n // runtime question in the built framework; caching it here would undo that.\n if (process.env.NODE_ENV !== \"development\") return null;\n\n // The one way to switch it off, and it has to be spelled. Everything else\n // falls back, so the warning is never lost to a mistyped value — only to an\n // explicit `false`.\n if (configured === false) return null;\n\n if (configured === undefined) return SLOW_TRANSACTION_THRESHOLD;\n if (!Number.isFinite(configured) || configured <= 0) {\n return SLOW_TRANSACTION_THRESHOLD;\n }\n return configured;\n}\n\n/**\n * Warn, in development only, about a transaction that has been open too long.\n *\n * The risk is structural rather than occasional: an open transaction holds one\n * reserved connection for as long as its callback runs, and nothing about\n * `Model.transaction(async () => { ... })` stops that callback from awaiting a\n * `fetch`, an S3 upload or a slow queue push. Under concurrency that drains the\n * pool, and the symptom — every unrelated query in the process blocking on\n * connection acquisition — names neither the callback nor the I/O in it.\n *\n * A timer rather than measuring elapsed time on the way out, for one reason:\n * the worst case is the transaction that *never* settles (a hung request, a\n * lock wait, a deadlock). After-the-fact measurement is silent for exactly that\n * case; a timer fires while it is still open and still holding the connection.\n *\n * The `Error` is constructed up front and read only if the timer fires — V8\n * formats `.stack` lazily on first access, so an ordinary fast transaction pays\n * for an object allocation and nothing else.\n *\n * The clock starts at the `begin` call, not at the moment a connection is\n * acquired, and stops when `begin` settles rather than when the callback\n * returns — so it spans the pool wait and the commit round-trip as well as the\n * callback. That is deliberate: all three are time this transaction is in\n * flight, and a warning that only covered the callback would stay silent for a\n * transaction stuck waiting on an exhausted pool, which is the exact situation\n * a long transaction elsewhere creates. Hence \"not settled\" rather than \"open\n * for\" — the message must not claim a connection was held for the whole span.\n */\nfunction watchForSlowTransaction(configured?: number | false): () => void {\n const threshold = slowTransactionThreshold(configured);\n if (threshold === null) return () => {};\n\n const site = new Error(\"transaction opened here\");\n\n const timer = setTimeout(() => {\n const stack = site.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\";\n console.warn(\n `[gemi] A database transaction has not settled after ${threshold}ms. It ` +\n `reserves a pooled connection until it does — check for network or ` +\n `filesystem I/O inside the callback, and move it outside the ` +\n `transaction if you find any.\\n${stack}\\n` +\n `(development only; set database.slowTransactionThreshold to change ` +\n `the threshold, or false to switch this off)`,\n );\n }, threshold);\n\n // Otherwise the warning timer is itself a reason the process stays alive,\n // which would turn a diagnostic into a hang in short-lived commands and\n // scripts.\n timer.unref?.();\n\n return () => clearTimeout(timer);\n}\n\n/**\n * Runs what a committed transaction deferred, outside the transaction it was\n * deferred by.\n *\n * `outside` is the scope that was ambient before `begin` — an `asSystem` block,\n * a named connection, or nothing at all — and re-entering it explicitly is the\n * guarantee rather than a tidy-up. The alternative is relying on where a `.then`\n * happens to have captured its context, and the failure that produces is the\n * one the whole feature is about: a listener that runs \"after commit\" while\n * still holding the closed transaction's handle joins nothing, because Bun's\n * handle stays callable and simply runs on the pool. So the scope is rebuilt\n * with `tx` and the drained list cleared, and a listener that opens its own\n * transaction gets a real one.\n *\n * Errors are caught per callback and the next one still runs, for the reason\n * the event subsystem catches per listener: these are independent side effects\n * whose order came from a filesystem walk. And the transaction is not failed by\n * one — it committed, the database kept the rows, and reporting a rejection to\n * the caller would have it roll back or retry work that is already durable.\n * stderr is all that is left, and it is enough: the caller has no decision to\n * make here.\n *\n * The transaction's own promise does not resolve until this has finished, which\n * is the one thing about `afterCommit` that a caller can feel. Deliberate: the\n * alternative is a floating promise whose rejection nobody sees and whose work\n * a short-lived process — a command, a seed — exits out from under.\n */\nasync function drainAfterCommit(\n callbacks: AfterCommitCallback[],\n outside: OrmScope | undefined,\n): Promise<void> {\n if (callbacks.length === 0) return;\n\n await ormContext.run(\n {\n ...outside,\n tx: undefined,\n afterCommit: undefined,\n commitDependsOn: undefined,\n depth: outside?.depth ?? 0,\n },\n async () => {\n for (const callback of callbacks) {\n try {\n await callback();\n } catch (error) {\n console.error(\n `An after-commit callback threw. The transaction it was waiting ` +\n `on had already committed and stays committed, and the ` +\n `callbacks after it still ran.`,\n error,\n );\n }\n }\n },\n );\n}\n\n/**\n * Run `fn` inside a transaction, entering the ambient scope for its whole async\n * subtree.\n *\n * The single implementation behind both `Model.transaction` and\n * `DB.transaction`, so the two cannot become transaction systems that ignore\n * each other: a `Model.create` inside a `DB.transaction` joins it, and a raw\n * `DB.sql` inside a `Model.transaction` can join it through\n * `currentTransaction()`.\n *\n * Nesting becomes a savepoint. Not a preference — Bun refuses the alternative\n * outright (`cannot call begin inside a transaction use savepoint() instead`),\n * and a savepoint is the semantics worth having anyway: an inner failure rolls\n * back to it and leaves the outer transaction usable, which a caller that\n * catches can rely on. Verified on SQLite and Postgres.\n *\n * Note Bun hands the savepoint callback the *same* handle object as the outer\n * transaction (`sp === tx`), so the depth counter is the only thing that\n * actually changes on the way in. The callback's argument is still what gets\n * stored, so this keeps working if that ever stops being true. The cast is\n * because Bun types a savepoint handle as plain `SQL` — without `savepoint` on\n * it — while the runtime object does carry the method, which is what makes\n * three levels of nesting work.\n *\n * Anything `deferUntilCommit` queued is drained once `begin` resolves, outside\n * the transaction and only on the outermost call — a savepoint has committed\n * nothing durable, so draining there would run work that a later rollback of\n * the enclosing transaction was meant to have prevented. See `drainAfterCommit`\n * for what that costs the caller.\n *\n * In development, an outermost transaction that stays open past\n * `options.slowTransactionThreshold` (2s by default, `false` to disable) warns\n * — see `watchForSlowTransaction`. Nothing here *prevents* a long transaction;\n * the warning exists because the cost of one is paid by unrelated queries\n * elsewhere in the process, which makes it hard to trace back.\n *\n * The threshold is passed in rather than read from `app(DatabaseManager)` here.\n * Every caller already holds the manager — it is where `pool` came from — and\n * taking it as an argument keeps this file free of the container, so a bare\n * `SQL` is still enough to call it. Its tests rely on that.\n *\n * `options.connection` is the name `pool` belongs to, and follows the same rule\n * for the same reason: the pool cannot be asked what it is called. Passing it\n * is what lets a nested `withTransaction` tell \"the same connection, so take a\n * savepoint\" from \"a different one, so refuse\" — omitting it means the default\n * connection, which is what a two-argument call always meant.\n *\n * The return type is asserted rather than inferred for one reason worth\n * knowing: Bun's `begin` unwraps a callback that resolves to an *array of\n * promises*, awaiting each. So `Model.transaction(async () => [a, b])` where\n * `a` and `b` are promises resolves to their values, not to the promises. That\n * is Bun's behaviour and is left alone; it is only surprising if unmentioned.\n */\nexport function withTransaction<T>(\n pool: SQL,\n fn: (tx: TransactionSQL) => Promise<T>,\n options?: { slowTransactionThreshold?: number | false; connection?: string },\n): Promise<T> {\n const current = ormContext.getStore();\n\n // THE SINGLE-CONNECTION ASSUMPTION, WHICH IS NOW CHECKED RATHER THAN PINNED.\n //\n // The savepoint branch below ignores `pool` entirely. That was correct while\n // there was one `DatabaseManager` and one `SQL` — the ambient handle and\n // whatever pool the caller passed were necessarily the same database — and\n // the note that stood here said what would happen when a second connection\n // became configurable (#327): a `DB.transaction` on B inside a\n // `Model.transaction` on A would savepoint on **A** and hand the callback A's\n // handle, so statements landed in the wrong database with no error at all.\n //\n // So the name is compared before the branch is taken, and a mismatch raises.\n // Refusing is the whole answer rather than half of one — there is no way to\n // make one transaction span two pools, and the alternatives are covered on\n // `CrossConnectionTransactionError`.\n //\n // A caller that passes no `connection` is treated as naming the default,\n // which is what `withTransaction(pool, fn)` meant before this argument\n // existed.\n const name = options?.connection ?? DEFAULT_CONNECTION;\n assertConnectionUsable(name);\n\n // `current?.tx` rather than `current`: since iteration 6 a scope can exist\n // with no open transaction — `Model.asSystem` enters one — and a savepoint\n // needs an actual handle, not merely a store.\n if (current?.tx) {\n // WHERE THE SHARED AFTER-COMMIT LIST IS PUT RIGHT.\n //\n // The savepoint's scope is a spread of this one, so it appends to the\n // transaction's list rather than to a list of its own — which is what makes\n // \"the outer transaction rolled back, so nothing runs\" free. The case that\n // is not free is this one: the savepoint rolls back and the transaction\n // goes on to commit. Its entries have to go, or a dispatch made inside a\n // block the database threw away runs anyway, which is the same wrong answer\n // as before with an extra step.\n //\n // A mark on the way in and a truncate on the way out, rather than tagging\n // each entry with its depth and dropping everything at or below the failing\n // one. Depth cannot tell two *siblings* apart: a savepoint that committed\n // and one that rolled back both left entries at the same depth, adjacent in\n // the list, and dropping by depth would discard the committed sibling's\n // work as well. The index is exact because the ORM issues one statement at\n // a time on a transaction handle — see `OrmScope.tx` — so nothing appends\n // between the mark and the failure but this savepoint's own subtree.\n const deferred = current.afterCommit;\n const mark = deferred?.length ?? 0;\n // The same mark for the writes the commit depends on. The savepoint waits\n // for its own before it releases, so one that failed rolls back only the\n // savepoint — which a caller that catches can survive, exactly as it\n // survives a statement that threw inside it — and is then forgotten\n // rather than failing the transaction a second time.\n const dependencies = current.commitDependsOn;\n const dependencyMark = dependencies?.length ?? 0;\n\n return current.tx\n .savepoint((sp) => {\n const nested = sp as TransactionSQL;\n return ormContext.run(\n { ...current, tx: nested, depth: current.depth + 1 },\n async () => {\n const result = await fn(nested);\n if (dependencies) {\n await awaitDependencies(dependencies, dependencyMark);\n }\n return result;\n },\n );\n })\n .catch((error: unknown) => {\n if (deferred) deferred.length = mark;\n if (dependencies) dependencies.length = dependencyMark;\n throw error;\n }) as Promise<T>;\n }\n\n // Only the outermost scope is watched. A savepoint reserves no connection of\n // its own — its lifetime is bounded by the transaction it sits in, which is\n // already being timed — so warning per depth would report one slow block as\n // several warnings and point at the innermost frame rather than the one\n // holding the connection.\n const stopWatching = watchForSlowTransaction(\n options?.slowTransactionThreshold,\n );\n\n // Built out here rather than inside the `begin` callback, because the drain\n // below needs it *after* that callback's scope is gone, and reading it off\n // the store then is exactly what is no longer possible.\n const deferred: AfterCommitCallback[] = [];\n const dependencies: Promise<unknown>[] = [];\n\n // The `try` covers a *synchronous* throw from `begin` — a closed pool, say.\n // `.finally` alone would not: it is only attached once `begin` has returned a\n // promise, so a synchronous throw escapes with the timer still armed and\n // eventually warns about a transaction that never opened. `unref` keeps that\n // from holding the process, which makes it cosmetic rather than a leak, but\n // it is the same gap the `.finally` below exists to close.\n try {\n // Spread rather than replace: a `Model.transaction` inside a\n // `Model.asSystem` must not silently re-enable policies for its subtree.\n //\n // The connection goes into the scope alongside the handle, and the pair is\n // what makes the check at the top of this function possible: \"which\n // connection is this transaction on\" has to be answerable from the store,\n // because the handle itself does not say. It is also what makes an\n // unqualified query inside `DB.connection(\"analytics\").transaction(...)`\n // *join* the transaction instead of being refused by it — the query\n // inherits the name rather than defaulting to the hot path.\n return (\n pool\n .begin((tx) =>\n ormContext.run(\n {\n ...current,\n tx,\n depth: 0,\n connection: name === DEFAULT_CONNECTION ? undefined : name,\n // A fresh list per outermost transaction, assigned rather than\n // left to the spread. `current` holds no list today — the drain\n // clears the field before it runs anything — and assigning is\n // what keeps that from being load-bearing: a transaction opened\n // by a callback during a drain gets its own list either way,\n // rather than appending to the array it is being run out of.\n afterCommit: deferred,\n commitDependsOn: dependencies,\n },\n async () => {\n const result = await fn(tx);\n await awaitDependencies(dependencies, 0);\n return result;\n },\n ),\n )\n // `finally` and not a `then`/`catch` pair: the connection is released on\n // rollback exactly as it is on commit, so a throwing callback must clear\n // the timer too or every failed transaction leaves a warning armed\n // against a connection that has already gone back to the pool.\n //\n // Before the drain, so that a slow after-commit listener is not\n // reported as a transaction that will not settle. The connection went\n // back to the pool at the commit; the warning is about holding it.\n .finally(stopWatching)\n // Only here, on the fulfilled path. A rejected `begin` rolled back, so\n // the scope and everything queued on it are discarded unread — which is\n // the whole of what `afterCommit` promises.\n .then(\n async (result) => {\n settledLists.set(deferred, \"committed\");\n await drainAfterCommit(deferred, current);\n return result;\n },\n (error: unknown) => {\n settledLists.set(deferred, \"rolled_back\");\n throw error;\n },\n ) as Promise<T>\n );\n } catch (error) {\n stopWatching();\n throw error;\n }\n}\n"
6
6
  ],
7
7
  "mappings": ";yDACA,4BAAS,oBAmJF,IAAM,EAAa,IAAI,EAavB,SAAS,CAAkB,EAA+B,CAC/D,OAAO,EAAW,SAAS,GAAG,GAUzB,SAAS,CAAqB,EAAW,CAC9C,OAAO,EAAW,SAAS,GAAG,YAAc,EAgBvC,SAAS,CAAkB,CAChC,EACA,EACY,CACZ,IAAM,EAAU,EAAW,SAAS,EACpC,GAAI,EAAsB,IAAM,EAAM,OAAO,EAAG,EAehD,OAFA,EAAuB,CAAI,EAEpB,EAAW,IAChB,IACK,EACH,MAAO,GAAS,OAAS,EACzB,WAAY,IAAS,EAAqB,OAAY,CACxD,EACA,CACF,EAiBK,SAAS,CAAsB,CAAC,EAAoB,CACzD,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,OAAW,OAE7B,IAAM,EAAO,EAAM,YAAc,EACjC,GAAI,IAAS,EAAM,OAEnB,MAAM,IAAI,EAAgC,EAAM,CAAI,EAsB/C,SAAS,CAAgB,CAAC,EAAwC,CACvE,IAAM,EAAQ,EAAW,SAAS,EAClC,GAAI,GAAO,KAAO,QAAa,EAAM,cAAgB,OAAW,MAAO,GAQvE,IAAM,EAAU,EAAa,IAAI,EAAM,WAAW,EAClD,GAAI,IAAY,YAAa,MAAO,GACpC,GAAI,IAAY,cAAe,MAAO,GAGtC,OADA,EAAM,YAAY,KAAK,CAAQ,EACxB,GAQT,IAAM,EAAe,I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2164756E21",
8
+ "debugId": "F7605D555AE36ACE64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Q as C}from"./chunk-fn2qfwgx.js";import{aa as A}from"./chunk-kzsjyvvc.js";import{Jj as _}from"./chunk-17dndh5z.js";var S=_(C(),1),p=_(A(),1),N="AWS_ACCESS_KEY_ID",a="AWS_SECRET_ACCESS_KEY",i="AWS_SESSION_TOKEN",I="AWS_CREDENTIAL_EXPIRATION",d="AWS_CREDENTIAL_SCOPE",v="AWS_ACCOUNT_ID",T=(e)=>async()=>{e?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let o=process.env[N],r=process.env[a],n=process.env[i],s=process.env[I],t=process.env[d],E=process.env[v];if(o&&r){let c={accessKeyId:o,secretAccessKey:r,...n&&{sessionToken:n},...s&&{expiration:new Date(s)},...t&&{credentialScope:t},...E&&{accountId:E}};return S.setCredentialFeature(c,"CREDENTIALS_ENV_VARS","g"),c}throw new p.CredentialsProviderError("Unable to find environment variable credentials.",{logger:e?.logger})};export{N as a,a as b,i as c,I as d,d as e,v as f,T as g};
2
+ import{Q as C}from"./chunk-6vz75swk.js";import{aa as A}from"./chunk-7zj6bk9a.js";import{Dk as _}from"./chunk-hxn0s3zh.js";var S=_(C(),1),p=_(A(),1),N="AWS_ACCESS_KEY_ID",a="AWS_SECRET_ACCESS_KEY",i="AWS_SESSION_TOKEN",I="AWS_CREDENTIAL_EXPIRATION",d="AWS_CREDENTIAL_SCOPE",v="AWS_ACCOUNT_ID",T=(e)=>async()=>{e?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let o=process.env[N],r=process.env[a],n=process.env[i],s=process.env[I],t=process.env[d],E=process.env[v];if(o&&r){let c={accessKeyId:o,secretAccessKey:r,...n&&{sessionToken:n},...s&&{expiration:new Date(s)},...t&&{credentialScope:t},...E&&{accountId:E}};return S.setCredentialFeature(c,"CREDENTIALS_ENV_VARS","g"),c}throw new p.CredentialsProviderError("Unable to find environment variable credentials.",{logger:e?.logger})};export{N as a,a as b,i as c,I as d,d as e,v as f,T as g};
3
3
 
4
- //# debugId=D105571FD7A9E5E864756E2164756E21
4
+ //# debugId=84347603A0CA2CCD64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { setCredentialFeature } from \"@aws-sdk/core/client\";\nimport { CredentialsProviderError } from \"@smithy/property-provider\";\nexport const ENV_KEY = \"AWS_ACCESS_KEY_ID\";\nexport const ENV_SECRET = \"AWS_SECRET_ACCESS_KEY\";\nexport const ENV_SESSION = \"AWS_SESSION_TOKEN\";\nexport const ENV_EXPIRATION = \"AWS_CREDENTIAL_EXPIRATION\";\nexport const ENV_CREDENTIAL_SCOPE = \"AWS_CREDENTIAL_SCOPE\";\nexport const ENV_ACCOUNT_ID = \"AWS_ACCOUNT_ID\";\nexport const fromEnv = (init) => async () => {\n init?.logger?.debug(\"@aws-sdk/credential-provider-env - fromEnv\");\n const accessKeyId = process.env[ENV_KEY];\n const secretAccessKey = process.env[ENV_SECRET];\n const sessionToken = process.env[ENV_SESSION];\n const expiry = process.env[ENV_EXPIRATION];\n const credentialScope = process.env[ENV_CREDENTIAL_SCOPE];\n const accountId = process.env[ENV_ACCOUNT_ID];\n if (accessKeyId && secretAccessKey) {\n const credentials = {\n accessKeyId,\n secretAccessKey,\n ...(sessionToken && { sessionToken }),\n ...(expiry && { expiration: new Date(expiry) }),\n ...(credentialScope && { credentialScope }),\n ...(accountId && { accountId }),\n };\n setCredentialFeature(credentials, \"CREDENTIALS_ENV_VARS\", \"g\");\n return credentials;\n }\n throw new CredentialsProviderError(\"Unable to find environment variable credentials.\", { logger: init?.logger });\n};\n"
6
6
  ],
7
7
  "mappings": ";sIAAA,SACA,KACa,EAAU,oBACV,EAAa,wBACb,EAAc,oBACd,EAAiB,4BACjB,EAAuB,uBACvB,EAAiB,iBACjB,EAAU,CAAC,IAAS,SAAY,CACzC,GAAM,QAAQ,MAAM,4CAA4C,EAChE,IAAM,EAAc,QAAQ,IAAI,GAC1B,EAAkB,QAAQ,IAAI,GAC9B,EAAe,QAAQ,IAAI,GAC3B,EAAS,QAAQ,IAAI,GACrB,EAAkB,QAAQ,IAAI,GAC9B,EAAY,QAAQ,IAAI,GAC9B,GAAI,GAAe,EAAiB,CAChC,IAAM,EAAc,CAChB,cACA,qBACI,GAAgB,CAAE,cAAa,KAC/B,GAAU,CAAE,WAAY,IAAI,KAAK,CAAM,CAAE,KACzC,GAAmB,CAAE,iBAAgB,KACrC,GAAa,CAAE,WAAU,CACjC,EAEA,OADA,uBAAqB,EAAa,uBAAwB,GAAG,EACtD,EAEX,MAAM,IAAI,2BAAyB,mDAAoD,CAAE,OAAQ,GAAM,MAAO,CAAC",
8
- "debugId": "D105571FD7A9E5E864756E2164756E21",
8
+ "debugId": "84347603A0CA2CCD64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -29,6 +29,6 @@ export { h } from ${JSON.stringify("virtual:gemi-island-runtime")};
29
29
  import { hydrateRoot } from "react-dom/client";
30
30
  export ${z}
31
31
  `,Q='const d=document,c=JSON.parse(d.getElementById("gemi-islands").textContent),w=f=>(window.requestIdleCallback||setTimeout)(f),m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};for(const e of d.querySelectorAll("gemi-island")){const o=c.i[e.dataset.island];if(!o)continue;if(o.l=="eager")m(e,o);else if(o.l=="idle"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}';
32
- export{B as rj,F as sj,G as tj,J as uj,M as vj,Q as wj};
32
+ export{B as kk,F as lk,G as mk,J as nk,M as ok,Q as pk};
33
33
 
34
- //# debugId=AE4637C298F0D39E64756E2164756E21
34
+ //# debugId=21D334A89B93406564756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "/**\n * The browser side of islands, shared by the Vite plugin (which builds it), the\n * servers (which point the loader at it) and the tests.\n *\n * No imports: the Vite plugin is built on its own and the servers load it at\n * boot, so this file stays plain strings.\n */\n\n/**\n * The module that hydrates islands: React, `react-dom/client` and the small\n * `h(marker, Component)` below. A virtual module of gemi's Vite plugin that\n * every island entry imports, so the islands on a page share one copy of\n * React, in one chunk.\n */\nexport const ISLAND_RUNTIME_ID = \"virtual:gemi-island-runtime\";\n\n/** What `resolveId` turns `ISLAND_RUNTIME_ID` into (Vite's virtual-module convention). */\nexport const RESOLVED_ISLAND_RUNTIME_ID = `\\0${ISLAND_RUNTIME_ID}`;\n\n/**\n * The query that turns a module into its island entry: `Counter.tsx?gemi-island`\n * is a module of the plugin's that re-exports `Counter.tsx` as `m` next to the\n * runtime's `h`. It is what a static page imports for an island, and so it\n * is what the client manifest lists, keyed `app/…/Counter.tsx?gemi-island`,\n * with React and `react-dom/client` among its imports.\n */\nexport const ISLAND_ENTRY_QUERY = \"?gemi-island\";\n\n/** The island entry module for `file` (an absolute path or a root-relative URL). */\nexport function islandEntrySource(file: string) {\n return `import * as m from ${JSON.stringify(file)};\nexport { m };\nexport { h } from ${JSON.stringify(ISLAND_RUNTIME_ID)};\n`;\n}\n\n/**\n * `h(marker, Component)`: hydrates one `<gemi-island>` marker with the island's\n * component and the props the server serialised into `data-props`.\n *\n * The island's static children were rendered on the server into a\n * `<gemi-slot>` (the first one that belongs to this marker, not to an island\n * nested in it). They are handed back to the component as that same element\n * with the server's HTML, so hydration matches and React leaves them alone.\n *\n * `data-uid` is the `identifierPrefix` the server rendered the island with, so\n * `useId` agrees on both sides and two islands never share an id.\n *\n * Written as a function body with `createElement` and `hydrateRoot` free, so a\n * test can run it against real React without a bundler.\n */\nexport const ISLAND_HYDRATE_SOURCE = `function h(marker, Component) {\n if (typeof Component !== \"function\" && (typeof Component !== \"object\" || Component === null)) {\n throw new Error(\"gemi: island module has no component export for \" + marker.outerHTML.slice(0, 80));\n }\n const json = marker.getAttribute(\"data-props\");\n const props = json ? JSON.parse(json) : {};\n let slot = null;\n for (const candidate of marker.querySelectorAll(\"gemi-slot\")) {\n if (candidate.closest(\"gemi-island\") === marker) {\n slot = candidate;\n break;\n }\n }\n const children = slot\n ? [createElement(\"gemi-slot\", {\n style: { display: \"contents\" },\n suppressHydrationWarning: true,\n dangerouslySetInnerHTML: { __html: slot.innerHTML },\n })]\n : [];\n return hydrateRoot(marker, createElement(Component, props, ...children), {\n identifierPrefix: marker.getAttribute(\"data-uid\") || undefined,\n });\n}`;\n\n/** The runtime module's source, as the plugin serves and builds it. */\nexport const ISLAND_RUNTIME_SOURCE = `import { createElement } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nexport ${ISLAND_HYDRATE_SOURCE}\n`;\n\n/**\n * The island loader, inlined into a static document that uses islands.\n *\n * Kept byte-for-byte constant (the per-page island table travels in a\n * separate `<script type=\"application/json\">`, which a Content Security Policy\n * does not treat as script), so a strict policy can allow it by hash:\n * `script-src 'sha256-…'` with `ISLAND_LOADER_CSP_HASH`. Everything it loads\n * is a plain `import()` of a same-origin (or asset-base) file.\n *\n * The table is `{ i: [{ s: entry URL, e: export, l: load }] }` and each\n * marker's `data-island` indexes `i`. Per marker, on its schedule: import the\n * island's entry (the module as `m`, the runtime's `h`), then\n * `h(marker, m[export])`, which calls `hydrateRoot`. A failure is logged and\n * leaves the server-rendered markup in place.\n */\nexport const ISLAND_LOADER_SOURCE =\n 'const d=document,c=JSON.parse(d.getElementById(\"gemi-islands\").textContent),' +\n \"w=f=>(window.requestIdleCallback||setTimeout)(f),\" +\n \"m=(e,o)=>{if(!e.g){e.g=1;import(o.s).then(x=>x.h(e,x.m[o.e])).catch(r=>console.error(r))}};\" +\n 'for(const e of d.querySelectorAll(\"gemi-island\")){const o=c.i[e.dataset.island];if(!o)continue;' +\n 'if(o.l==\"eager\")m(e,o);else if(o.l==\"idle\"||!window.IntersectionObserver||!e.children.length)w(()=>m(e,o));' +\n \"else{const v=new IntersectionObserver(n=>{if(n.some(x=>x.isIntersecting)){v.disconnect();m(e,o)}});for(const k of e.children)v.observe(k)}}\";\n"
6
6
  ],
7
7
  "mappings": ";AAcO,IAAM,EAAoB,8BAGpB,EAA6B,kCAS7B,EAAqB,eAG3B,SAAS,CAAiB,CAAC,EAAc,CAC9C,MAAO,sBAAsB,KAAK,UAAU,CAAI;AAAA;AAAA,oBAE9B,KAAK,UAlBQ,6BAkBmB;AAAA,EAmB7C,IAAM,EAAwB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GA0BxB,EAAwB;AAAA;AAAA,SAE5B;AAAA,EAkBI,EACX",
8
- "debugId": "AE4637C298F0D39E64756E2164756E21",
8
+ "debugId": "21D334A89B93406564756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  function v(j){return j==="/api"||j.startsWith("/api/")}function z(j){return v(j)?j.slice(4):j}
3
- export{v as Hj,z as Ij};
3
+ export{v as Bk,z as Ck};
4
4
 
5
- //# debugId=C8E388136BA39D9164756E2164756E21
5
+ //# debugId=C849F80A2661EC7B64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "/**\n * The prefix every api route is served under. The browser adds it when it\n * fetches (`/api${path}`) and the server strips it before matching, so an api\n * router's own paths never carry it.\n */\nexport const API_PREFIX = \"/api\";\n\n/**\n * Whether a request pathname is an api request: `/api` itself or anything\n * under `/api/`. A bare `startsWith(\"/api\")` also claims `/apidocs`,\n * `/api-keys` and `/apiary`, so a view route there would never render — the\n * api dispatcher would answer its 404 JSON instead.\n */\nexport function isApiPath(pathname: string): boolean {\n return pathname === API_PREFIX || pathname.startsWith(`${API_PREFIX}/`);\n}\n\n/**\n * The api router path a request pathname addresses: `/api/users/1` is\n * `/users/1`, `/api/` is `/` and `/api` is `\"\"`. Only the leading prefix is\n * stripped — `replace(\"/api\", \"\")` would also strip an `/api` inside the path\n * of a request that did not start with one (`/files/api` becoming `/files`).\n * A pathname outside `/api` comes back unchanged, so the dispatcher can still\n * be handed a request by its route path directly.\n */\nexport function apiPath(pathname: string): string {\n return isApiPath(pathname) ? pathname.slice(API_PREFIX.length) : pathname;\n}\n"
6
6
  ],
7
7
  "mappings": ";AAaO,SAAS,CAAS,CAAC,EAA2B,CACnD,OAAO,IATiB,QASU,EAAS,WAAW,OAAgB,EAWjE,SAAS,CAAO,CAAC,EAA0B,CAChD,OAAO,EAAU,CAAQ,EAAI,EAAS,MAAM,CAAiB,EAAI",
8
- "debugId": "C8E388136BA39D9164756E2164756E21",
8
+ "debugId": "C849F80A2661EC7B64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Kh as g,Lh as m,di as k}from"./chunk-96a1459v.js";import{oj as p}from"./chunk-rpyczdta.js";import{Lj as n}from"./chunk-17dndh5z.js";var b={};n(b,{registeredNames:()=>x,register:()=>i,has:()=>S,get:()=>_,clearRegistry:()=>a});var M=new Map;function i(q,z){M.set(q,z)}function S(q){return M.has(q)}function _(q){let z=M.get(q);if(z===void 0)throw new k(q,[...M.keys()]);return z}function x(){return[...M.keys()]}function a(){M.clear()}import{createCipheriv as r,createDecipheriv as e,randomBytes as qq}from"crypto";class Y{static token="encrypter";keys=new Map;currentId;constructor(q={}){for(let[z,J]of Object.entries(q.keys??{})){if(!u.test(z))throw new U(`Encryption key id "${z}" is not valid. Use 1-32 letters, digits, "_" or "-": the id is written into every encrypted value.`);this.keys.set(z,zq(z,J))}if(q.current!==void 0){if(!this.keys.has(q.current))throw new U(`encryption.current is "${q.current}", but encryption.keys has no key by that id (${I(this.keys)}).`);this.currentId=q.current}else if(this.keys.size===1)this.currentId=[...this.keys.keys()][0];else if(this.keys.size>1)throw new U(`encryption.keys has ${this.keys.size} keys (${I(this.keys)}) and no encryption.current to say which one encrypts new values.`)}get configured(){return this.currentId!==void 0}get currentKeyId(){return this.requireCurrent()}encrypt(q){if(typeof q!=="string")throw TypeError(`Encrypter.encrypt takes a string, got ${Jq(q)}. Serialise other values first (JSON.stringify).`);let z=this.requireCurrent(),J=this.keys.get(z),Q=`${j}:${z}`,Z=qq(y),$=r(E,J,Z);$.setAAD(Buffer.from(Q));let X=Buffer.concat([$.update(q,"utf8"),$.final(),$.getAuthTag()]);return`${Q}:${Z.toString("base64url")}:${X.toString("base64url")}`}decrypt(q){let z=D(q);if(!z)throw new N("malformed","The value is not an encrypted envelope.");if(!this.configured)this.requireCurrent();let J=this.keys.get(z.keyId);if(!J)throw new N("unknown_key",`The value was encrypted with key "${z.keyId}", which is not in encryption.keys (${I(this.keys)}). Keep a key configured until encryption:rotate has re-encrypted the values written with it.`);try{let Q=e(E,J,z.iv);return Q.setAAD(Buffer.from(`${j}:${z.keyId}`)),Q.setAuthTag(z.tag),Buffer.concat([Q.update(z.ciphertext),Q.final()]).toString("utf8")}catch{throw new N("invalid",`The value did not authenticate under key "${z.keyId}": it was altered, or encrypted with a different key under the same id.`)}}isEncrypted(q){return D(q)!==null}keyIdOf(q){return D(q)?.keyId??null}needsReencryption(q){return this.keyIdOf(q)!==this.requireCurrent()}requireCurrent(){if(this.currentId===void 0)throw new U("No encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as `encryption` in your Kernel's config. Generate a key with `openssl rand -base64 32`.");return this.currentId}}class U extends Error{constructor(q){super(q);this.name="EncryptionKeyError"}}class N extends Error{reason;column;constructor(q,z){super(z);this.reason=q;this.name="DecryptionError"}}var j="v1",E="aes-256-gcm",f=32,y=12,A=16,u=/^[A-Za-z0-9_-]{1,32}$/,v=/^[A-Za-z0-9_-]+$/;function zq(q,z){if(typeof z!=="string"||z.trim()==="")throw new U(`Encryption key "${q}" is empty. Is the environment variable it reads set?`);let J=z.trim().replace(/^base64:/,""),Q=/^[A-Za-z0-9+/=_-]+$/.test(J)?Buffer.from(J,"base64"):Buffer.alloc(0);if(Q.length!==f)throw new U(`Encryption key "${q}" is not ${f} bytes of base64 (it decodes to ${Q.length}). Generate one with \`openssl rand -base64 32\`.`);return Q}function D(q){if(typeof q!=="string")return null;let z=q.split(":");if(z.length!==4||z[0]!==j)return null;let[,J,Q,Z]=z;if(!u.test(J)||!v.test(Q)||!v.test(Z))return null;let $=Buffer.from(Q,"base64url"),X=Buffer.from(Z,"base64url");if($.length!==y||X.length<A)return null;return{keyId:J,iv:$,ciphertext:X.subarray(0,X.length-A),tag:X.subarray(X.length-A)}}function I(q){return q.size===0?"none configured":[...q.keys()].map((z)=>`"${z}"`).join(", ")}function Jq(q){return q===null?"null":Array.isArray(q)?"an array":`a ${typeof q}`}var h=new WeakMap;function T(q){let z=h.get(q);if(z===void 0)z=Object.values(q.fields).filter((J)=>J.encrypted===!0).map((J)=>J.name),h.set(q,z);return z}function Mq(){let q=new Set,z=[];for(let J of x()){let Q=O(J);if(!Q||q.has(Q.name))continue;q.add(Q.name);for(let Z of T(Q))z.push(`${Q.name}.${Z}`)}return z}function c(){let q=p();if(!q.bound(Y))throw new U("Encrypted columns need an Encrypter, and none is bound in this application. A booted Kernel binds one from the `encryption` config slice; a hand-built Application can bind its own: `application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.");return q.make(Y)}var l=Symbol("gemi.orm.encryptedColumnsRaw");function Nq(q){return{...q,[l]:!0}}function Vq(q){return typeof q==="object"&&q!==null&&q[l]===!0}function Lq(q,z,J){if(!P(J))return;let Q={model:q.name,operation:z};d(q,J,Q,0);for(let Z of["by","_min","_max","_avg","_sum"])if(J[Z]!==void 0)o(q,J[Z],Z,Q);if(J.having!==void 0)B(q,J.having,Q)}var w=64;function d(q,z,J,Q){if(Q>w)return;if(z.where!==void 0)W(q,z.where,"where",J,Q);if(z.cursor!==void 0)W(q,z.cursor,"cursor",J,Q);if(z.orderBy!==void 0)K(q,z.orderBy,J,Q);if(z.distinct!==void 0)o(q,z.distinct,"distinct",J);for(let Z of[z.include,z.select]){if(!P(Z))continue;for(let[$,X]of Object.entries(Z)){if(!P(X))continue;if($==="_count"){if(!P(X.select))continue;for(let[G,F]of Object.entries(X.select)){let H=R(q,G);if(H&&P(F)&&F.where!==void 0)W(H,F.where,"where",J,Q+1)}continue}let C=R(q,$);if(C)d(C,X,J,Q+1)}}}var Qq=["some","every","none","is","isNot"];function W(q,z,J,Q,Z){if(Z>w)return;if(Array.isArray(z)){for(let $ of z)W(q,$,J,Q,Z);return}if(!P(z))return;for(let[$,X]of Object.entries(z)){if(X===void 0)continue;if($==="AND"||$==="OR"||$==="NOT"){W(q,X,J,Q,Z);continue}let C=q.fields[$];if(C){if(C.encrypted===!0&&!t(X))L(q,$,J,Q);continue}let G=R(q,$);if(G){if(!P(X))continue;let F=Object.keys(X).filter((H)=>Qq.includes(H));if(F.length>0)for(let H of F)W(G,X[H],J,Q,Z+1);else W(G,X,J,Q,Z+1);continue}if(P(X)){for(let F of Object.keys(X))if(q.fields[F]?.encrypted===!0)L(q,F,J,Q)}}}function K(q,z,J,Q){if(Q>w)return;if(Array.isArray(z)){for(let Z of z)K(q,Z,J,Q);return}if(!P(z))return;for(let[Z,$]of Object.entries(z)){if(q.fields[Z]?.encrypted===!0)L(q,Z,"orderBy",J);let X=R(q,Z);if(X&&P($)&&!("_count"in $))K(X,$,J,Q+1)}}function o(q,z,J,Q){let Z=typeof z==="string"?[z]:Array.isArray(z)?z.filter(($)=>typeof $==="string"):P(z)?Object.keys(z).filter(($)=>z[$]):[];for(let $ of Z)if(q.fields[$]?.encrypted===!0)L(q,$,J,Q)}function B(q,z,J){if(Array.isArray(z)){for(let Q of z)B(q,Q,J);return}if(!P(z))return;for(let[Q,Z]of Object.entries(z)){if(Q==="AND"||Q==="OR"||Q==="NOT"){B(q,Z,J);continue}if(q.fields[Q]?.encrypted===!0&&!t(Z))L(q,Q,"having",J)}}function t(q){if(q===null)return!0;if(!P(q))return!1;let z=Object.entries(q).filter(([,J])=>J!==void 0);return z.length>0&&z.every(([J,Q])=>(J==="equals"||J==="not")&&Q===null)}function L(q,z,J,Q){throw new m(J,Q.model,Q.operation,`${q.name}.${z} is an encrypted column: each write stores a different random ciphertext, so the database cannot compare, sort or group by it. Only null checks work on it ({ ${z}: null } or { ${z}: { not: null } }). To look a row up by a secret, store a keyed hash of it in a separate column and filter on that.`)}function Yq(q,z,J){let Q=T(q);if(Q.length===0||!P(J))return J;let Z={model:q.name,operation:z},$,X=(F)=>($??=c()).encrypt(F),C=J,G=(F,H)=>{if(H===C[F])return;if(C===J)C={...J};C[F]=H};switch(z){case"create":case"update":case"updateMany":G("data",V(Q,J.data,X,Z));break;case"createMany":G("data",Array.isArray(J.data)?Zq(J.data,(F)=>V(Q,F,X,Z)):V(Q,J.data,X,Z));break;case"upsert":G("create",V(Q,J.create,X,Z)),G("update",V(Q,J.update,X,Z));break}return C}function V(q,z,J,Q){if(!P(z))return z;let Z;for(let $ of q){if(!($ in z))continue;let X=z[$],C=s($,X,J,Q);if(C!==X)(Z??={...z})[$]=C}return Z??z}function s(q,z,J,Q){if(z===void 0||z===null)return z;if(typeof z==="string")return J(z);if(P(z)&&Object.keys(z).length===1&&"set"in z){let Z=z.set;return Z===null||Z===void 0?z:{set:s(q,Z,J,Q)}}throw new g("data",Q.model,Q.operation,`${Q.model}.${q} is an encrypted column and takes a string or null (or { set: string | null }); got ${Cq(z)}.`)}function Zq(q,z){let J;return q.forEach((Q,Z)=>{let $=z(Q);if($!==Q)(J??=[...q])[Z]=$}),J??q}function $q(q,z){let J=T(q);if(J.length===0||z.length===0)return;let Q;for(let Z of z){if(!P(Z))continue;for(let $ of J){let X=Z[$];if(typeof X!=="string")continue;Q??=c();try{Z[$]=Q.decrypt(X)}catch(C){if(C instanceof N)C.column={model:q.name,field:$},C.message=`Could not decrypt ${q.name}.${$}: ${C.message}`;throw C}}}}function Xq(q,z){let J=O(q.model),Q=[];for(let Z of z){if(!P(Z))continue;let $=Z[q.as];if(Array.isArray($))Q.push(...$);else if(P($))Q.push($)}if(Q.length===0)return;if(J)$q(J,Q);for(let Z of q.folded??[])Xq(Z,Q)}function O(q){if(!S(q))return;return _(q).$schema}function R(q,z){let J=q.relations[z];return J?O(J.model):void 0}function P(q){return typeof q==="object"&&q!==null&&!Array.isArray(q)&&!(q instanceof Date)}function Cq(q){if(Array.isArray(q))return"an array";if(q instanceof Date)return"a Date";return`a ${typeof q}`}
3
- export{i as sh,S as th,_ as uh,x as vh,b as wh,Y as xh,U as yh,N as zh,T as Ah,Mq as Bh,c as Ch,Nq as Dh,Vq as Eh,Lq as Fh,Yq as Gh,$q as Hh,Xq as Ih};
2
+ import{Di as g,Ei as m,Yi as k}from"./chunk-ap3g6rbw.js";import{hk as p}from"./chunk-6gwxvmjv.js";import{Fk as n}from"./chunk-hxn0s3zh.js";var b={};n(b,{registeredNames:()=>x,register:()=>i,has:()=>S,get:()=>_,clearRegistry:()=>a});var M=new Map;function i(q,z){M.set(q,z)}function S(q){return M.has(q)}function _(q){let z=M.get(q);if(z===void 0)throw new k(q,[...M.keys()]);return z}function x(){return[...M.keys()]}function a(){M.clear()}import{createCipheriv as r,createDecipheriv as e,randomBytes as qq}from"crypto";class Y{static token="encrypter";keys=new Map;currentId;constructor(q={}){for(let[z,J]of Object.entries(q.keys??{})){if(!u.test(z))throw new U(`Encryption key id "${z}" is not valid. Use 1-32 letters, digits, "_" or "-": the id is written into every encrypted value.`);this.keys.set(z,zq(z,J))}if(q.current!==void 0){if(!this.keys.has(q.current))throw new U(`encryption.current is "${q.current}", but encryption.keys has no key by that id (${I(this.keys)}).`);this.currentId=q.current}else if(this.keys.size===1)this.currentId=[...this.keys.keys()][0];else if(this.keys.size>1)throw new U(`encryption.keys has ${this.keys.size} keys (${I(this.keys)}) and no encryption.current to say which one encrypts new values.`)}get configured(){return this.currentId!==void 0}get currentKeyId(){return this.requireCurrent()}encrypt(q){if(typeof q!=="string")throw TypeError(`Encrypter.encrypt takes a string, got ${Jq(q)}. Serialise other values first (JSON.stringify).`);let z=this.requireCurrent(),J=this.keys.get(z),Q=`${j}:${z}`,Z=qq(y),$=r(E,J,Z);$.setAAD(Buffer.from(Q));let X=Buffer.concat([$.update(q,"utf8"),$.final(),$.getAuthTag()]);return`${Q}:${Z.toString("base64url")}:${X.toString("base64url")}`}decrypt(q){let z=D(q);if(!z)throw new N("malformed","The value is not an encrypted envelope.");if(!this.configured)this.requireCurrent();let J=this.keys.get(z.keyId);if(!J)throw new N("unknown_key",`The value was encrypted with key "${z.keyId}", which is not in encryption.keys (${I(this.keys)}). Keep a key configured until encryption:rotate has re-encrypted the values written with it.`);try{let Q=e(E,J,z.iv);return Q.setAAD(Buffer.from(`${j}:${z.keyId}`)),Q.setAuthTag(z.tag),Buffer.concat([Q.update(z.ciphertext),Q.final()]).toString("utf8")}catch{throw new N("invalid",`The value did not authenticate under key "${z.keyId}": it was altered, or encrypted with a different key under the same id.`)}}isEncrypted(q){return D(q)!==null}keyIdOf(q){return D(q)?.keyId??null}needsReencryption(q){return this.keyIdOf(q)!==this.requireCurrent()}requireCurrent(){if(this.currentId===void 0)throw new U("No encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as `encryption` in your Kernel's config. Generate a key with `openssl rand -base64 32`.");return this.currentId}}class U extends Error{constructor(q){super(q);this.name="EncryptionKeyError"}}class N extends Error{reason;column;constructor(q,z){super(z);this.reason=q;this.name="DecryptionError"}}var j="v1",E="aes-256-gcm",f=32,y=12,A=16,u=/^[A-Za-z0-9_-]{1,32}$/,v=/^[A-Za-z0-9_-]+$/;function zq(q,z){if(typeof z!=="string"||z.trim()==="")throw new U(`Encryption key "${q}" is empty. Is the environment variable it reads set?`);let J=z.trim().replace(/^base64:/,""),Q=/^[A-Za-z0-9+/=_-]+$/.test(J)?Buffer.from(J,"base64"):Buffer.alloc(0);if(Q.length!==f)throw new U(`Encryption key "${q}" is not ${f} bytes of base64 (it decodes to ${Q.length}). Generate one with \`openssl rand -base64 32\`.`);return Q}function D(q){if(typeof q!=="string")return null;let z=q.split(":");if(z.length!==4||z[0]!==j)return null;let[,J,Q,Z]=z;if(!u.test(J)||!v.test(Q)||!v.test(Z))return null;let $=Buffer.from(Q,"base64url"),X=Buffer.from(Z,"base64url");if($.length!==y||X.length<A)return null;return{keyId:J,iv:$,ciphertext:X.subarray(0,X.length-A),tag:X.subarray(X.length-A)}}function I(q){return q.size===0?"none configured":[...q.keys()].map((z)=>`"${z}"`).join(", ")}function Jq(q){return q===null?"null":Array.isArray(q)?"an array":`a ${typeof q}`}var h=new WeakMap;function T(q){let z=h.get(q);if(z===void 0)z=Object.values(q.fields).filter((J)=>J.encrypted===!0).map((J)=>J.name),h.set(q,z);return z}function Mq(){let q=new Set,z=[];for(let J of x()){let Q=O(J);if(!Q||q.has(Q.name))continue;q.add(Q.name);for(let Z of T(Q))z.push(`${Q.name}.${Z}`)}return z}function c(){let q=p();if(!q.bound(Y))throw new U("Encrypted columns need an Encrypter, and none is bound in this application. A booted Kernel binds one from the `encryption` config slice; a hand-built Application can bind its own: `application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.");return q.make(Y)}var l=Symbol("gemi.orm.encryptedColumnsRaw");function Nq(q){return{...q,[l]:!0}}function Vq(q){return typeof q==="object"&&q!==null&&q[l]===!0}function Lq(q,z,J){if(!P(J))return;let Q={model:q.name,operation:z};d(q,J,Q,0);for(let Z of["by","_min","_max","_avg","_sum"])if(J[Z]!==void 0)o(q,J[Z],Z,Q);if(J.having!==void 0)B(q,J.having,Q)}var w=64;function d(q,z,J,Q){if(Q>w)return;if(z.where!==void 0)W(q,z.where,"where",J,Q);if(z.cursor!==void 0)W(q,z.cursor,"cursor",J,Q);if(z.orderBy!==void 0)K(q,z.orderBy,J,Q);if(z.distinct!==void 0)o(q,z.distinct,"distinct",J);for(let Z of[z.include,z.select]){if(!P(Z))continue;for(let[$,X]of Object.entries(Z)){if(!P(X))continue;if($==="_count"){if(!P(X.select))continue;for(let[G,F]of Object.entries(X.select)){let H=R(q,G);if(H&&P(F)&&F.where!==void 0)W(H,F.where,"where",J,Q+1)}continue}let C=R(q,$);if(C)d(C,X,J,Q+1)}}}var Qq=["some","every","none","is","isNot"];function W(q,z,J,Q,Z){if(Z>w)return;if(Array.isArray(z)){for(let $ of z)W(q,$,J,Q,Z);return}if(!P(z))return;for(let[$,X]of Object.entries(z)){if(X===void 0)continue;if($==="AND"||$==="OR"||$==="NOT"){W(q,X,J,Q,Z);continue}let C=q.fields[$];if(C){if(C.encrypted===!0&&!t(X))L(q,$,J,Q);continue}let G=R(q,$);if(G){if(!P(X))continue;let F=Object.keys(X).filter((H)=>Qq.includes(H));if(F.length>0)for(let H of F)W(G,X[H],J,Q,Z+1);else W(G,X,J,Q,Z+1);continue}if(P(X)){for(let F of Object.keys(X))if(q.fields[F]?.encrypted===!0)L(q,F,J,Q)}}}function K(q,z,J,Q){if(Q>w)return;if(Array.isArray(z)){for(let Z of z)K(q,Z,J,Q);return}if(!P(z))return;for(let[Z,$]of Object.entries(z)){if(q.fields[Z]?.encrypted===!0)L(q,Z,"orderBy",J);let X=R(q,Z);if(X&&P($)&&!("_count"in $))K(X,$,J,Q+1)}}function o(q,z,J,Q){let Z=typeof z==="string"?[z]:Array.isArray(z)?z.filter(($)=>typeof $==="string"):P(z)?Object.keys(z).filter(($)=>z[$]):[];for(let $ of Z)if(q.fields[$]?.encrypted===!0)L(q,$,J,Q)}function B(q,z,J){if(Array.isArray(z)){for(let Q of z)B(q,Q,J);return}if(!P(z))return;for(let[Q,Z]of Object.entries(z)){if(Q==="AND"||Q==="OR"||Q==="NOT"){B(q,Z,J);continue}if(q.fields[Q]?.encrypted===!0&&!t(Z))L(q,Q,"having",J)}}function t(q){if(q===null)return!0;if(!P(q))return!1;let z=Object.entries(q).filter(([,J])=>J!==void 0);return z.length>0&&z.every(([J,Q])=>(J==="equals"||J==="not")&&Q===null)}function L(q,z,J,Q){throw new m(J,Q.model,Q.operation,`${q.name}.${z} is an encrypted column: each write stores a different random ciphertext, so the database cannot compare, sort or group by it. Only null checks work on it ({ ${z}: null } or { ${z}: { not: null } }). To look a row up by a secret, store a keyed hash of it in a separate column and filter on that.`)}function Yq(q,z,J){let Q=T(q);if(Q.length===0||!P(J))return J;let Z={model:q.name,operation:z},$,X=(F)=>($??=c()).encrypt(F),C=J,G=(F,H)=>{if(H===C[F])return;if(C===J)C={...J};C[F]=H};switch(z){case"create":case"update":case"updateMany":G("data",V(Q,J.data,X,Z));break;case"createMany":G("data",Array.isArray(J.data)?Zq(J.data,(F)=>V(Q,F,X,Z)):V(Q,J.data,X,Z));break;case"upsert":G("create",V(Q,J.create,X,Z)),G("update",V(Q,J.update,X,Z));break}return C}function V(q,z,J,Q){if(!P(z))return z;let Z;for(let $ of q){if(!($ in z))continue;let X=z[$],C=s($,X,J,Q);if(C!==X)(Z??={...z})[$]=C}return Z??z}function s(q,z,J,Q){if(z===void 0||z===null)return z;if(typeof z==="string")return J(z);if(P(z)&&Object.keys(z).length===1&&"set"in z){let Z=z.set;return Z===null||Z===void 0?z:{set:s(q,Z,J,Q)}}throw new g("data",Q.model,Q.operation,`${Q.model}.${q} is an encrypted column and takes a string or null (or { set: string | null }); got ${Cq(z)}.`)}function Zq(q,z){let J;return q.forEach((Q,Z)=>{let $=z(Q);if($!==Q)(J??=[...q])[Z]=$}),J??q}function $q(q,z){let J=T(q);if(J.length===0||z.length===0)return;let Q;for(let Z of z){if(!P(Z))continue;for(let $ of J){let X=Z[$];if(typeof X!=="string")continue;Q??=c();try{Z[$]=Q.decrypt(X)}catch(C){if(C instanceof N)C.column={model:q.name,field:$},C.message=`Could not decrypt ${q.name}.${$}: ${C.message}`;throw C}}}}function Xq(q,z){let J=O(q.model),Q=[];for(let Z of z){if(!P(Z))continue;let $=Z[q.as];if(Array.isArray($))Q.push(...$);else if(P($))Q.push($)}if(Q.length===0)return;if(J)$q(J,Q);for(let Z of q.folded??[])Xq(Z,Q)}function O(q){if(!S(q))return;return _(q).$schema}function R(q,z){let J=q.relations[z];return J?O(J.model):void 0}function P(q){return typeof q==="object"&&q!==null&&!Array.isArray(q)&&!(q instanceof Date)}function Cq(q){if(Array.isArray(q))return"an array";if(q instanceof Date)return"a Date";return`a ${typeof q}`}
3
+ export{i as li,S as mi,_ as ni,x as oi,b as pi,Y as qi,U as ri,N as si,T as ti,Mq as ui,c as vi,Nq as wi,Vq as xi,Lq as yi,Yq as zi,$q as Ai,Xq as Bi};
4
4
 
5
- //# debugId=F5B24005ADDA605864756E2164756E21
5
+ //# debugId=9CCF9F247C0EA28064756E2164756E21
@@ -7,6 +7,6 @@
7
7
  "import { app } from \"../foundation/app\";\nimport {\n DecryptionError,\n Encrypter,\n EncryptionKeyError,\n} from \"../services/encryption/Encrypter\";\nimport { InvalidArgumentError, UnsupportedByDesignError } from \"./errors\";\nimport * as registry from \"./registry\";\nimport type { ModelSchema } from \"./schema\";\n\n/**\n * Encrypted columns: a `String` field marked `/// @gemi.encrypted` in the\n * Prisma schema is stored as an `Encrypter` envelope and read back as the\n * plaintext.\n *\n * Applied in `Model.$exec`, per model, at the two places a value crosses the\n * boundary:\n *\n * - **Writes** encrypt the model's *own* columns in `data` (and an upsert's\n * `create` / `update`). A nested write into a related model is not touched\n * here: every nested write runs through the related model's own `$exec`,\n * which encrypts its own columns, so encrypting it here as well would\n * encrypt it twice.\n * - **Reads** decrypt the model's own rows after shaping. A batched `include`\n * comes back through the child's `$exec` and is already decrypted; a folded\n * (lateral) one never enters it, so the parent decrypts those rows on the\n * child's behalf (`decryptFolded`) — the same split `redactFolded` handles\n * for policies.\n *\n * The schema, not the model class, says which columns are encrypted. That is\n * deliberate: a column that is encrypted when written through `FigmaConnection`\n * and plaintext when written through `FigmaConnectionModel` is not encrypted\n * at rest. The generated base, the subclass and every `Model.on(...)` variant\n * share one `$schema`, so none of them can write the column in the clear.\n *\n * A filter, sort or grouping on an encrypted column is refused: every write\n * stores a different random ciphertext, so the database cannot compare it to\n * anything. A null check is the exception, because a NULL column is stored as\n * NULL.\n */\n\nconst fieldsBySchema = new WeakMap<ModelSchema, readonly string[]>();\n\n/** The schema's encrypted fields, in declaration order. Empty for most models. */\nexport function encryptedFields(schema: ModelSchema): readonly string[] {\n let fields = fieldsBySchema.get(schema);\n if (fields === undefined) {\n fields = Object.values(schema.fields)\n .filter((field) => field.encrypted === true)\n .map((field) => field.name);\n fieldsBySchema.set(schema, fields);\n }\n return fields;\n}\n\n/** `Model.field` for every encrypted column of every registered model. */\nexport function encryptedColumnsInRegistry(): string[] {\n const seen = new Set<string>();\n const columns: string[] = [];\n for (const name of registry.registeredNames()) {\n const schema = schemaOf(name);\n if (!schema || seen.has(schema.name)) continue;\n seen.add(schema.name);\n for (const field of encryptedFields(schema)) columns.push(`${schema.name}.${field}`);\n }\n return columns;\n}\n\n/**\n * The application's `Encrypter`. An application booted without the\n * framework's providers (a test harness that binds only the database) gets a\n * typed error naming the fix rather than a container error.\n */\nexport function currentEncrypter(): Encrypter {\n const application = app();\n if (!application.bound(Encrypter)) {\n throw new EncryptionKeyError(\n \"Encrypted columns need an Encrypter, and none is bound in this \" +\n \"application. A booted Kernel binds one from the `encryption` config \" +\n \"slice; a hand-built Application can bind its own: \" +\n \"`application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.\",\n );\n }\n return application.make(Encrypter);\n}\n\n// --- the internal raw mode ---------------------------------------------------\n\n/**\n * Marks an `$exec` call as reading and writing encrypted columns *as stored*:\n * no decryption of results, no encryption of `data`, and filters on encrypted\n * columns allowed (compared against the envelope). Used by `encryption:rotate`\n * to compare-and-swap one envelope for another. A module-private symbol, like\n * the other `$exec` markers, so an application cannot set it.\n */\nconst RAW = Symbol(\"gemi.orm.encryptedColumnsRaw\");\n\nexport function markEncryptionRaw<T extends object>(options: T): T {\n return { ...options, [RAW]: true };\n}\n\nexport function isEncryptionRaw(options: unknown): boolean {\n return (\n typeof options === \"object\" &&\n options !== null &&\n (options as Record<symbol, unknown>)[RAW] === true\n );\n}\n\n// --- refusing filters --------------------------------------------------------\n\ninterface Origin {\n model: string;\n operation: string;\n}\n\n/**\n * Refuses any argument that would make the database compare, sort or group an\n * encrypted column: `where` (including relation filters into other models),\n * `orderBy`, `distinct`, `cursor`, `groupBy`'s `by` and `having`, the\n * `_min` / `_max` aggregates, and the same arguments nested inside an\n * `include` or `select`.\n *\n * Walked whether or not this model has encrypted columns, because a relation\n * filter or an include reaches other models'.\n */\nexport function assertNoEncryptedFilters(schema: ModelSchema, op: string, args: unknown): void {\n if (!isObject(args)) return;\n const origin: Origin = { model: schema.name, operation: op };\n readArgs(schema, args, origin, 0);\n for (const key of [\"by\", \"_min\", \"_max\", \"_avg\", \"_sum\"]) {\n if (args[key] !== undefined) fieldList(schema, args[key], key, origin);\n }\n if (args.having !== undefined) having(schema, args.having, origin);\n}\n\n/** Generous: relation depth is bounded by `MAX_RELATION_DEPTH` long before this. */\nconst MAX_WALK_DEPTH = 64;\n\nfunction readArgs(schema: ModelSchema, args: Record<string, any>, origin: Origin, depth: number) {\n if (depth > MAX_WALK_DEPTH) return;\n if (args.where !== undefined) where(schema, args.where, \"where\", origin, depth);\n if (args.cursor !== undefined) where(schema, args.cursor, \"cursor\", origin, depth);\n if (args.orderBy !== undefined) orderBy(schema, args.orderBy, origin, depth);\n if (args.distinct !== undefined) fieldList(schema, args.distinct, \"distinct\", origin);\n\n for (const projection of [args.include, args.select]) {\n if (!isObject(projection)) continue;\n for (const [key, value] of Object.entries(projection)) {\n if (!isObject(value)) continue;\n if (key === \"_count\") {\n if (!isObject(value.select)) continue;\n for (const [name, count] of Object.entries(value.select)) {\n const target = relationTarget(schema, name);\n if (target && isObject(count) && count.where !== undefined) {\n where(target, count.where, \"where\", origin, depth + 1);\n }\n }\n continue;\n }\n const target = relationTarget(schema, key);\n if (target) readArgs(target, value, origin, depth + 1);\n }\n }\n}\n\nconst RELATION_FILTERS = [\"some\", \"every\", \"none\", \"is\", \"isNot\"];\n\nfunction where(\n schema: ModelSchema,\n node: unknown,\n argument: string,\n origin: Origin,\n depth: number,\n): void {\n if (depth > MAX_WALK_DEPTH) return;\n if (Array.isArray(node)) {\n for (const item of node) where(schema, item, argument, origin, depth);\n return;\n }\n if (!isObject(node)) return;\n\n for (const [key, value] of Object.entries(node)) {\n if (value === undefined) continue;\n\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n where(schema, value, argument, origin, depth);\n continue;\n }\n\n const field = schema.fields[key];\n if (field) {\n if (field.encrypted === true && !isNullCheck(value)) {\n refuse(schema, key, argument, origin);\n }\n continue;\n }\n\n const target = relationTarget(schema, key);\n if (target) {\n if (!isObject(value)) continue;\n const filters = Object.keys(value).filter((name) => RELATION_FILTERS.includes(name));\n if (filters.length > 0) {\n for (const name of filters) where(target, value[name], argument, origin, depth + 1);\n } else {\n where(target, value, argument, origin, depth + 1);\n }\n continue;\n }\n\n // A compound unique key — `provider_providerId: { provider, providerId }`.\n if (isObject(value)) {\n for (const name of Object.keys(value)) {\n if (schema.fields[name]?.encrypted === true) refuse(schema, name, argument, origin);\n }\n }\n }\n}\n\nfunction orderBy(schema: ModelSchema, node: unknown, origin: Origin, depth: number): void {\n if (depth > MAX_WALK_DEPTH) return;\n if (Array.isArray(node)) {\n for (const item of node) orderBy(schema, item, origin, depth);\n return;\n }\n if (!isObject(node)) return;\n for (const [key, value] of Object.entries(node)) {\n if (schema.fields[key]?.encrypted === true) refuse(schema, key, \"orderBy\", origin);\n const target = relationTarget(schema, key);\n if (target && isObject(value) && !(\"_count\" in value)) {\n orderBy(target, value, origin, depth + 1);\n }\n }\n}\n\n/** `distinct`, `by`, and the `_min` / `_max` / `_avg` / `_sum` selections. */\nfunction fieldList(schema: ModelSchema, node: unknown, argument: string, origin: Origin): void {\n const names =\n typeof node === \"string\"\n ? [node]\n : Array.isArray(node)\n ? node.filter((name): name is string => typeof name === \"string\")\n : isObject(node)\n ? Object.keys(node).filter((name) => node[name])\n : [];\n for (const name of names) {\n if (schema.fields[name]?.encrypted === true) refuse(schema, name, argument, origin);\n }\n}\n\nfunction having(schema: ModelSchema, node: unknown, origin: Origin): void {\n if (Array.isArray(node)) {\n for (const item of node) having(schema, item, origin);\n return;\n }\n if (!isObject(node)) return;\n for (const [key, value] of Object.entries(node)) {\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n having(schema, value, origin);\n continue;\n }\n if (schema.fields[key]?.encrypted === true && !isNullCheck(value)) {\n refuse(schema, key, \"having\", origin);\n }\n }\n}\n\n/** `null`, `{ equals: null }`, `{ not: null }` — the only comparisons a ciphertext supports. */\nfunction isNullCheck(value: unknown): boolean {\n if (value === null) return true;\n if (!isObject(value)) return false;\n const entries = Object.entries(value).filter(([, operand]) => operand !== undefined);\n return (\n entries.length > 0 &&\n entries.every(([operator, operand]) => (operator === \"equals\" || operator === \"not\") && operand === null)\n );\n}\n\nfunction refuse(schema: ModelSchema, field: string, argument: string, origin: Origin): never {\n throw new UnsupportedByDesignError(\n argument,\n origin.model,\n origin.operation,\n `${schema.name}.${field} is an encrypted column: each write stores a ` +\n `different random ciphertext, so the database cannot compare, sort or ` +\n `group by it. Only null checks work on it ({ ${field}: null } or ` +\n `{ ${field}: { not: null } }). To look a row up by a secret, store a ` +\n `keyed hash of it in a separate column and filter on that.`,\n );\n}\n\n// --- writes ------------------------------------------------------------------\n\n/**\n * `args` with this model's encrypted columns encrypted, or `args` itself when\n * there is nothing to encrypt. Never mutates the caller's objects: the same\n * `data` may be reused for a second call.\n *\n * Only `data` (and an upsert's `create` / `update`) at this level. Nested\n * relation writes are left as they are; see the note at the top of the file.\n */\nexport function encryptWriteArgs(schema: ModelSchema, op: string, args: any): any {\n const fields = encryptedFields(schema);\n if (fields.length === 0 || !isObject(args)) return args;\n\n const origin: Origin = { model: schema.name, operation: op };\n let encrypter: Encrypter | undefined;\n const encrypt = (value: string) => (encrypter ??= currentEncrypter()).encrypt(value);\n\n let next = args;\n const replace = (key: string, value: unknown) => {\n if (value === next[key]) return;\n if (next === args) next = { ...args };\n next[key] = value;\n };\n\n switch (op) {\n case \"create\":\n case \"update\":\n case \"updateMany\":\n replace(\"data\", encryptData(fields, args.data, encrypt, origin));\n break;\n case \"createMany\":\n replace(\n \"data\",\n Array.isArray(args.data)\n ? mapIfChanged(args.data, (row) => encryptData(fields, row, encrypt, origin))\n : encryptData(fields, args.data, encrypt, origin),\n );\n break;\n case \"upsert\":\n replace(\"create\", encryptData(fields, args.create, encrypt, origin));\n replace(\"update\", encryptData(fields, args.update, encrypt, origin));\n break;\n }\n return next;\n}\n\nfunction encryptData(\n fields: readonly string[],\n data: unknown,\n encrypt: (value: string) => string,\n origin: Origin,\n): unknown {\n if (!isObject(data)) return data;\n let copy: Record<string, unknown> | undefined;\n for (const name of fields) {\n if (!(name in data)) continue;\n const value = data[name];\n const next = encryptValue(name, value, encrypt, origin);\n if (next !== value) (copy ??= { ...data })[name] = next;\n }\n return copy ?? data;\n}\n\nfunction encryptValue(\n field: string,\n value: unknown,\n encrypt: (value: string) => string,\n origin: Origin,\n): unknown {\n if (value === undefined || value === null) return value;\n if (typeof value === \"string\") return encrypt(value);\n // Prisma's `{ set: value }` spelling of a scalar update.\n if (isObject(value) && Object.keys(value).length === 1 && \"set\" in value) {\n const set = value.set;\n return set === null || set === undefined ? value : { set: encryptValue(field, set, encrypt, origin) };\n }\n throw new InvalidArgumentError(\n \"data\",\n origin.model,\n origin.operation,\n `${origin.model}.${field} is an encrypted column and takes a string or ` +\n `null (or { set: string | null }); got ${describe(value)}.`,\n );\n}\n\nfunction mapIfChanged<T>(items: T[], fn: (item: T) => T): T[] {\n let copy: T[] | undefined;\n items.forEach((item, index) => {\n const next = fn(item);\n if (next !== item) (copy ??= [...items])[index] = next;\n });\n return copy ?? items;\n}\n\n// --- reads -------------------------------------------------------------------\n\n/**\n * Decrypts this model's encrypted columns on `rows`, in place. A value that\n * does not decrypt raises `DecryptionError` naming the column — a ciphertext\n * is never handed back as if it were the value.\n */\nexport function decryptRows(schema: ModelSchema, rows: readonly unknown[]): void {\n const fields = encryptedFields(schema);\n if (fields.length === 0 || rows.length === 0) return;\n\n let encrypter: Encrypter | undefined;\n for (const row of rows) {\n if (!isObject(row)) continue;\n for (const field of fields) {\n const value = row[field];\n if (typeof value !== \"string\") continue;\n encrypter ??= currentEncrypter();\n try {\n row[field] = encrypter.decrypt(value);\n } catch (error) {\n if (error instanceof DecryptionError) {\n error.column = { model: schema.name, field };\n error.message = `Could not decrypt ${schema.name}.${field}: ${error.message}`;\n }\n throw error;\n }\n }\n }\n}\n\n/**\n * Decrypts the rows a strategy folded into the parent's statement, which never\n * passed through their own model's `$exec`. Recursive, because the fold is.\n */\nexport function decryptFolded(\n relation: { as: string; model: string; folded?: readonly { as: string; model: string; folded?: readonly unknown[] }[] },\n parents: readonly unknown[],\n): void {\n const schema = schemaOf(relation.model);\n const rows: unknown[] = [];\n for (const parent of parents) {\n if (!isObject(parent)) continue;\n const value = parent[relation.as];\n if (Array.isArray(value)) rows.push(...value);\n else if (isObject(value)) rows.push(value);\n }\n if (rows.length === 0) return;\n if (schema) decryptRows(schema, rows);\n for (const child of relation.folded ?? []) {\n decryptFolded(child as Parameters<typeof decryptFolded>[0], rows);\n }\n}\n\n// --- helpers -----------------------------------------------------------------\n\nfunction schemaOf(model: string): ModelSchema | undefined {\n if (!registry.has(model)) return undefined;\n return registry.get<{ $schema?: ModelSchema }>(model).$schema;\n}\n\nfunction relationTarget(schema: ModelSchema, name: string): ModelSchema | undefined {\n const relation = schema.relations[name];\n return relation ? schemaOf(relation.model) : undefined;\n}\n\nfunction isObject(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof Date);\n}\n\nfunction describe(value: unknown): string {\n if (Array.isArray(value)) return \"an array\";\n if (value instanceof Date) return \"a Date\";\n return `a ${typeof value}`;\n}\n"
8
8
  ],
9
9
  "mappings": ";oPAeA,FAAM,JAAS,IAAI,IAEZ,SAAS,CAAQ,CAAC,EAAc,EAAsB,CAC3D,EAAO,IAAI,EAAM,CAAK,EAGjB,SAAS,CAAG,CAAC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,CAAE,MAAO,EAAO,KAAM,OAAM,EAC3C,EAAM,QAAU,qBAAqB,EAAO,QAAQ,MAAU,EAAM,UAEtE,MAAM,KAUP,SAAS,EAAa,CAC3B,EACA,EACM,CACN,IAAM,EAAS,EAAS,EAAS,KAAK,EAChC,EAAkB,CAAC,EACzB,QAAW,KAAU,EAAS,CAC5B,GAAI,CAAC,EAAS,CAAM,EAAG,SACvB,IAAM,EAAQ,EAAO,EAAS,IAC9B,GAAI,MAAM,QAAQ,CAAK,EAAG,EAAK,KAAK,GAAG,CAAK,EACvC,QAAI,EAAS,CAAK,EAAG,EAAK,KAAK,CAAK,EAE3C,GAAI,EAAK,SAAW,EAAG,OACvB,GAAI,EAAQ,GAAY,EAAQ,CAAI,EACpC,QAAW,KAAS,EAAS,QAAU,CAAC,EACtC,GAAc,EAA8C,CAAI,EAMpE,SAAS,CAAQ,CAAC,EAAwC,CACxD,GAAI,CAAU,EAAI,CAAK,EAAG,OAC1B,OAAgB,EAA+B,CAAK,EAAE,QAGxD,SAAS,CAAc,CAAC,EAAqB,EAAuC,CAClF,IAAM,EAAW,EAAO,UAAU,GAClC,OAAO,EAAW,EAAS,EAAS,KAAK,EAAI,OAG/C,SAAS,CAAQ,CAAC,EAA8C,CAC9D,OAAO,OAAO,IAAU,UAAY,IAAU,MAAQ,CAAC,MAAM,QAAQ,CAAK,GAAK,EAAE,aAAiB,MAGpG,SAAS,EAAQ,CAAC,EAAwB,CACxC,GAAI,MAAM,QAAQ,CAAK,EAAG,MAAO,WACjC,GAAI,aAAiB,KAAM,MAAO,SAClC,MAAO,KAAK,OAAO",
10
- "debugId": "F5B24005ADDA605864756E2164756E21",
10
+ "debugId": "9CCF9F247C0EA28064756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -2,6 +2,6 @@
2
2
  import{existsSync as $,readdirSync as B}from"fs";import{join as Y,relative as G}from"path";function J(K,Q=[]){let U=[],X=(H)=>{let z=G(K,H).split("\\").join("/");return Q.some((q)=>z===q||z.startsWith(`${q}/`))},V=(H)=>{for(let z of B(H,{withFileTypes:!0}).sort((q,Z)=>q.name<Z.name?-1:q.name>Z.name?1:0)){let q=Y(H,z.name);if(X(q))continue;if(z.isDirectory()){if(z.name.startsWith(".")||z.name==="node_modules")continue;if($(Y(q,"package.json")))continue;V(q);continue}if(!z.name.endsWith(".ts")&&!z.name.endsWith(".tsx"))continue;if(z.name.endsWith(".d.ts"))continue;if(/\.(test|test-d|spec|bench)\.tsx?$/.test(z.name))continue;U.push(q)}};if(!$(K))return U;return V(K),U}class A extends Error{constructor(K,Q){super(K,Q);this.name="DiscoveryError"}}async function W(K,Q,U=[],X){let V=new Set;for(let H of J(K,U)){let z;try{z=await import(H)}catch(q){throw new A(`${H} could not be imported, so the classes in it could not be discovered:
3
3
  ${q.message}
4
4
  List the classes explicitly in the config slice for this directory to skip the walk.`,{cause:q})}for(let q of Object.values(z)){if(typeof q==="function"&&q!==Q&&Object.prototype.isPrototypeOf.call(Q,q)){V.add(q);continue}X?.(q,H)}}return[...V]}function F(){return Y(process.cwd(),process.env.GEMI_PROJECT_DIR??"")}
5
- export{J as Dj,A as Ej,W as Fj,F as Gj};
5
+ export{J as xk,A as yk,W as zk,F as Ak};
6
6
 
7
- //# debugId=2B3374A47261944D64756E2164756E21
7
+ //# debugId=DEA8E7127EC132ED64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import { existsSync, readdirSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Finding the classes an application declared and never imported — the walk\n * #322 and #323 both end at.\n *\n * ### Why it has to run the files\n *\n * A job that is written and not listed does not fail; it disappears.\n * `QueueManager.run` looks a dispatched name up in the map its config built and\n * drops what is not there, so the dispatch is simply lost. A cron drifts worse:\n * nothing is waiting on a tick, so a job that never fires reports nothing to\n * anyone. What both come down to is that `app/config/queue.ts` naming every\n * `Job` subclass is the *only* thing putting those classes in the module graph —\n * the list and the directory are two spellings of one set, kept in step by hand.\n *\n * The way out of that is to read the directory, and there is no static read that\n * will do: the class does not exist until its module has run. So **every file\n * walked here is imported**, and a file that *does something* when imported does\n * it here — at boot, in production, on every start. `gemi check models` makes\n * the same trade for the same reason and pays it once per CI run; a caller of\n * this pays it once per process.\n *\n * ### What that asks of a caller\n *\n * **Point it at a directory of class declarations, not at `app/`.** The skip\n * rules on `sourceFiles` drop what certainly is not one — tests, benchmarks,\n * `.d.ts`, vendored packages — and nothing else. Widening the guesses is how a\n * discovery pass ends up quietly covering less than the directory holds, which\n * is the same silence in a new place.\n *\n * **Let a broken file stop the boot.** `discoverClasses` rethrows an import\n * failure naming the file rather than dropping it and carrying on, for the same\n * reason: four classes found out of five looks exactly like five out of five.\n *\n * **Leave a way out.** Discovery is what should happen when an app said\n * nothing. An app that lists its classes explicitly must not reach this file at\n * all — that is the escape hatch for a directory holding something this cannot\n * import, and it is the sentence an error from here should point at.\n *\n * ### One more thing worth knowing\n *\n * This imports by absolute path, while the application imports the same files\n * through the `@/app/*` alias. Bun keys its module registry by the *resolved*\n * path, so those two specifiers land on one module: a job already reached from\n * a controller is not evaluated a second time here, and the class object is the\n * same one. `gemi build` leaves that true in production — `packages: \"external\"`\n * keeps the app's own code out of `dist/server/server.mjs` and resolves it from\n * source at runtime, exactly as `gemi dev` does.\n *\n * Nothing here depends on that holding, and deliberately: `QueueManager` and the\n * `Scheduler`'s cross-reload registry are both keyed by name rather than by\n * class identity, so a build that did inline the app's modules would produce a\n * duplicate class object and still register the right job. Worth knowing before\n * writing a registry keyed the other way.\n */\n\n/**\n * The files under `dir` that could declare a class.\n *\n * Everything underneath it, because apps do group classes into folders, minus\n * what cannot be one. Each of these is going to be *imported*, so the exclusions\n * are about what is certainly not source rather than about what is probably not:\n *\n * - **Declaration files.** `.d.ts` has no runtime module behind it.\n * - **Tests, type tests and benchmarks**, by the suffix a runner already\n * recognises.\n * - **Dot-directories and `node_modules`.**\n * - **Any directory holding a `package.json`.** That is a package that happens\n * to live here — a vendored client, a generated SDK — not this app's source,\n * and importing its entry point runs somebody else's module graph. The\n * template has two under `app/models`.\n *\n * `ignore` is the escape hatch for the rest: a path prefix, relative to `dir`,\n * naming a file or a directory of adjacent code that runs something on import.\n * Nothing is ignored by default.\n *\n * The order is the same on every run over the same tree, which matters because\n * the caller is going to import in it: entries are sorted per directory before\n * recursing, and `readdirSync` order is the filesystem's rather than\n * alphabetical — a tree written `A.ts` then `B.ts` reads back `B.ts` first on\n * the machines this was tested on. Sorting per directory rather than sorting the\n * finished list is deliberate: for a tree holding both `a.ts` and `a/b.ts`, this\n * emits `a/b.ts` first, because the directory sorts before the file.\n *\n * A directory that does not exist yields an empty list rather than throwing.\n * \"The app has no jobs yet\" is an ordinary state and not this function's to\n * complain about — but it is indistinguishable from \"the app's source did not\n * ship\", so a caller that boots on the answer owes the reader a word about which\n * one it got.\n */\nexport function sourceFiles(dir: string, ignore: string[] = []): string[] {\n const out: string[] = [];\n\n const ignored = (path: string) => {\n const rel = relative(dir, path).split(\"\\\\\").join(\"/\");\n return ignore.some(\n (pattern) => rel === pattern || rel.startsWith(`${pattern}/`),\n );\n };\n\n const walk = (current: string) => {\n for (const entry of readdirSync(current, { withFileTypes: true }).sort(\n (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),\n )) {\n const path = join(current, entry.name);\n if (ignored(path)) continue;\n\n if (entry.isDirectory()) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\")\n continue;\n if (existsSync(join(path, \"package.json\"))) continue;\n walk(path);\n continue;\n }\n\n if (!entry.name.endsWith(\".ts\") && !entry.name.endsWith(\".tsx\")) continue;\n if (entry.name.endsWith(\".d.ts\")) continue;\n if (/\\.(test|test-d|spec|bench)\\.tsx?$/.test(entry.name)) continue;\n\n out.push(path);\n }\n };\n\n if (!existsSync(dir)) return out;\n\n walk(dir);\n return out;\n}\n\n/**\n * A class, as much of one as this file can name. `abstract` so that a base an\n * app never instantiates directly is a legal argument.\n */\ntype ClassLike = abstract new (...args: never[]) => unknown;\n\n/**\n * A file that would not import, reported with the file that would not import.\n *\n * Separate from a bare rethrow because the stack of a failed dynamic import\n * names the module that failed to *resolve*, several frames deep, and says\n * nothing about the walk that asked for it — so the reader learns that some\n * `?raw` specifier is unresolvable without learning that discovery is what\n * imported it, or that listing the classes explicitly is how they get their boot\n * back.\n */\nexport class DiscoveryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"DiscoveryError\";\n }\n}\n\n/**\n * Every exported class under `dir` whose prototype chain reaches `base`.\n *\n * `base` is a parameter rather than an import so that this file names no\n * service and stays cheap to depend on — `bin/check-models.ts` uses the walker\n * above and is bundled into `dist/bin/gemi.js`, which is not somewhere gemi's\n * service layer should end up. It is also what lets a test hand in a base class\n * of its own instead of standing up a project that can resolve `gemi/services`.\n *\n * `base` itself is never returned. A directory whose files import their base\n * from a sibling — the shape an app reaches for when several jobs share a gate —\n * re-exports it as often as not, and a framework that scheduled the abstract\n * base along with its subclasses would be running a job nobody wrote.\n *\n * A class is returned once no matter how many exports name it. A barrel in the\n * directory re-exporting everything beside it is the ordinary case, and it makes\n * every class reachable twice.\n *\n * The order is the walk's, and within a file the module namespace's, which the\n * language sorts by name. So the answer is the same on every run — worth having\n * where the caller is a scheduler and the alternative is a boot order that\n * depends on the filesystem.\n *\n * `onSkipped` is handed every export that did *not* match, with the file it came\n * from. Discovery's characteristic failure is a thing the author wrote and this\n * walk cannot see, and by the time an export has been discarded here the\n * information about why is gone — the caller is left holding \"four classes\"\n * where the directory holds five. A caller that can recognise its own\n * near-misses, as `discoverCommands` recognises a builder chain that was never\n * finished, uses this to say so by name instead.\n *\n * @throws DiscoveryError if a walked file cannot be imported. Not a skip: a file\n * that will not load is a class the caller was going to be told about and now is\n * not, which is the failure discovery exists to remove.\n */\nexport async function discoverClasses<T extends ClassLike>(\n dir: string,\n base: T,\n ignore: string[] = [],\n onSkipped?: (value: unknown, file: string) => void,\n): Promise<T[]> {\n const found = new Set<T>();\n\n for (const path of sourceFiles(dir, ignore)) {\n let module: Record<string, unknown>;\n\n try {\n module = (await import(path)) as Record<string, unknown>;\n } catch (error) {\n throw new DiscoveryError(\n `${path} could not be imported, so the classes in it could not be ` +\n `discovered:\\n ${(error as Error).message}\\n` +\n `List the classes explicitly in the config slice for this directory ` +\n `to skip the walk.`,\n { cause: error },\n );\n }\n\n for (const value of Object.values(module)) {\n if (\n typeof value === \"function\" &&\n value !== base &&\n Object.prototype.isPrototypeOf.call(base, value)\n ) {\n found.add(value as unknown as T);\n continue;\n }\n\n onSkipped?.(value, path);\n }\n }\n\n return [...found];\n}\n\n/**\n * The directory an app's `app/` sits in, as the running process can know it.\n *\n * `ROOT_DIR` is the obvious answer and is not available: `Server.start` awaits\n * `waitForBoot()` — every provider's `register` and `boot` — and only then\n * imports the http layer that sets it. Anything resolving paths during boot is\n * earlier than the variable it would want.\n *\n * What it can use is the same rule `httpProd` computes `ROOT_DIR` with a moment\n * later, which is why that file now calls this instead of repeating it. `gemi\n * dev` and `gemi start` both spawn the server with no `cwd`, so the process\n * inherits the CLI's, and the CLI takes `process.cwd()` for the project root\n * itself — `bun/preload.ts` reads `gemi.config` from it on the same assumption.\n *\n * `httpDev` computes a bare `process.cwd()`, so it and `httpProd` already\n * disagree whenever `GEMI_PROJECT_DIR` is set. Nothing in this repo sets it and\n * `gemi start` ignores it when locating the built entry point, so the two rules\n * are the same rule for every configuration that runs today; the divergence is\n * older than this function and wants its own fix.\n */\nexport function projectRoot(): string {\n return join(process.cwd(), process.env.GEMI_PROJECT_DIR ?? \"\");\n}\n"
6
6
  ],
7
7
  "mappings": ";AAAA,qBAAS,iBAAY,WACrB,eAAS,cAAM,aA2FR,SAAS,CAAW,CAAC,EAAa,EAAmB,CAAC,EAAa,CACxE,IAAM,EAAgB,CAAC,EAEjB,EAAU,CAAC,IAAiB,CAChC,IAAM,EAAM,EAAS,EAAK,CAAI,EAAE,MAAM,IAAI,EAAE,KAAK,GAAG,EACpD,OAAO,EAAO,KACZ,CAAC,IAAY,IAAQ,GAAW,EAAI,WAA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AAI,CAAqB,EAC/B,SAGF,IAAY,EAAO,CAAI,GAI3B,MAAO,CAAC,GAAG,CAAK,EAuBX,SAAS,CAAW,EAAW,CACpC,OAAO,EAAK,QAAQ,IAAI,EAAG,QAAQ,IAAI,kBAAoB,EAAE",
8
- "debugId": "2B3374A47261944D64756E2164756E21",
8
+ "debugId": "DEA8E7127EC132ED64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  import{constants as M}from"os";var Y=Symbol.for("gemi.server.shutdown");function Q(){let j=globalThis;return j[Y]??={shuttingDown:!1,drained:!1},j[Y]}function R(){return Q().shuttingDown}function f(){Q().shuttingDown=!0}function x(){Q().drained=!0}function W(j=process.env){let z={timeoutMs:U(j.GEMI_SHUTDOWN_TIMEOUT,20),delayMs:U(j.GEMI_SHUTDOWN_DELAY,0),providerTimeoutMs:U(j.GEMI_SHUTDOWN_PROVIDER_TIMEOUT,5)};if(z.delayMs>0&&z.delayMs>=z.timeoutMs)console.warn(`[gemi] GEMI_SHUTDOWN_DELAY (${z.delayMs/1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${z.timeoutMs/1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`);return z}function U(j,z){let B=j===void 0||j.trim()===""?NaN:Number(j);if(Number.isFinite(B)&&B>=0)return B*1000;if(j!==void 0)console.warn(`[gemi] Ignoring shutdown setting "${j}": expected a number of seconds.`);return z*1000}async function E(j){let{server:z,settings:B}=j,J=Date.now()+B.timeoutMs;f(),console.log(`[gemi] Shutting down: draining in-flight requests (up to ${B.timeoutMs/1000}s).`);let H=!0;if(z){if(B.delayMs>0)await _(Math.min(B.delayMs,J-Date.now()));let O=z.stop(),V=Promise.resolve();try{V=Promise.resolve(j.closeSockets?.()).catch(()=>{})}catch(F){console.error("[gemi] Closing the broadcast sockets failed:",F)}let X=J-Date.now(),$=j.closeSockets?Promise.race([O,Promise.all([V,y(z)])]):O;if(H=X>0?await G($,X):z.pendingRequests===0,!H)console.error(`[gemi] Shutdown grace period elapsed with ${z.pendingRequests} request(s) still in flight; abandoning them.`),z.stop(!0).catch(()=>{})}x();let P=await j.shutdownProviders({timeoutMs:B.providerTimeoutMs}),K=H&&P.failed.length===0&&P.timedOut.length===0;return console.log(`[gemi] Shutdown ${K?"complete":"finished with errors"}.`),K?0:1}function y(j){return new Promise((z)=>{let B=()=>{if(j.pendingRequests===0){z();return}setTimeout(B,50).unref?.()};B()})}async function G(j,z){if(z<=0)return!1;let B,J=await Promise.race([j.then(()=>!0,()=>!0),new Promise((H)=>{B=setTimeout(()=>H(!1),z)})]);return clearTimeout(B),J}function _(j){return new Promise((z)=>setTimeout(z,Math.max(0,j)))}function q(j){if(!R())return j;try{return j.headers.set("Connection","close"),j}catch{let z=new Response(j.body,j);return z.headers.set("Connection","close"),z}}function N(j){return async(z,B)=>{if(Q().drained)return new Response("Service Unavailable",{status:503,headers:{Connection:"close"}});return q(await j(z,B))}}var Z=Symbol.for("gemi.server.signalsInstalled"),w=1000;function D(j,z={}){let B=globalThis;if(B[Z])return;B[Z]=!0;let J=z.repeatWindowMs??w,H,P=(K)=>{if(H!==void 0){if(Date.now()-H<J)return;console.error(`[gemi] ${K} received again; exiting without waiting for the drain.`),process.exit(128+M.signals[K])}H=Date.now(),console.log(`[gemi] ${K} received.`),j().then((O)=>process.exit(O),(O)=>{console.error("[gemi] Shutdown failed:",O),process.exit(1)})};process.on("SIGTERM",P),process.on("SIGINT",P)}
3
- export{R as xj,f as yj,W as zj,E as Aj,N as Bj,D as Cj};
3
+ export{R as qk,f as rk,W as sk,E as tk,q as uk,N as vk,D as wk};
4
4
 
5
- //# debugId=6DB3F4C9F21071C964756E2164756E21
5
+ //# debugId=9A20614C89E7040A64756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../server/shutdown.ts"],
4
+ "sourcesContent": [
5
+ "import { constants } from \"node:os\";\nimport type { ShutdownReport } from \"../foundation/Application\";\nimport type { Instrumentation } from \"./types\";\n\n// On `globalThis` under a registry symbol rather than in a module variable, so\n// the flag an app's health route reads is the one the server set even when two\n// copies of this module are loaded — the built CLI bundles its own gemi (see\n// `app/App.ts`), and `bun --hot` re-evaluates every module on a reload.\nconst STATE = Symbol.for(\"gemi.server.shutdown\");\n\ntype ShutdownState = { shuttingDown: boolean; drained: boolean };\n\nfunction state(): ShutdownState {\n const global = globalThis as { [STATE]?: ShutdownState };\n global[STATE] ??= { shuttingDown: false, drained: false };\n return global[STATE];\n}\n\n/**\n * True from the moment this server process has been told to stop — before it\n * stops accepting connections — until it exits.\n *\n * gemi's built-in health route (`./health`) answers `503` while this is true,\n * and so should an app's own health route, so the platform's probe pulls the\n * instance while the in-flight requests are still draining. Every response sent in that window also carries\n * `Connection: close`, so a client that honours it opens its next request on a\n * new connection — one the load balancer can route elsewhere — instead of\n * reusing this one.\n */\nexport function isShuttingDown(): boolean {\n return state().shuttingDown;\n}\n\nexport function markShuttingDown() {\n state().shuttingDown = true;\n}\n\n/**\n * The request drain is over and the providers' `shutdown()` may be running:\n * from here on a request must not reach the app. See `serveForShutdown`.\n */\nexport function markDrained() {\n state().drained = true;\n}\n\n/** Test seam: a fresh process starts false, and so should each test. */\nexport function resetShuttingDown() {\n state().shuttingDown = false;\n state().drained = false;\n}\n\nexport type ShutdownSettings = {\n /**\n * From the signal to the end of the request drain, in milliseconds — the\n * delay below included. Requests still in flight when it runs out are\n * abandoned. `GEMI_SHUTDOWN_TIMEOUT`, in seconds; default 20. `0` means\n * \"close the listener and do not wait\": a shutdown with nothing in flight is\n * still a clean one.\n */\n timeoutMs: number;\n /**\n * How long to keep accepting new requests after `isShuttingDown()` turns\n * true, in milliseconds, so a health probe can see the `503` and the load\n * balancer stop routing here before the listener closes.\n * `GEMI_SHUTDOWN_DELAY`, in seconds; default 0.\n */\n delayMs: number;\n /**\n * The shared deadline for every provider's `shutdown()`, in milliseconds,\n * after the drain. `GEMI_SHUTDOWN_PROVIDER_TIMEOUT`, in seconds; default 5.\n * `0` skips the hooks — deliberately, so it is not reported as a failure.\n */\n providerTimeoutMs: number;\n};\n\n/**\n * 20s to drain plus 5s for providers is 25s: under the 30s that Kubernetes,\n * Azure Container Apps and ECS give by default between `SIGTERM` and `SIGKILL`,\n * with 5s left for the `gemi start` relay, the process exit and clock skew\n * between the platform's timer and ours. A platform with a shorter window\n * (Cloud Run's 10s, Fly's 5s) needs these lowered, not the other way round —\n * a drain that outlives the grace period ends in the same `SIGKILL` as no drain.\n *\n * The delay defaults to 0 because it only helps where a probe is watching, and\n * otherwise every shutdown would pay it for nothing.\n */\nexport function shutdownSettings(\n env: Record<string, string | undefined> = process.env,\n): ShutdownSettings {\n const settings = {\n timeoutMs: seconds(env.GEMI_SHUTDOWN_TIMEOUT, 20),\n delayMs: seconds(env.GEMI_SHUTDOWN_DELAY, 0),\n providerTimeoutMs: seconds(env.GEMI_SHUTDOWN_PROVIDER_TIMEOUT, 5),\n };\n // Warned, not clamped: the delay is sized to a probe, the timeout to the\n // platform's grace period, and which one is wrong only the operator knows.\n // Left alone, every shutdown spends the whole timeout in the delay and then\n // abandons whatever is in flight without draining it.\n if (settings.delayMs > 0 && settings.delayMs >= settings.timeoutMs) {\n console.warn(\n `[gemi] GEMI_SHUTDOWN_DELAY (${settings.delayMs / 1000}s) leaves no time to drain within GEMI_SHUTDOWN_TIMEOUT (${settings.timeoutMs / 1000}s); in-flight requests will be abandoned on every shutdown. Raise the timeout.`,\n );\n }\n return settings;\n}\n\nfunction seconds(value: string | undefined, fallback: number): number {\n const parsed = value === undefined || value.trim() === \"\" ? NaN : Number(value);\n if (Number.isFinite(parsed) && parsed >= 0) return parsed * 1000;\n if (value !== undefined) {\n console.warn(`[gemi] Ignoring shutdown setting \"${value}\": expected a number of seconds.`);\n }\n return fallback * 1000;\n}\n\n/** The part of `Bun.Server` a drain needs. */\nexport type Stoppable = {\n stop(closeActiveConnections?: boolean): Promise<void>;\n readonly pendingRequests: number;\n};\n\n/**\n * The shutdown sequence, in its order:\n *\n * 1. `isShuttingDown()` turns true — first, so the health route answers `503`\n * and responses carry `Connection: close` while the listener is still open.\n * 2. After `delayMs`, the listener closes (`server.stop()` without force):\n * new connections are refused, while every request in flight — a streamed\n * response included, to its last chunk — runs to completion.\n * Broadcast sockets are told `bye` and closed (`closeSockets`): a graceful\n * stop waits for open WebSockets, which never close on their own.\n * 3. That completion is awaited until `timeoutMs` from the start.\n * 4. From here a request is refused with a `503` before it reaches the app\n * (`serveForShutdown`), and every provider's `shutdown()` runs, reverse\n * order, `providerTimeoutMs`.\n *\n * Resolves with the exit code: 0 when every step finished in time, 1 when the\n * drain was cut short or a provider failed or overran.\n *\n * Two things `stop()` does not do, both measured on Bun 1.3.14, and both why\n * the process exit that follows is what actually ends the server:\n *\n * - It does not close a kept-alive connection. One that is idle when the\n * listener closes stays open, and a request sent down it afterwards is\n * served. That is what the `Connection: close` on every response in the\n * window is for: a client (or a proxy in front) that honours it opens its\n * next request on a new connection, which the closed listener refuses. A\n * client that does not honour it is what step 4's `503` is for — Bun does\n * not close the socket after a `Connection: close` response either (#566).\n * - `stop(true)` issued after a graceful `stop()` does not cut the remaining\n * requests off; it waits for the same ones. It is still called when the\n * drain times out, for a Bun that does, but nothing here depends on it. Nor\n * does it close an idle kept-alive connection. Only a `stop(true)` issued\n * *first* does that, and it cuts off the requests in flight with it, which\n * is the drain given up — so the idle ones are refused, not closed.\n */\nexport async function drain(params: {\n server: Stoppable | undefined;\n /**\n * Says `bye` to the broadcast sockets and closes them, right after the\n * listener closes, and resolves once they are closed or cut. A graceful\n * `stop()` waits for open WebSockets, which otherwise never close on their\n * own.\n */\n closeSockets?: () => void | Promise<void>;\n shutdownProviders: (options: { timeoutMs: number }) => Promise<ShutdownReport>;\n settings: ShutdownSettings;\n}): Promise<number> {\n const { server, settings } = params;\n const deadline = Date.now() + settings.timeoutMs;\n\n markShuttingDown();\n console.log(\n `[gemi] Shutting down: draining in-flight requests (up to ${settings.timeoutMs / 1000}s).`,\n );\n\n let drained = true;\n if (server) {\n if (settings.delayMs > 0) {\n await sleep(Math.min(settings.delayMs, deadline - Date.now()));\n }\n const stopped = server.stop();\n let socketsClosed: Promise<unknown> = Promise.resolve();\n try {\n socketsClosed = Promise.resolve(params.closeSockets?.()).catch(() => {});\n } catch (error) {\n console.error(\"[gemi] Closing the broadcast sockets failed:\", error);\n }\n // No time left to wait — a `GEMI_SHUTDOWN_TIMEOUT` of 0, or a delay that\n // spent all of it — is \"do not wait for what is in flight\", and that is\n // only a failure when something *is* in flight. Reading it as one made\n // every clean shutdown log an abandonment and exit 1 for the operator who\n // zeroed the budget to fit a 5s grace period, with nothing to abandon.\n const remaining = deadline - Date.now();\n // With broadcast sockets, the stop's own promise has been seen to stay\n // pending for good after every request finished and every socket was\n // closed or terminated (Bun 1.4.2 on a loaded Linux CI runner, with its\n // `pendingWebSockets` stuck above 0). So the drain also ends on its real\n // condition: no request in flight, and the hub's sockets closed or cut.\n const done = params.closeSockets\n ? Promise.race([stopped, Promise.all([socketsClosed, noRequestInFlight(server)])])\n : stopped;\n drained =\n remaining > 0 ? await settlesWithin(done, remaining) : server.pendingRequests === 0;\n if (!drained) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${server.pendingRequests} request(s) still in flight; abandoning them.`,\n );\n void server.stop(true).catch(() => {});\n }\n }\n\n // Whether or not the drain finished: a request that arrives now, down a\n // kept-alive connection the listener's close left open, would run against\n // providers that are being shut down underneath it.\n markDrained();\n const report = await params.shutdownProviders({ timeoutMs: settings.providerTimeoutMs });\n const clean = drained && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n}\n\n/**\n * Resolves once `server` has no request in flight. A streamed response counts\n * until its last chunk (measured on Bun 1.4, macOS and Linux).\n */\nfunction noRequestInFlight(server: Stoppable): Promise<void> {\n return new Promise((resolve) => {\n const check = () => {\n if (server.pendingRequests === 0) {\n resolve();\n return;\n }\n const timer = setTimeout(check, 50);\n (timer as { unref?: () => void }).unref?.();\n };\n check();\n });\n}\n\nasync function settlesWithin(promise: Promise<unknown>, ms: number): Promise<boolean> {\n // `drain` decides for itself what a budget that is already spent means, so\n // this is only a guard: a race against `setTimeout(0)` is a coin toss, and\n // \"did not settle within no time at all\" is the honest answer to it.\n if (ms <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const result = await Promise.race([\n promise.then(\n () => true,\n () => true,\n ),\n new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), ms);\n }),\n ]);\n clearTimeout(timer);\n return result;\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));\n}\n\n/**\n * `Connection: close` on a response sent while shutting down, so the client's\n * next request opens a connection — which the load balancer can send elsewhere\n * — instead of reusing this one.\n *\n * The spec makes some responses' headers immutable (a `Response.redirect`, a\n * proxied `fetch`), and setting one throws. Bun 1.3.14 lets both be set, so\n * the copy is for a Bun that follows the spec — a throw here would turn every\n * such response in the drain window into a 500.\n */\nexport function closeConnectionWhileShuttingDown(res: Response): Response {\n if (!isShuttingDown()) return res;\n try {\n res.headers.set(\"Connection\", \"close\");\n return res;\n } catch {\n const copy = new Response(res.body, res);\n copy.headers.set(\"Connection\", \"close\");\n return copy;\n }\n}\n\n/**\n * What every response goes through while this process serves: the app's\n * instrumentation, with the two changes a shutdown makes to it.\n *\n * - While the requests in flight drain, a response carries `Connection: close`\n * (`closeConnectionWhileShuttingDown`).\n * - Once they have drained, a request is answered `503` with\n * `Connection: close` and reaches neither the app nor its instrumentation.\n * The listener is closed by then, so only a kept-alive connection can still\n * deliver one, and `server.stop()` leaves those open. Serving it would run a\n * handler against providers whose `shutdown()` is closing the pool, the\n * queue or the cache it uses — until the process exits. The instrumentation\n * is skipped too because it is app code, and a tracer or error reporter is\n * exactly what a provider flushes and closes at this point.\n */\nexport function serveForShutdown(instrumentation: Instrumentation): Instrumentation {\n return async (req, next) => {\n if (state().drained) {\n return new Response(\"Service Unavailable\", {\n status: 503,\n headers: { Connection: \"close\" },\n });\n }\n return closeConnectionWhileShuttingDown(await instrumentation(req, next));\n };\n}\n\n// Installed once per process, not once per `Server`: a listener per instance\n// would each start a shutdown of its own, and read the other's signal as the\n// second one.\nconst SIGNALS_INSTALLED = Symbol.for(\"gemi.server.signalsInstalled\");\n\n/**\n * A repeat of the first signal inside this window is the same shutdown\n * delivered twice, not an operator asking to skip the drain. One shutdown\n * routinely arrives more than once, milliseconds apart: Ctrl+C on\n * `bun run start` reaches the server directly (the whole foreground group is\n * signalled), and again through `gemi start`'s relay — twice over, since\n * `bun run` forwards it to `gemi start` too. systemd's default\n * `KillMode=control-group` and `tini -g` do the same to every process in the\n * group. A person pressing Ctrl+C again is well outside a second.\n */\nconst REPEAT_WINDOW_MS = 1000;\n\n/**\n * `SIGTERM` or `SIGINT` runs `stop` and exits with the code it resolves with.\n * Another signal of either kind, more than `repeatWindowMs` after the first,\n * exits at once with `128 + n` — an operator pressing Ctrl+C again does not\n * want to wait out the grace period. Without a listener the first signal would\n * do that too: the default action for both is to terminate the process on the\n * spot.\n */\nexport function installShutdownSignals(\n stop: () => Promise<number>,\n options: { repeatWindowMs?: number } = {},\n) {\n const global = globalThis as { [SIGNALS_INSTALLED]?: boolean };\n if (global[SIGNALS_INSTALLED]) return;\n global[SIGNALS_INSTALLED] = true;\n\n const repeatWindowMs = options.repeatWindowMs ?? REPEAT_WINDOW_MS;\n let receivedAt: number | undefined;\n const onSignal = (signal: \"SIGTERM\" | \"SIGINT\") => {\n if (receivedAt !== undefined) {\n if (Date.now() - receivedAt < repeatWindowMs) return;\n console.error(`[gemi] ${signal} received again; exiting without waiting for the drain.`);\n process.exit(128 + constants.signals[signal]);\n }\n receivedAt = Date.now();\n console.log(`[gemi] ${signal} received.`);\n stop().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"[gemi] Shutdown failed:\", error);\n process.exit(1);\n },\n );\n };\n process.on(\"SIGTER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