gemi 0.131.0 → 0.133.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 (230) hide show
  1. package/dist/ai/AgentController.d.ts +73 -0
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/AgentProvider.d.ts +25 -0
  4. package/dist/ai/AgentProvider.d.ts.map +1 -1
  5. package/dist/ai/VoiceBridge.d.ts +365 -0
  6. package/dist/ai/VoiceBridge.d.ts.map +1 -0
  7. package/dist/ai/index.d.ts +13 -0
  8. package/dist/ai/index.d.ts.map +1 -1
  9. package/dist/ai/index.js +18 -18
  10. package/dist/ai/index.js.map +11 -6
  11. package/dist/ai/providers/endpoints.d.ts +19 -0
  12. package/dist/ai/providers/endpoints.d.ts.map +1 -1
  13. package/dist/ai/providers/realtime.d.ts +272 -0
  14. package/dist/ai/providers/realtime.d.ts.map +1 -0
  15. package/dist/ai/providers/sideband.d.ts +254 -0
  16. package/dist/ai/providers/sideband.d.ts.map +1 -0
  17. package/dist/ai/runtime.d.ts.map +1 -1
  18. package/dist/ai/types.d.ts +15 -0
  19. package/dist/ai/types.d.ts.map +1 -1
  20. package/dist/ai/voice/index.d.ts +23 -0
  21. package/dist/ai/voice/index.d.ts.map +1 -0
  22. package/dist/ai/voice/index.js +433 -0
  23. package/dist/ai/voice/index.js.map +1 -0
  24. package/dist/ai/voice/state.d.ts +34 -0
  25. package/dist/ai/voice/state.d.ts.map +1 -0
  26. package/dist/ai/voice/useVoiceSession.d.ts +82 -0
  27. package/dist/ai/voice/useVoiceSession.d.ts.map +1 -0
  28. package/dist/ai/voice/voiceCall.d.ts +57 -0
  29. package/dist/ai/voice/voiceCall.d.ts.map +1 -0
  30. package/dist/ai/voice/wire.d.ts +66 -0
  31. package/dist/ai/voice/wire.d.ts.map +1 -0
  32. package/dist/ai/voiceConfig.d.ts +70 -0
  33. package/dist/ai/voiceConfig.d.ts.map +1 -0
  34. package/dist/ai/voiceMcp.d.ts +89 -0
  35. package/dist/ai/voiceMcp.d.ts.map +1 -0
  36. package/dist/ai/voiceStore.d.ts +52 -0
  37. package/dist/ai/voiceStore.d.ts.map +1 -0
  38. package/dist/app/index.js +1 -1
  39. package/dist/bun/plugin.js +1 -1
  40. package/dist/bun/preload.js +1 -1
  41. package/dist/{chunk-4gmhx2ba.js → chunk-0eamc2tr.js} +2 -2
  42. package/dist/{chunk-4gmhx2ba.js.map → chunk-0eamc2tr.js.map} +1 -1
  43. package/dist/{chunk-2x0n3ze1.js → chunk-0gg4e94v.js} +2 -2
  44. package/dist/{chunk-2x0n3ze1.js.map → chunk-0gg4e94v.js.map} +1 -1
  45. package/dist/{chunk-p642ja42.js → chunk-0rhf4g12.js} +3 -3
  46. package/dist/{chunk-p642ja42.js.map → chunk-0rhf4g12.js.map} +1 -1
  47. package/dist/{chunk-dxm5gxqk.js → chunk-1awxdnb6.js} +1 -1
  48. package/dist/{chunk-2senwsdq.js → chunk-2cnawkke.js} +12 -12
  49. package/dist/{chunk-2senwsdq.js.map → chunk-2cnawkke.js.map} +3 -3
  50. package/dist/{chunk-fxm8fqh9.js → chunk-33hdxe7v.js} +1 -1
  51. package/dist/{chunk-63xekerg.js → chunk-3g5q0cj5.js} +2 -2
  52. package/dist/{chunk-63xekerg.js.map → chunk-3g5q0cj5.js.map} +1 -1
  53. package/dist/{chunk-xjs72pb0.js → chunk-3h37f124.js} +2 -2
  54. package/dist/{chunk-xjs72pb0.js.map → chunk-3h37f124.js.map} +1 -1
  55. package/dist/{chunk-65fq5a9d.js → chunk-4278e429.js} +2 -2
  56. package/dist/{chunk-65fq5a9d.js.map → chunk-4278e429.js.map} +1 -1
  57. package/dist/chunk-47e7fbsp.js +5 -0
  58. package/dist/{chunk-mvka90rq.js.map → chunk-47e7fbsp.js.map} +1 -1
  59. package/dist/{chunk-p6b0cyf8.js → chunk-4pvv8qs0.js} +2 -2
  60. package/dist/{chunk-p6b0cyf8.js.map → chunk-4pvv8qs0.js.map} +1 -1
  61. package/dist/{chunk-rjyw1thg.js → chunk-4t41m5f1.js} +2 -2
  62. package/dist/{chunk-rjyw1thg.js.map → chunk-4t41m5f1.js.map} +1 -1
  63. package/dist/{chunk-f21v4n2v.js → chunk-53rr32zm.js} +1 -1
  64. package/dist/{chunk-xhvknqvn.js → chunk-5pdgh9a1.js} +2 -2
  65. package/dist/{chunk-xhvknqvn.js.map → chunk-5pdgh9a1.js.map} +1 -1
  66. package/dist/{chunk-e4ay1vg9.js → chunk-65j32dtn.js} +2 -2
  67. package/dist/{chunk-e4ay1vg9.js.map → chunk-65j32dtn.js.map} +1 -1
  68. package/dist/{chunk-jxvec7jc.js → chunk-6fr6j338.js} +2 -2
  69. package/dist/{chunk-jxvec7jc.js.map → chunk-6fr6j338.js.map} +1 -1
  70. package/dist/{chunk-jd1afbrs.js → chunk-6hz63ts4.js} +4 -4
  71. package/dist/{chunk-jd1afbrs.js.map → chunk-6hz63ts4.js.map} +1 -1
  72. package/dist/{chunk-4z0rt6ws.js → chunk-6qty7at2.js} +2 -2
  73. package/dist/{chunk-4z0rt6ws.js.map → chunk-6qty7at2.js.map} +1 -1
  74. package/dist/{chunk-pzb3agv9.js → chunk-7nxnyw7x.js} +2 -2
  75. package/dist/{chunk-pzb3agv9.js.map → chunk-7nxnyw7x.js.map} +1 -1
  76. package/dist/{chunk-7n0zn5h4.js → chunk-8ryrjtn0.js} +2 -2
  77. package/dist/{chunk-7n0zn5h4.js.map → chunk-8ryrjtn0.js.map} +1 -1
  78. package/dist/{chunk-c1gq2ttb.js → chunk-8sde8337.js} +2 -2
  79. package/dist/{chunk-c1gq2ttb.js.map → chunk-8sde8337.js.map} +1 -1
  80. package/dist/{chunk-cggywjzz.js → chunk-99a4e6zf.js} +2 -2
  81. package/dist/{chunk-cggywjzz.js.map → chunk-99a4e6zf.js.map} +1 -1
  82. package/dist/chunk-b6yb3svm.js +6 -0
  83. package/dist/{chunk-539w9yt3.js.map → chunk-b6yb3svm.js.map} +2 -2
  84. package/dist/{chunk-822p54vc.js → chunk-beb265c9.js} +2 -2
  85. package/dist/{chunk-822p54vc.js.map → chunk-beb265c9.js.map} +1 -1
  86. package/dist/{chunk-hdgbh8hn.js → chunk-cxsvzqd4.js} +2 -2
  87. package/dist/{chunk-hdgbh8hn.js.map → chunk-cxsvzqd4.js.map} +1 -1
  88. package/dist/{chunk-pahr13xg.js → chunk-dt95z6et.js} +2 -2
  89. package/dist/{chunk-pahr13xg.js.map → chunk-dt95z6et.js.map} +1 -1
  90. package/dist/{chunk-hr8annr1.js → chunk-feajsgns.js} +2 -2
  91. package/dist/{chunk-hr8annr1.js.map → chunk-feajsgns.js.map} +1 -1
  92. package/dist/{chunk-2tda49mv.js → chunk-ff60bzvf.js} +2 -2
  93. package/dist/{chunk-2tda49mv.js.map → chunk-ff60bzvf.js.map} +1 -1
  94. package/dist/{chunk-b00z33zg.js → chunk-gng5e7pd.js} +1 -1
  95. package/dist/{chunk-mz73066c.js → chunk-gqgpwb88.js} +2 -2
  96. package/dist/{chunk-mz73066c.js.map → chunk-gqgpwb88.js.map} +1 -1
  97. package/dist/{chunk-h0xye69a.js → chunk-ha15x5ns.js} +2 -2
  98. package/dist/{chunk-h0xye69a.js.map → chunk-ha15x5ns.js.map} +1 -1
  99. package/dist/{chunk-d5g1caxb.js → chunk-hb9hm8za.js} +3 -3
  100. package/dist/{chunk-d5g1caxb.js.map → chunk-hb9hm8za.js.map} +1 -1
  101. package/dist/{chunk-8fvt7kys.js → chunk-hf492gg2.js} +1 -1
  102. package/dist/{chunk-fgtr9cds.js → chunk-hj88dcss.js} +3 -3
  103. package/dist/{chunk-fgtr9cds.js.map → chunk-hj88dcss.js.map} +1 -1
  104. package/dist/{chunk-hnf11jhc.js → chunk-j5g7qc5f.js} +2 -2
  105. package/dist/{chunk-hnf11jhc.js.map → chunk-j5g7qc5f.js.map} +1 -1
  106. package/dist/{chunk-e1fhy2h5.js → chunk-jgx8ggbz.js} +2 -2
  107. package/dist/{chunk-e1fhy2h5.js.map → chunk-jgx8ggbz.js.map} +1 -1
  108. package/dist/{chunk-35zw2s61.js → chunk-jx2mgvvt.js} +3 -3
  109. package/dist/{chunk-35zw2s61.js.map → chunk-jx2mgvvt.js.map} +1 -1
  110. package/dist/{chunk-w26cw41m.js → chunk-jx5zx48j.js} +2 -2
  111. package/dist/{chunk-w26cw41m.js.map → chunk-jx5zx48j.js.map} +1 -1
  112. package/dist/{chunk-z1gjgr1c.js → chunk-jy9dkgt0.js} +2 -2
  113. package/dist/{chunk-z1gjgr1c.js.map → chunk-jy9dkgt0.js.map} +1 -1
  114. package/dist/{chunk-7j48ymk1.js → chunk-k2xeskp6.js} +2 -2
  115. package/dist/{chunk-7j48ymk1.js.map → chunk-k2xeskp6.js.map} +1 -1
  116. package/dist/{chunk-jxmc33m9.js → chunk-ka991yx4.js} +2 -2
  117. package/dist/{chunk-jxmc33m9.js.map → chunk-ka991yx4.js.map} +1 -1
  118. package/dist/{chunk-65s63bdh.js → chunk-krk880my.js} +2 -2
  119. package/dist/{chunk-65s63bdh.js.map → chunk-krk880my.js.map} +1 -1
  120. package/dist/{chunk-x4yq0c9v.js → chunk-m9vwg9j1.js} +3 -3
  121. package/dist/{chunk-x4yq0c9v.js.map → chunk-m9vwg9j1.js.map} +1 -1
  122. package/dist/{chunk-x07rp3fc.js → chunk-mpqvmge4.js} +1 -1
  123. package/dist/{chunk-n7sbwpce.js → chunk-mw7ft5bs.js} +2 -2
  124. package/dist/{chunk-n7sbwpce.js.map → chunk-mw7ft5bs.js.map} +1 -1
  125. package/dist/{chunk-v5esvs66.js → chunk-njpnstck.js} +2 -2
  126. package/dist/{chunk-v5esvs66.js.map → chunk-njpnstck.js.map} +1 -1
  127. package/dist/{chunk-p320fd3g.js → chunk-p82868xx.js} +2 -2
  128. package/dist/{chunk-p320fd3g.js.map → chunk-p82868xx.js.map} +1 -1
  129. package/dist/{chunk-jbd723h1.js → chunk-pm8wjatv.js} +3 -3
  130. package/dist/{chunk-jbd723h1.js.map → chunk-pm8wjatv.js.map} +1 -1
  131. package/dist/{chunk-t227jn4b.js → chunk-q15f5g86.js} +2 -2
  132. package/dist/{chunk-t227jn4b.js.map → chunk-q15f5g86.js.map} +1 -1
  133. package/dist/{chunk-838cdh6v.js → chunk-qfra7gah.js} +2 -2
  134. package/dist/{chunk-838cdh6v.js.map → chunk-qfra7gah.js.map} +1 -1
  135. package/dist/{chunk-aprjvzrz.js → chunk-rnp5k8m3.js} +2 -2
  136. package/dist/{chunk-aprjvzrz.js.map → chunk-rnp5k8m3.js.map} +1 -1
  137. package/dist/{chunk-qz89m7ss.js → chunk-rzqft8q8.js} +2 -2
  138. package/dist/{chunk-qz89m7ss.js.map → chunk-rzqft8q8.js.map} +1 -1
  139. package/dist/{chunk-zc5962gh.js → chunk-s025aycr.js} +2 -2
  140. package/dist/{chunk-zc5962gh.js.map → chunk-s025aycr.js.map} +1 -1
  141. package/dist/{chunk-y14weak4.js → chunk-s21kn0x8.js} +2 -2
  142. package/dist/{chunk-y14weak4.js.map → chunk-s21kn0x8.js.map} +1 -1
  143. package/dist/{chunk-3wnczt5w.js → chunk-s55t7rxw.js} +2 -2
  144. package/dist/{chunk-3wnczt5w.js.map → chunk-s55t7rxw.js.map} +1 -1
  145. package/dist/{chunk-fzs7g6mc.js → chunk-s782bzeq.js} +2 -2
  146. package/dist/{chunk-fzs7g6mc.js.map → chunk-s782bzeq.js.map} +1 -1
  147. package/dist/{chunk-77ymcf7q.js → chunk-sa6cxt3g.js} +2 -2
  148. package/dist/{chunk-77ymcf7q.js.map → chunk-sa6cxt3g.js.map} +1 -1
  149. package/dist/{chunk-dz76qhx8.js → chunk-swwkdm75.js} +2 -2
  150. package/dist/{chunk-dz76qhx8.js.map → chunk-swwkdm75.js.map} +1 -1
  151. package/dist/{chunk-58mg4rpd.js → chunk-t33yh84d.js} +2 -2
  152. package/dist/{chunk-58mg4rpd.js.map → chunk-t33yh84d.js.map} +1 -1
  153. package/dist/{chunk-mym7egdq.js → chunk-vnw91fe1.js} +2 -2
  154. package/dist/{chunk-mym7egdq.js.map → chunk-vnw91fe1.js.map} +1 -1
  155. package/dist/{chunk-4wda9teq.js → chunk-w1cksc5z.js} +3 -3
  156. package/dist/{chunk-4wda9teq.js.map → chunk-w1cksc5z.js.map} +1 -1
  157. package/dist/chunk-wevj4981.js +122 -0
  158. package/dist/{chunk-fx7r6pdf.js.map → chunk-wevj4981.js.map} +3 -3
  159. package/dist/{chunk-ayjfs5mm.js → chunk-wrsf2abe.js} +2 -2
  160. package/dist/{chunk-ayjfs5mm.js.map → chunk-wrsf2abe.js.map} +1 -1
  161. package/dist/{chunk-j1wc4afr.js → chunk-x16ckgq1.js} +2 -2
  162. package/dist/{chunk-j1wc4afr.js.map → chunk-x16ckgq1.js.map} +1 -1
  163. package/dist/{chunk-gnaxedwh.js → chunk-x51tegk3.js} +2 -2
  164. package/dist/{chunk-gnaxedwh.js.map → chunk-x51tegk3.js.map} +1 -1
  165. package/dist/{chunk-qspam5cf.js → chunk-x5hj0mqp.js} +2 -2
  166. package/dist/{chunk-qspam5cf.js.map → chunk-x5hj0mqp.js.map} +1 -1
  167. package/dist/{chunk-dp2yz8bj.js → chunk-x9bk5s21.js} +2 -2
  168. package/dist/{chunk-dp2yz8bj.js.map → chunk-x9bk5s21.js.map} +1 -1
  169. package/dist/{chunk-p462p2xe.js → chunk-xvvsc58s.js} +2 -2
  170. package/dist/{chunk-p462p2xe.js.map → chunk-xvvsc58s.js.map} +1 -1
  171. package/dist/{chunk-0g5f8ymy.js → chunk-xymr3asa.js} +2 -2
  172. package/dist/{chunk-0g5f8ymy.js.map → chunk-xymr3asa.js.map} +1 -1
  173. package/dist/{chunk-j4y0sjdc.js → chunk-ysc7ykss.js} +2 -2
  174. package/dist/{chunk-j4y0sjdc.js.map → chunk-ysc7ykss.js.map} +1 -1
  175. package/dist/{chunk-3xy41vc0.js → chunk-z61dj480.js} +3 -3
  176. package/dist/{chunk-3xy41vc0.js.map → chunk-z61dj480.js.map} +1 -1
  177. package/dist/{chunk-0q68t71d.js → chunk-z9xxthp1.js} +3 -3
  178. package/dist/{chunk-0q68t71d.js.map → chunk-z9xxthp1.js.map} +1 -1
  179. package/dist/{chunk-47eav3ex.js → chunk-zv5qyrqg.js} +2 -2
  180. package/dist/{chunk-47eav3ex.js.map → chunk-zv5qyrqg.js.map} +1 -1
  181. package/dist/{chunk-asmszzkp.js → chunk-zyhmn3hy.js} +3 -3
  182. package/dist/{chunk-asmszzkp.js.map → chunk-zyhmn3hy.js.map} +1 -1
  183. package/dist/{chunk-zzgt759n.js → chunk-zypmy8yq.js} +2 -2
  184. package/dist/{chunk-zzgt759n.js.map → chunk-zypmy8yq.js.map} +1 -1
  185. package/dist/config/index.js +1 -1
  186. package/dist/console/run.js +2 -2
  187. package/dist/console/run.js.map +1 -1
  188. package/dist/container/index.js +2 -2
  189. package/dist/container/index.js.map +1 -1
  190. package/dist/database/index.js +2 -2
  191. package/dist/database/index.js.map +1 -1
  192. package/dist/email/index.js +2 -2
  193. package/dist/email/index.js.map +1 -1
  194. package/dist/facades/index.js +2 -2
  195. package/dist/facades/index.js.map +1 -1
  196. package/dist/foundation/index.js +2 -2
  197. package/dist/foundation/index.js.map +1 -1
  198. package/dist/http/ApiRouter.d.ts +27 -5
  199. package/dist/http/ApiRouter.d.ts.map +1 -1
  200. package/dist/http/index.js +2 -2
  201. package/dist/http/index.js.map +1 -1
  202. package/dist/i18n/dictionaryRuntime.js +2 -2
  203. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  204. package/dist/i18n/index.js +2 -2
  205. package/dist/i18n/index.js.map +1 -1
  206. package/dist/kernel/index.js +2 -2
  207. package/dist/kernel/index.js.map +1 -1
  208. package/dist/orm/defaults.d.ts.map +1 -1
  209. package/dist/orm/index.js +3 -3
  210. package/dist/orm/index.js.map +3 -3
  211. package/dist/server/index.js +2 -2
  212. package/dist/server/index.js.map +1 -1
  213. package/dist/services/index.js +2 -2
  214. package/dist/services/index.js.map +1 -1
  215. package/dist/services/queue/work.js +2 -2
  216. package/dist/services/queue/work.js.map +1 -1
  217. package/dist/stats/route-table.js +1 -1
  218. package/dist/support/index.js +2 -2
  219. package/dist/support/index.js.map +1 -1
  220. package/dist/vitest/index.js +1 -1
  221. package/package.json +2 -1
  222. package/dist/chunk-539w9yt3.js +0 -6
  223. package/dist/chunk-fx7r6pdf.js +0 -122
  224. package/dist/chunk-mvka90rq.js +0 -5
  225. /package/dist/{chunk-dxm5gxqk.js.map → chunk-1awxdnb6.js.map} +0 -0
  226. /package/dist/{chunk-fxm8fqh9.js.map → chunk-33hdxe7v.js.map} +0 -0
  227. /package/dist/{chunk-f21v4n2v.js.map → chunk-53rr32zm.js.map} +0 -0
  228. /package/dist/{chunk-b00z33zg.js.map → chunk-gng5e7pd.js.map} +0 -0
  229. /package/dist/{chunk-8fvt7kys.js.map → chunk-hf492gg2.js.map} +0 -0
  230. /package/dist/{chunk-x07rp3fc.js.map → chunk-mpqvmge4.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Aj as T0,xj as n,yj as k}from"./chunk-j4y0sjdc.js";import{Bj as S0}from"./chunk-w26cw41m.js";import{Dj as N0,Ej as R0,Fj as Q0,Hj as D,Jj as q,Sj as B0}from"./chunk-0q68t71d.js";import{fk as X0}from"./chunk-e4ay1vg9.js";import{Ck as W0,Fk as m}from"./chunk-35zw2s61.js";import{Ok as M0}from"./chunk-mz73066c.js";class y{table;sql;dialect;connection;busyTimeout;configured;constructor(z,V={}){let Y=V.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Y))throw Error(`The lock table name "${Y}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Y,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=V.busyTimeout??1000}async createTable(){await this.configure();for(let z of v0(this.dialect,this.table))await this.sql.unsafe(z)}async acquire(z,V,Y){await this.configure();let Z=this.sql,$=this.now(Z);if(await this.seed(Z,z),this.mysql){let H=await Z`
2
+ import{Bj as T0,yj as n,zj as k}from"./chunk-ysc7ykss.js";import{Cj as S0}from"./chunk-jx5zx48j.js";import{Ej as N0,Fj as R0,Gj as Q0,Ij as D,Kj as q,Tj as B0}from"./chunk-z9xxthp1.js";import{gk as X0}from"./chunk-65j32dtn.js";import{Dk as W0,Gk as m}from"./chunk-jx2mgvvt.js";import{Pk as M0}from"./chunk-gqgpwb88.js";class y{table;sql;dialect;connection;busyTimeout;configured;constructor(z,V={}){let Y=V.table??"gemi_locks";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Y))throw Error(`The lock table name "${Y}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Y,this.sql=z.sql,this.dialect=z.dialect,this.connection=z.name,this.busyTimeout=V.busyTimeout??1000}async createTable(){await this.configure();for(let z of v0(this.dialect,this.table))await this.sql.unsafe(z)}async acquire(z,V,Y){await this.configure();let Z=this.sql,$=this.now(Z);if(await this.seed(Z,z),this.mysql){let H=await Z`
3
3
  UPDATE ${this.name(Z)}
4
4
  SET owner = ${V}, token = token + 1, expires_at = ${$} + ${this.ms(Z,Y)},
5
5
  updated_at = ${$}
@@ -413,4 +413,4 @@ ADD COLUMN IF NOT EXISTS "progress" ${Y}`,`CREATE INDEX IF NOT EXISTS "${V}_batc
413
413
  `],"worker.ts"),$=URL.createObjectURL(Z);return new Worker($)}async function d0(z,V){let Y=w0();return Y.postMessage({jobName:z,args:V}),await new Promise((Z,$)=>{Y.onmessage=(X)=>{let H=X.data;if("error"in H)$(H.error);else Z(H.result)}})}var c0=new k0("gemi.queue"),l0=60000;class h{static token="queue";jobs={};config;driver;application;inFlight=new Map;state="idle";looping=!1;claiming;woken=!1;claimFailures=0;resume;unsubscribe;heartbeatTimer;releasedNames=new Set;lockManager;workflowRuntime;constructor(z={},V={}){if(this.config=S0(D0(),z),this.application=V.application,this.driver=r0(this.config.driver,this.application),this.useJobs(this.config.jobs),this.config.workflows.length>0)this.useWorkflows(this.config.workflows)}useJobs(z){this.config.jobs=z,this.jobs={};for(let V of z)this.claim(V);this.registerTickJob()}useWorkflows(z){this.config.workflows=z,this.workflows.use(z),this.registerTickJob()}get registeredWorkflows(){return[...this.config.workflows]}get workflows(){return this.workflowRuntime??=new H0(this),this.workflowRuntime}registerTickJob(){if(!this.workflowRuntime||Object.keys(this.workflowRuntime.workflows).length===0)return;let z=this.workflowRuntime.tickJob;if(this.jobs[z.name]&&this.jobs[z.name]!==z){console.error(`A queued job is named "${z.name}", which the workflow runtime uses. Workflows will not run until it is renamed.`);return}this.jobs[z.name]=z}registerJob(z){this.config.jobs=[...this.config.jobs,z],this.claim(z)}claim(z){if(this.jobs[z.name]){console.error(`Two queued jobs are named "${z.name}" \u2014 the first is registered `+"and this one is not, so dispatching either would have run one of them. A class name is the queue's key, so only one job can hold it. Rename one.");return}this.jobs[z.name]=z}get registeredJobs(){return[...this.config.jobs]}dispatchJob(z,V){if(this.jobs[z])return new this.jobs[z]().run(JSON.parse(V))}push(z,V,Y={}){let Z=this.uniqueKey(z,V);if(Z)return this.pushUnique(z,V,Z,Y);let $=this.driver.joinsTransaction?.()===!0;if(!$){let X=Bun.randomUUIDv7();if(D(()=>this.record(z,V,{id:X,reportFailure:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve(X)}return this.record(z,V,{reportFailure:Y.reportFailure,joins:$})}pushBatch(z,V,Y={}){let Z=this.buildBatch(z,V,Y),$={id:Z.id,total:V.length},X=this.driver.joinsTransaction?.()===!0;if(!X){if(D(()=>this.recordBatch(Z,{committed:!0}).then(()=>{},()=>{})))return Promise.resolve($)}return this.recordBatch(Z,{joins:X}).then(()=>$)}buildBatch(z,V,Y={}){if(!this.driver.enqueueBatch)throw Error("This queue's driver does not support batches. The memory and database drivers do.");if(new z().worker)throw Error(`${z.name} is a worker job, and a worker job cannot be dispatched in a batch: its thread has no way to report progress or reach the batch.`);if(z.prototype.uniqueId!==S.prototype.uniqueId)throw Error(`${z.name} is unique (it defines uniqueId), and a unique job cannot be dispatched in a batch: a duplicate would resolve to a job outside the batch, and the batch would wait for it forever.`);let $={};for(let X of["then","catch","finally"]){let H=Y[X];if(H===void 0)continue;if(typeof H?.name!=="string"||!Array.isArray(H.args))throw Error(`The batch's ${X} callback is not a job call. Build it with SomeJob.with(...args).`);$[X]={name:H.name,args:H.args}}return{id:Bun.randomUUIDv7(),name:Y.name??null,job:z.name,args:V,allowFailures:Y.allowFailures===!0,callbacks:$}}recordBatch(z,V){let Y=this.driver.enqueueBatch(z);this.startIfIdle();let Z=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),$=V.joins===!0&&D(Z);return Y.then(()=>$||Z(),(X)=>{if(!V.committed)return;console.error(`[gemi] The queue driver could not record a batch of ${z.job}, which was held until its transaction committed. The transaction stays committed; the batch's jobs did not run and will not be retried.`,X)}),Y}async findBatch(z){if(!this.driver.findBatch)throw Error("This queue's driver does not support batches.");return this.driver.findBatch(z)}async cancelBatch(z){if(!this.driver.cancelBatch)throw Error("This queue's driver does not support batches.");let V=await this.driver.cancelBatch(z);if(V)this.claimSoon();return V}get locks(){return this.lockManager??=new T0(this.resolveLockStore()),this.lockManager}resolveLockStore(){let z=this.config.locks;if(z==="auto"){let V=this.driver.lockStore?.();if(V)return V;if(this.durable)console.warn('[gemi] The queue driver keeps no locks, so unique jobs, withoutOverlapping and onOneServer only hold within this process. Set the queue slice\'s `locks` to "database" or a LockStore.');return new p}if(z==="memory")return new p;if(z==="database"||typeof z==="function"){if(!this.application&&(z==="database"||z.length>0))throw Error("The queue's locks need the application they belong to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new y(this.application.make(X0));return z(this.application)}if(typeof z==="string")throw Error(`Unknown queue locks "${z}". The queue slice's locks is "auto", "memory", "database", a LockStore, or a function returning one.`);return z}uniqueKey(z,V){if(z.prototype.uniqueId===S.prototype.uniqueId)return;let Y=new z,Z=Y.uniqueId(...JSON.parse(V));if(Z===void 0||Z===null||Z==="")return;return{key:L0(z.name,Z),ttl:Math.max(1,Y.uniqueFor)}}pushUnique(z,V,Y,Z){let $=Bun.randomUUIDv7();if(D(()=>this.recordUnique(z,V,Y,$,{report:!0,committed:!0}).then(()=>{},()=>{})))return Promise.resolve($);return this.recordUnique(z,V,Y,$,{report:Z.reportFailure!==!1,committed:!1})}recordUnique(z,V,Y,Z,$){let X=this.locks.store,H=(async()=>{for(let G=0;G<5;G++){if(await X.acquire(Y.key,Z,Y.ttl)!==null)try{return await this.record(z,V,{id:Z,reportFailure:!1})}catch(B){throw await X.release(Y.key,Z).catch(()=>{}),B}let Q=await X.holder(Y.key);if(Q)return Q.owner}throw Error(`The unique key "${Y.key}" kept changing hands, so ${z.name} was not queued.`)})();return H.catch((G)=>{if(!$.report)return;console.error(`[gemi] The queue could not record the unique job ${z.name}`+($.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),G)}),H}async releaseUnique(z,V,Y){if(z.uniqueId===S.prototype.uniqueId)return;try{let Z=z.uniqueId(...V);if(Z===void 0||Z===null||Z==="")return;await this.locks.store.release(L0(Y.name,Z),Y.id)}catch(Z){console.error(`[gemi] Could not free the unique key of ${Y.name} (${Y.id}); it frees itself after uniqueFor.`,Z)}}record(z,V,Y){let Z=this.driver.enqueue({name:z.name,args:V,...Y.id===void 0?{}:{id:Y.id}});this.startIfIdle();let $=()=>!this.driver.subscribe&&this.state==="running"&&this.wake(),X=Y.joins===!0&&D($);return Z.then(()=>X||$(),(H)=>{if(Y.reportFailure===!1)return;console.error(`[gemi] The queue driver could not record ${z.name}`+(Y.committed?", which was held until its transaction committed. The transaction stays committed; the job did not run and will not be retried.":", so it did not run and will not be retried."),H)}),Z}async retryDead(z){if(!this.driver.retryDead)throw Error("This queue's driver keeps nothing of a dead-lettered job, so there is nothing to retry. The database driver keeps them.");let V=await this.driver.retryDead(z);if(V)this.claimSoon();return V}startIfIdle(){if(this.state==="idle"&&(!this.durable||this.mayClaimHere()))this.start()}claimSoon(){if(this.startIfIdle(),!this.driver.subscribe&&this.state==="running")this.wake()}start(){if(this.state==="running")return;if(this.state="running",this.durable&&this.application&&this.mayClaimHere()&&!i0())globalThis.__gemiDevQueue=this;if(this.unsubscribe=this.driver.subscribe?.(()=>this.wake()),this.looping)return this.wake();c0.runInAsyncScope(()=>void this.loop())}async drain(z=1/0){if(this.state="stopped",globalThis.__gemiDevQueue===this)globalThis.__gemiDevQueue=void 0;this.unsubscribe?.(),this.unsubscribe=void 0,this.wake();let V,Y=new Promise(($)=>{if(z!==1/0)V=setTimeout($,z)}),Z=(async()=>{await this.claiming?.catch(()=>{}),await Promise.allSettled([...this.inFlight.values()].map(($)=>$.done))})();return await Promise.race([Z,Y]),clearTimeout(V),{unfinished:[...this.inFlight.values()].map(($)=>({...$.job}))}}stop(){return this.drain(0)}get running(){return this.inFlight.size}async loop(){this.looping=!0;try{await this.claimWhileRunning()}finally{this.looping=!1}}async claimWhileRunning(){while(this.state==="running"){let z=this.durable&&M0()?0:this.config.concurrency-this.inFlight.size;if(z>0){this.woken=!1;let V=this.driver.claim(z,{...this.lease(),registered:{names:Object.keys(this.jobs),graceMs:this.config.unknownJobGrace}});this.claiming=V;let Y=[];try{Y=await V,this.claimFailures=0}catch(Z){this.claimFailures++,console.error(`The queue could not claim jobs from its driver; it will try again in ${this.retryDelay()}ms.`,Z)}finally{this.claiming=void 0}for(let Z of Y)this.execute(Z);if(Y.length===z)continue;if(this.woken&&this.inFlight.size<this.config.concurrency)continue}await this.sleep()}}sleep(){return new Promise((z)=>{let V,Y=this.claimFailures>0?this.retryDelay():this.driver.subscribe?void 0:this.config.pollInterval;if(Y!==void 0)V=setTimeout(()=>this.wake(),Y),V.unref?.();this.resume=()=>{clearTimeout(V),z()}})}retryDelay(){let z=Math.min(Math.max(0,this.claimFailures-1),30);return Math.min(this.config.pollInterval*2**z,l0)}wake(){this.woken=!0;let z=this.resume;this.resume=void 0,z?.()}get durable(){return!(this.driver instanceof i)}mayClaimHere(){return!this.application||s0()}lease(){return{visibilityTimeoutMs:this.config.visibilityTimeout}}execute(z){let V=`${z.id}:${z.attempt}`,Y=()=>this.run(z),Z=(this.application?W0.run(this.application,Y):Y()).catch(($)=>{console.error(`The queue could not record the outcome of ${z.name}.`,$)}).finally(()=>{this.inFlight.delete(V),this.wake()});this.inFlight.set(V,{job:z,done:Z}),this.heartbeat()}heartbeat(){let z=this.driver;if(!z.heartbeat||this.heartbeatTimer)return;this.heartbeatTimer=setInterval(()=>{if(this.inFlight.size===0){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0;return}let V=[...this.inFlight.values()].map((Y)=>Y.job);z.heartbeat(V,this.lease()).catch((Y)=>{console.error("The queue could not extend its job leases.",Y)})},Math.max(1,Math.floor(this.config.visibilityTimeout/3))),this.heartbeatTimer.unref?.()}async run(z){let V=this.jobs[z.name];if(!V){let B=Date.now()-z.createdAt;if(this.durable&&B<this.config.unknownJobGrace){if(!this.releasedNames.has(z.name))this.releasedNames.add(z.name),console.error(`Left a queued "${z.name}" for another replica: nothing is registered here under that name. It is dead-lettered if no replica has run it within unknownJobGrace (${this.config.unknownJobGrace}ms) of its dispatch.`);await this.driver.release(z,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}console.error(`Dropped a queued job: nothing is registered under the name "${z.name}". If the class exists, it was not `+"discovered \u2014 check that it is under the queue slice's jobsDir "+"(app/jobs by default), or list it in app/config/queue.ts."),await this.driver.fail(z,{error:`No job is registered under the name "${z.name}".`,retryInMs:null});return}let Y;try{Y=new V}catch(B){console.error(`Dropped a queued ${z.name}: it could not be constructed.`,B),await this.driver.fail(z,{error:`The job could not be constructed: ${String(B)}`,retryInMs:null});return}let Z;try{Z=JSON.parse(z.args)}catch(B){console.error(`Dropped a queued ${z.name}: its arguments are not JSON.`,B),await this.driver.fail(z,{error:`The arguments are not JSON: ${String(B)}`,retryInMs:null});return}if(z.attempt>Math.max(1,Y.maxAttempts)){let B=Error(`${z.name} was claimed for attempt ${z.attempt} of ${Y.maxAttempts}: an earlier attempt never finished, most likely because the process running it exited. Dead-lettered without running it again.`);$0(`${z.name}.onDeadletter`,()=>Y.onDeadletter(B,...Z)),await this.driver.fail(z,{error:B.message,retryInMs:null}),await this.releaseUnique(Y,Z,z);return}if(Y.$claimed={...z},z.batchId!==void 0){if((await this.driver.findBatch?.(z.batchId,{progress:!1}))?.cancelledAt!=null){await this.driver.fail(z,{error:"Its batch was cancelled before it ran.",retryInMs:null,cancelled:!0});return}let K=this.batchHandle(z);Y.batch=K.batch,Y.$progress=K.progress}let $=await this.admit(Y,Z,z);if(!$)return;let X,H;try{H=await(Y.worker?d0(z.name,z.args):Y.run(...Z))}catch(B){X=B}finally{await $.done()}let G=Y.$outcome;if(X===void 0&&G?.kind==="release"){await this.driver.release(z,{retryInMs:Math.max(0,G.delayMs)});return}if(X===void 0&&G?.kind==="fail")X=G.error;let Q=G?.kind==="fail"?G.retry:!0;if(X===void 0)try{Y.onSuccess(H,...Z)}catch(B){X=B}if(X!==void 0){let B=String(X?.stack??X);if($0(`${z.name}.onFail`,()=>Y.onFail(X,...Z)),!Q||z.attempt>=Y.maxAttempts)$0(`${z.name}.onDeadletter`,()=>Y.onDeadletter(X,...Z)),await this.driver.fail(z,{error:B,retryInMs:null}),await this.releaseUnique(Y,Z,z);else await this.driver.fail(z,{error:B,retryInMs:s(Y.backoff,z.attempt)});return}await this.driver.complete(z),await this.releaseUnique(Y,Z,z)}batchHandle(z){let V=z.batchId,Y=this.driver;return{batch:{id:V,cancelled:async()=>(await Y.findBatch?.(V,{progress:!1}))?.cancelledAt!=null},progress:(Z)=>Y.reportProgress?.(z,Z)??Promise.resolve()}}async admit(z,V,Y){let Z=z.concurrency(...V),$=[z.throttle(...V)??[]].flat();if(!Z&&$.length===0)return{done:async()=>{}};let X=this.locks,H;if(Z&&Z.limit>0){let Q=this.config.visibilityTimeout;for(let B=0;B<Z.limit&&!H;B++)H=await X.acquire(`gemi:concurrency:${Z.key}:${B}`,{ttl:Q,renew:!0})??void 0;if(!H){await this.driver.release(Y,{retryInMs:Math.round(this.config.pollInterval*(1+Math.random()))});return}}let G=[];for(let Q of $){let B=`gemi:throttle:${Q.key}`,K=await X.store.hit(B,Q.limit,Q.window);if(!K.allowed){await Promise.all(G.map((A)=>X.store.refund(A))),await H?.release(),await this.driver.release(Y,{retryInMs:Math.max(1,K.resetInMs)});return}G.push(B)}return{done:async()=>{await H?.release().catch((Q)=>{console.error(`[gemi] Could not free a concurrency slot of ${Y.name}.`,Q)})}}}}function L0(z,V){return`gemi:job:${z}:${String(V)}`}function $0(z,V){try{V()}catch(Y){console.error(`${z} threw; the job's claim was ended anyway.`,Y)}}function i0(){return Bun.env.NODE_ENV==="production"}function s0(){if(!p0)return!1;if(a0())return!0;return process.env.ROOT_DIR!==void 0&&!n0()}function n0(z=process.env){return(z.GEMI_QUEUE_CLAIM??"").trim().toLowerCase()==="off"}var x0=Symbol.for("gemi.queue.worker");function cz(z=!0){globalThis[x0]=z}function a0(){return globalThis[x0]===!0}function r0(z,V){if(z==="memory")return new i;if(z==="database"||typeof z==="function"){if(!V&&(z==="database"||z.length>0))throw Error("The queue driver needs the application it belongs to, and this QueueManager was built without one. Pass { application }.");if(z==="database")return new z0(V.make(X0));return z(V)}if(typeof z==="string")throw Error(`Unknown queue driver "${z}". The queue slice's driver is "memory", "database", a QueueDriver, or a function returning one.`);return z}class S{static name="unset";worker=!1;maxAttempts=3;backoff=0;uniqueId(...z){return}uniqueFor=3600000;throttle(...z){return}concurrency(...z){return}release(z=0){this.$outcome={kind:"release",delayMs:z}}fail(z,V={}){this.$outcome={kind:"fail",error:z instanceof Error?z:Error(String(z)),retry:V.retry??!0}}batch=void 0;async progress(z){let V=E(z);await this.$progress?.(V)}$progress;$claimed;$outcome;run(...z){}onFail(z,...V){}onSuccess(z,...V){}onDeadletter(z,...V){}static dispatch(...z){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return m(h).push(this,JSON.stringify(z))}static dispatchBatch(z,V={}){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");return m(h).pushBatch(this,z.map((Y)=>JSON.stringify(Y)),V)}static with(...z){if(this.name==="unset")throw Error("Cannot use a job with no name as a callback");return JSON.stringify(z),{name:this.name,args:z}}static findBatch(z){return m(h).findBatch(z)}static cancelBatch(z){return m(h).cancelBatch(z)}}var r=["completed","failed","cancelled"],t0=1000;class H0{queue;registry={};storeInstance;tickClass;reportedNames=new Set;constructor(z){this.queue=z}get workflows(){return this.registry}use(z){this.registry={};for(let V of z){if(V.name==="unset"||!V.name){console.error("A workflow class has no `static name`, so it was not registered. Add one.");continue}if(this.registry[V.name]){console.error(`Two workflows are named "${V.name}" \u2014 the first is registered `+"and this one is not. A workflow's name is its key in storage. Rename one.");continue}this.registry[V.name]=V}}get tickJob(){return this.tickClass??=o0(this),this.tickClass}get store(){if(!this.storeInstance){let z=this.queue.driver.workflowStore?.();if(!z||!this.queue.driver.enqueueBatch)throw Error("This queue's driver does not support workflows. The memory and database drivers do.");this.storeInstance=z}return this.storeInstance}start(z,V){if(z.name==="unset"||!z.name)throw Error("Cannot start a workflow with no name");let Y=this.store,Z={id:Bun.randomUUIDv7(),name:z.name,args:u(V,`The arguments of ${z.name}`)??"[]"},$=()=>this.queue.claimSoon(),X=Y.joinsTransaction?.()===!0;if(!X){if(D(()=>Y.create(Z).then($,(B)=>{console.error(`[gemi] The queue could not record the workflow ${z.name}, which was held until its transaction committed. The transaction stays committed; the workflow did not start.`,B)})))return Promise.resolve(Z.id)}let H=Y.create(Z),G=X&&D($);return H.then(()=>{if(!G)$();return Z.id})}async signal(z,V,Y){if(typeof V!=="string"||V.length===0||V.length>191)throw TypeError("A signal key is a string of 1 to 191 characters.");let Z=u(Y,`The payload of signal "${V}"`),$=await this.store.update(z,{key:V},({workflow:X,step:H,now:G})=>{if(r.includes(X.status)||X.status==="cancelling")return{result:!1};if(!H)return{result:!0,step:{workflowId:z,key:V,status:"signalled",attempt:0,output:Z,error:null,batchId:null,wakeAt:null,startedAt:null,finishedAt:G,createdAt:G,updatedAt:G}};if(H.status!=="waiting")return{result:!1};return{result:!0,step:{...H,status:"signalled",output:Z,wakeAt:H.wakeAt,finishedAt:G},tick:{delayMs:0}}});if($)this.queue.claimSoon();return $===!0}async cancel(z){let V=await this.store.update(z,{allSteps:!0},({workflow:Y,steps:Z})=>{if(r.includes(Y.status)||Y.status==="cancelling")return{result:!1};return{result:!0,workflow:{status:"cancelling"},cancelBatches:Z.filter(($)=>$.status==="batching"&&$.batchId!==null).map(($)=>$.batchId),tick:{delayMs:0}}});if(V)this.queue.claimSoon();return V===!0}async find(z){let V=await this.store.find(z);if(!V)return null;let{workflow:Y,steps:Z}=V,$=[];try{$=JSON.parse(Y.args)}catch{}return{id:Y.id,name:Y.name,status:Y.status,args:$,currentStep:Y.currentStep,progress:Y.progress,result:e0(Y.result),error:Y.error,steps:await Promise.all(Z.map(async(X)=>{let H={key:X.key,status:X.status,attempt:X.attempt,error:X.error,batchId:X.batchId,wakeAt:X.wakeAt,startedAt:X.startedAt,finishedAt:X.finishedAt};if(X.batchId===null)return H;let G=await this.queue.driver.findBatch?.(X.batchId);return G?{...H,progress:G.progress}:H})),createdAt:Y.createdAt,updatedAt:Y.updatedAt}}async tick(z,V){let Y=this.store,Z=V.$claimed,$=Z?`${Z.id}:${Z.attempt}`:`${crypto.randomUUID()}:1`,X=Math.max(1,this.queue.config.visibilityTimeout),H=await Y.acquire(z,$,X);if(H.kind!=="acquired")return;let{workflow:G}=H,Q=(J={})=>Y.update(z,{owner:$},()=>({...J,result:void 0,unlock:!0})).then(()=>this.queue.claimSoon()).catch((P)=>{if(!(P instanceof R))throw P});if(r.includes(G.status))return Q();let B=this.registry[G.name];if(!B)return this.unknown(G,V,Q);let K;try{K=JSON.parse(G.args)}catch(J){return Q({workflow:{status:"failed",error:`The arguments are not JSON: ${a(J)}`}})}let A=setInterval(()=>{Y.renew(z,$,X).catch((J)=>{console.error(`[gemi] Could not extend the hold on workflow ${z}.`,J)})},Math.max(1,Math.floor(X/3)));A.unref?.();let U=G.status==="cancelling",F=new Z0({workflowId:z,owner:$,store:Y,steps:H.steps,cancelling:U,findBatch:(J)=>this.queue.driver.findBatch?.(J,{progress:!1})??Promise.resolve(null),buildBatch:(J,P,N)=>this.queue.buildBatch(J,P.map((C)=>JSON.stringify(C)),{name:N.name,allowFailures:N.allowFailures,finally:{name:I,args:[z]}}),scheduled:()=>this.queue.claimSoon(),cancelCheckMs:t0});try{let J;try{let P=new B,N=await(U?P.onCancel(F,...K):P.run(F,...K));J=F.suspension?{kind:"suspended"}:{kind:"completed",result:U?null:u(N,`The result of ${G.name}`)}}catch(P){if(J=F.suspension||P instanceof g?{kind:"suspended"}:{kind:"failed",error:a(P)},P instanceof R)F.lost=!0}if(await F.settled(),F.lost)return;if(J.kind==="completed"&&F.suspension)J={kind:"suspended"};await Y.update(z,{owner:$},({workflow:P,now:N})=>this.finish(P,J,F,U,N)),this.queue.claimSoon()}catch(J){if(J instanceof R)return;throw J}finally{clearInterval(A)}}finish(z,V,Y,Z,$){let X={result:void 0,unlock:!0};if(z.status==="cancelling"&&!Z)return{...X,tick:{delayMs:0}};if(V.kind==="completed")return{...X,workflow:Z?{status:"cancelled",currentStep:null,wakeAt:null}:{status:"completed",result:V.result,progress:1,currentStep:null,wakeAt:null,error:null}};if(V.kind==="failed")return{...X,workflow:{status:Z?"cancelled":"failed",error:V.error,wakeAt:null}};let H=Y.suspension??{status:"waiting",wakes:[]},G={...X,workflow:{status:Z?"cancelling":H.status,currentStep:Y.current??z.currentStep}};if(H.wakes.length>0){let Q=Math.min(...H.wakes);if(!(z.wakeAt!==null&&z.wakeAt>$&&z.wakeAt<=Q))G.tick={delayMs:Math.max(0,Q-$)},G.workflow.wakeAt=Q}return G}async unknown(z,V,Y){let Z=Date.now()-z.createdAt;if(this.queue.durable&&Z<this.queue.config.unknownJobGrace){if(!this.reportedNames.has(z.name))this.reportedNames.add(z.name),console.error(`Left workflow "${z.name}" for another replica: nothing is registered here under that name.`);await Y(),V.release(Math.round(this.queue.config.pollInterval*(1+Math.random())));return}console.error(`Failed workflow ${z.id}: nothing is registered under the name "${z.name}". If the class exists, it was not discovered: check that it is under the queue slice's workflowsDir (app/workflows by default), or list it in app/config/queue.ts.`),await Y({workflow:{status:"failed",error:`No workflow is registered under the name "${z.name}".`}})}tickDeadLettered(z,V){console.error(`[gemi] The tick of workflow ${z} was dead-lettered.`,V),this.store.update(z,{},({workflow:Y})=>r.includes(Y.status)?{result:void 0}:{result:void 0,workflow:{status:"failed",error:`Its tick job was dead-lettered: ${V.message}`},unlock:!0}).catch(()=>{})}}function o0(z){return class extends S{static name=I;maxAttempts=20;backoff=[1000,5000,15000,30000,60000];async run(Y){await z.tick(Y,this)}onDeadletter(Y,Z){z.tickDeadLettered(Z,Y)}}}function e0(z){try{return _(z)}catch{return z}}
414
414
  export{y as qd,p as rd,o as sd,U0 as td,z0 as ud,Az as vd,D0 as wd,V0 as xd,i as yd,I0 as zd,Y0 as Ad,E0 as Bd,O0 as Cd,Z0 as Dd,H0 as Ed,h as Fd,s0 as Gd,n0 as Hd,cz as Id,a0 as Jd,S as Kd};
415
415
 
416
- //# debugId=2B60606284AB66A864756E2164756E21
416
+ //# debugId=B94DC115D8A54A1F64756E2164756E21
@@ -18,6 +18,6 @@
18
18
  "import { deferUntilCommit } from \"../../../orm/context\";\nimport { Job } from \"../Job\";\nimport type { QueueManager } from \"../QueueManager\";\nimport {\n Step,\n WorkflowSuspended,\n decode,\n describe,\n encode,\n} from \"./Step\";\nimport type { WorkflowClass, WorkflowStatus } from \"./Workflow\";\nimport {\n WORKFLOW_TICK_JOB,\n type WorkflowChange,\n WorkflowLeaseLostError,\n type WorkflowRecord,\n type WorkflowRunStatus,\n type WorkflowStore,\n} from \"./WorkflowStore\";\n\nconst ENDED: readonly WorkflowRunStatus[] = [\"completed\", \"failed\", \"cancelled\"];\n\n/** How often a running `step.run` checks whether its workflow was cancelled. */\nconst CANCEL_CHECK_MS = 1000;\n\ntype Outcome =\n | { kind: \"completed\"; result: string | null }\n | { kind: \"failed\"; error: string }\n | { kind: \"suspended\" };\n\n/**\n * The queue's half of workflows: the registry of workflow classes, what\n * `Workflow.start`, `signal`, `find` and `cancel` do, and the tick.\n *\n * ### The tick\n *\n * A workflow advances only inside its tick job, which takes the workflow\n * from the store for a lease (the queue's `visibilityTimeout`, renewed while\n * it runs), runs one pass of `run`, and lets go with the outcome written in\n * the same step. Every write of the pass is fenced by that hold, so a tick\n * that lost it (it was too slow and another took over) changes nothing.\n *\n * A tick that finds the workflow held by another is dropped, after marking\n * the workflow so the holder enqueues a fresh tick when it lets go: a signal\n * that lands mid-pass is never lost, and two passes of one workflow never\n * overlap. A tick that failed or died holds the workflow under its job's id,\n * so its own retry takes it straight back.\n */\nexport class WorkflowRuntime {\n private registry: Record<string, WorkflowClass> = {};\n private storeInstance: WorkflowStore | undefined;\n private tickClass: (new () => Job) | undefined;\n private readonly reportedNames = new Set<string>();\n\n constructor(private readonly queue: QueueManager) {}\n\n /** The workflow classes this process can run, by `static name`. */\n get workflows(): Readonly<Record<string, WorkflowClass>> {\n return this.registry;\n }\n\n /** Replaces the registry. The first class to claim a name wins. */\n use(workflows: readonly WorkflowClass[]) {\n this.registry = {};\n for (const workflow of workflows) {\n if (workflow.name === \"unset\" || !workflow.name) {\n console.error(\n `A workflow class has no \\`static name\\`, so it was not registered. Add one.`,\n );\n continue;\n }\n if (this.registry[workflow.name]) {\n console.error(\n `Two workflows are named \"${workflow.name}\" — the first is registered ` +\n `and this one is not. A workflow's name is its key in storage. Rename one.`,\n );\n continue;\n }\n this.registry[workflow.name] = workflow;\n }\n }\n\n /** The internal job a workflow's passes run in, one class per manager. */\n get tickJob(): new () => Job {\n this.tickClass ??= tickJobFor(this);\n return this.tickClass;\n }\n\n get store(): WorkflowStore {\n if (!this.storeInstance) {\n const store = this.queue.driver.workflowStore?.();\n if (!store || !this.queue.driver.enqueueBatch) {\n throw new Error(\n `This queue's driver does not support workflows. The memory and ` +\n `database drivers do.`,\n );\n }\n this.storeInstance = store;\n }\n return this.storeInstance;\n }\n\n start(workflow: WorkflowClass, args: unknown[]): Promise<string> {\n if (workflow.name === \"unset\" || !workflow.name) {\n throw new Error(\"Cannot start a workflow with no name\");\n }\n const store = this.store;\n const record = {\n id: Bun.randomUUIDv7(),\n name: workflow.name,\n args: encode(args, `The arguments of ${workflow.name}`) ?? \"[]\",\n };\n const wake = () => this.queue.claimSoon();\n\n // As `QueueManager.push`: on the caller's transaction when the store\n // joins it, otherwise held until it commits.\n const joins = store.joinsTransaction?.() === true;\n if (!joins) {\n const held = deferUntilCommit(() =>\n store.create(record).then(wake, (error: unknown) => {\n console.error(\n `[gemi] The queue could not record the workflow ${workflow.name}, which ` +\n `was held until its transaction committed. The transaction stays ` +\n `committed; the workflow did not start.`,\n error,\n );\n }),\n );\n if (held) return Promise.resolve(record.id);\n }\n const written = store.create(record);\n const wakeAtCommit = joins && deferUntilCommit(wake);\n return written.then(() => {\n if (!wakeAtCommit) wake();\n return record.id;\n });\n }\n\n async signal(id: string, key: string, payload?: unknown): Promise<boolean> {\n if (typeof key !== \"string\" || key.length === 0 || key.length > 191) {\n throw new TypeError(`A signal key is a string of 1 to 191 characters.`);\n }\n const output = encode(payload, `The payload of signal \"${key}\"`);\n const taken = await this.store.update(id, { key }, ({ workflow, step, now }) => {\n if (ENDED.includes(workflow.status) || workflow.status === \"cancelling\") {\n return { result: false };\n }\n if (!step) {\n return {\n result: true,\n step: {\n workflowId: id,\n key,\n status: \"signalled\",\n attempt: 0,\n output,\n error: null,\n batchId: null,\n wakeAt: null,\n startedAt: null,\n finishedAt: now,\n createdAt: now,\n updatedAt: now,\n },\n };\n }\n if (step.status !== \"waiting\") return { result: false };\n return {\n result: true,\n step: { ...step, status: \"signalled\", output, wakeAt: step.wakeAt, finishedAt: now },\n tick: { delayMs: 0 },\n };\n });\n if (taken) this.queue.claimSoon();\n return taken === true;\n }\n\n async cancel(id: string): Promise<boolean> {\n const cancelled = await this.store.update(id, { allSteps: true }, ({ workflow, steps }) => {\n if (ENDED.includes(workflow.status) || workflow.status === \"cancelling\") {\n return { result: false };\n }\n return {\n result: true,\n workflow: { status: \"cancelling\" },\n cancelBatches: steps\n .filter((step) => step.status === \"batching\" && step.batchId !== null)\n .map((step) => step.batchId!),\n tick: { delayMs: 0 },\n };\n });\n if (cancelled) this.queue.claimSoon();\n return cancelled === true;\n }\n\n async find(id: string): Promise<WorkflowStatus | null> {\n const state = await this.store.find(id);\n if (!state) return null;\n const { workflow, steps } = state;\n let args: unknown[] = [];\n try {\n args = JSON.parse(workflow.args) as unknown[];\n } catch {}\n return {\n id: workflow.id,\n name: workflow.name,\n status: workflow.status,\n args,\n currentStep: workflow.currentStep,\n progress: workflow.progress,\n result: safeDecode(workflow.result),\n error: workflow.error,\n steps: await Promise.all(\n steps.map(async (step) => {\n const status = {\n key: step.key,\n status: step.status,\n attempt: step.attempt,\n error: step.error,\n batchId: step.batchId,\n wakeAt: step.wakeAt,\n startedAt: step.startedAt,\n finishedAt: step.finishedAt,\n };\n if (step.batchId === null) return status;\n const batch = await this.queue.driver.findBatch?.(step.batchId);\n return batch ? { ...status, progress: batch.progress } : status;\n }),\n ),\n createdAt: workflow.createdAt,\n updatedAt: workflow.updatedAt,\n };\n }\n\n /** One pass of the workflow `id`, run by its tick job. */\n async tick(id: string, job: Job): Promise<void> {\n const store = this.store;\n const claimed = job.$claimed;\n const owner = claimed\n ? `${claimed.id}:${claimed.attempt}`\n : `${crypto.randomUUID()}:1`;\n const lease = Math.max(1, this.queue.config.visibilityTimeout);\n const acquired = await store.acquire(id, owner, lease);\n if (acquired.kind !== \"acquired\") return;\n const { workflow } = acquired;\n\n const letGo = (change: Partial<WorkflowChange<undefined>> = {}) =>\n store\n .update(id, { owner }, () => ({ ...change, result: undefined, unlock: true }))\n .then(() => this.queue.claimSoon())\n .catch((error) => {\n if (!(error instanceof WorkflowLeaseLostError)) throw error;\n });\n\n if (ENDED.includes(workflow.status)) return letGo();\n\n const Class = this.registry[workflow.name];\n if (!Class) return this.unknown(workflow, job, letGo);\n\n let args: unknown[];\n try {\n args = JSON.parse(workflow.args) as unknown[];\n } catch (error) {\n return letGo({\n workflow: { status: \"failed\", error: `The arguments are not JSON: ${describe(error)}` },\n });\n }\n\n const renew = setInterval(\n () => {\n store.renew(id, owner, lease).catch((error) => {\n console.error(`[gemi] Could not extend the hold on workflow ${id}.`, error);\n });\n },\n Math.max(1, Math.floor(lease / 3)),\n );\n renew.unref?.();\n\n const cancelling = workflow.status === \"cancelling\";\n const step = new Step({\n workflowId: id,\n owner,\n store,\n steps: acquired.steps,\n cancelling,\n findBatch: (batchId) =>\n this.queue.driver.findBatch?.(batchId, { progress: false }) ?? Promise.resolve(null),\n buildBatch: (batchJob, tuples, options) =>\n this.queue.buildBatch(\n batchJob,\n tuples.map((tuple) => JSON.stringify(tuple)),\n {\n name: options.name,\n allowFailures: options.allowFailures,\n finally: { name: WORKFLOW_TICK_JOB, args: [id] },\n },\n ),\n scheduled: () => this.queue.claimSoon(),\n cancelCheckMs: CANCEL_CHECK_MS,\n });\n\n try {\n let outcome: Outcome;\n try {\n const instance = new Class();\n const value = await (cancelling\n ? instance.onCancel(step, ...args)\n : instance.run(step, ...args));\n outcome = step.suspension\n ? { kind: \"suspended\" }\n : {\n kind: \"completed\",\n result: cancelling ? null : encode(value, `The result of ${workflow.name}`),\n };\n } catch (error) {\n outcome =\n step.suspension || error instanceof WorkflowSuspended\n ? { kind: \"suspended\" }\n : { kind: \"failed\", error: describe(error) };\n if (error instanceof WorkflowLeaseLostError) step.lost = true;\n }\n // A step the code did not await (or one that ran beside a sleep in a\n // `Promise.all`) is still writing; it finishes inside this pass.\n await step.settled();\n if (step.lost) return;\n // One of those suspended the workflow after `run` had returned: it is\n // not done until that step is.\n if (outcome.kind === \"completed\" && step.suspension) outcome = { kind: \"suspended\" };\n\n await store.update(id, { owner }, ({ workflow: current, now }) =>\n this.finish(current, outcome, step, cancelling, now),\n );\n this.queue.claimSoon();\n } catch (error) {\n if (error instanceof WorkflowLeaseLostError) return;\n throw error;\n } finally {\n clearInterval(renew);\n }\n }\n\n /** The tick's last write: the pass's outcome, and letting go. */\n private finish(\n current: WorkflowRecord,\n outcome: Outcome,\n step: Step,\n cancelling: boolean,\n now: number,\n ): WorkflowChange<undefined> {\n const change: WorkflowChange<undefined> = { result: undefined, unlock: true };\n\n // Cancelled during this pass of `run`: `onCancel` is next, whatever the\n // pass came to.\n if (current.status === \"cancelling\" && !cancelling) {\n return { ...change, tick: { delayMs: 0 } };\n }\n\n if (outcome.kind === \"completed\") {\n return {\n ...change,\n workflow: cancelling\n ? { status: \"cancelled\", currentStep: null, wakeAt: null }\n : {\n status: \"completed\",\n result: outcome.result,\n progress: 1,\n currentStep: null,\n wakeAt: null,\n error: null,\n },\n };\n }\n if (outcome.kind === \"failed\") {\n return {\n ...change,\n workflow: { status: cancelling ? \"cancelled\" : \"failed\", error: outcome.error, wakeAt: null },\n };\n }\n\n const suspension = step.suspension ?? { status: \"waiting\" as const, wakes: [] };\n const next: WorkflowChange<undefined> = {\n ...change,\n workflow: {\n status: cancelling ? \"cancelling\" : suspension.status,\n currentStep: step.current ?? current.currentStep,\n },\n };\n if (suspension.wakes.length > 0) {\n const wakeAt = Math.min(...suspension.wakes);\n // A tick already scheduled no later than this one wakes the workflow\n // in time, and schedules this one itself; a second would only run the\n // pass twice.\n const scheduled =\n current.wakeAt !== null && current.wakeAt > now && current.wakeAt <= wakeAt;\n if (!scheduled) {\n next.tick = { delayMs: Math.max(0, wakeAt - now) };\n next.workflow!.wakeAt = wakeAt;\n }\n }\n return next;\n }\n\n /**\n * A tick for a workflow this process has no class for. During a\n * blue/green ramp that is usually one only the other release has, so on a\n * shared driver it goes back for another replica until `unknownJobGrace`\n * has passed since the workflow started; then it fails.\n */\n private async unknown(\n workflow: WorkflowRecord,\n job: Job,\n letGo: (change?: Partial<WorkflowChange<undefined>>) => Promise<void>,\n ) {\n const age = Date.now() - workflow.createdAt;\n if (this.queue.durable && age < this.queue.config.unknownJobGrace) {\n if (!this.reportedNames.has(workflow.name)) {\n this.reportedNames.add(workflow.name);\n console.error(\n `Left workflow \"${workflow.name}\" for another replica: nothing is ` +\n `registered here under that name.`,\n );\n }\n await letGo();\n job.release(Math.round(this.queue.config.pollInterval * (1 + Math.random())));\n return;\n }\n console.error(\n `Failed workflow ${workflow.id}: nothing is registered under the name ` +\n `\"${workflow.name}\". If the class exists, it was not discovered: check ` +\n `that it is under the queue slice's workflowsDir (app/workflows by ` +\n `default), or list it in app/config/queue.ts.`,\n );\n await letGo({\n workflow: {\n status: \"failed\",\n error: `No workflow is registered under the name \"${workflow.name}\".`,\n },\n });\n }\n\n /**\n * The tick job ran out of attempts, which only a store that stayed\n * unreachable causes. Fails the workflow if it still can, so it does not\n * sit in `running` with nothing left to advance it.\n */\n /** @internal */\n tickDeadLettered(id: string, error: Error) {\n console.error(`[gemi] The tick of workflow ${id} was dead-lettered.`, error);\n void this.store\n .update(id, {}, ({ workflow }) =>\n ENDED.includes(workflow.status)\n ? { result: undefined }\n : {\n result: undefined,\n workflow: {\n status: \"failed\",\n error: `Its tick job was dead-lettered: ${error.message}`,\n },\n unlock: true,\n },\n )\n .catch(() => {});\n }\n}\n\n/** The internal job a workflow's passes run in, bound to one runtime. */\nfunction tickJobFor(runtime: WorkflowRuntime): new () => Job {\n return class WorkflowTickJob extends Job {\n static name = WORKFLOW_TICK_JOB;\n // A tick fails only when the store cannot be reached (a workflow's own\n // errors are recorded, not thrown), so it keeps trying for a while rather\n // than leaving the workflow stuck.\n maxAttempts = 20;\n backoff = [1000, 5000, 15000, 30000, 60000];\n async run(id: string) {\n await runtime.tick(id, this);\n }\n onDeadletter(error: Error, id: string) {\n runtime.tickDeadLettered(id, error);\n }\n };\n}\n\nfunction safeDecode(output: string | null): unknown {\n try {\n return decode(output);\n } catch {\n return output;\n }\n}\n"
19
19
  ],
20
20
  "mappings": ";6VAuCO,AAAM,LAAuC,LACzC,AACQ,FACA,QACA,WACA,YACT,WAER,WAAW,CACT,EAEA,EAAoC,CAAC,E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1,5 @@
1
1
  // @bun
2
2
  class K extends Error{lock;token;constructor(x,z,C="its lease ran out or another holder took it"){super(`Lost the lock "${x}" (token ${z}): ${C}.`);this.lock=x;this.token=z;this.name="LockLostError"}}var X=60000,Y=100,Z=(x)=>new Promise((z)=>setTimeout(z,x));class V{store;name;owner;token;ttl;lost;controller=new AbortController;deadline;expiryTimer;renewTimer;done=!1;constructor(x,z,C,B,G,J){this.store=x;this.name=z;this.owner=C;this.token=B;this.ttl=G;this.lost=this.controller.signal,this.deadline=J+G,this.armExpiry()}get expired(){return this.lost.aborted||performance.now()>=this.deadline}async extend(x=this.ttl){if(this.lost.aborted)return!1;let z=performance.now();if(!await this.store.extend(this.name,this.owner,this.token,x))return this.markLost(),!1;if(this.done)return!0;return this.deadline=Math.max(this.deadline,z+x),this.armExpiry(),!0}async isHeld(){if(this.lost.aborted)return!1;let x=await this.store.held(this.name,this.owner,this.token);if(!x)this.markLost();return x}async fence(x){if(this.lost.aborted)throw new K(this.name,this.token);try{return await this.store.fence(this.name,this.owner,this.token,x)}catch(z){if(z instanceof K)this.markLost();throw z}}async release(){if(this.stop(),this.lost.aborted)return!1;return this.store.release(this.name,this.owner,this.token)}startRenewing(){if(this.renewTimer||this.done)return;this.renewTimer=setInterval(()=>{this.extend().catch((x)=>{console.error(`[gemi] Could not renew the lock "${this.name}".`,x)})},Math.max(1,Math.floor(this.ttl/3))),this.renewTimer.unref?.()}markLost(x){if(this.stop(),!this.lost.aborted)this.controller.abort(new K(this.name,this.token,x))}stop(){this.done=!0,clearInterval(this.renewTimer),clearTimeout(this.expiryTimer),this.renewTimer=void 0,this.expiryTimer=void 0}armExpiry(){clearTimeout(this.expiryTimer),this.expiryTimer=setTimeout(()=>this.markLost("its lease ran out before it was renewed"),Math.max(0,this.deadline-performance.now())),this.expiryTimer.unref?.()}}class ${store;static token="locks";constructor(x){this.store=x}async acquire(x,z={}){let C=z.ttl??X;if(!(C>0))throw Error(`A lock's ttl must be a positive number of milliseconds; got ${C}.`);let B=Bun.randomUUIDv7(),G=performance.now()+Math.max(0,z.wait??0);for(;;){let J=performance.now(),M=await this.store.acquire(x,B,C);if(M!==null){let Q=new V(this.store,x,B,M,C,J);if(z.renew)Q.startRenewing();return Q}let O=G-performance.now();if(O<=0)return null;await Z(Math.min(Y,O))}}async run(x,z,C){let B=await this.acquire(x,{...z,renew:z.renew??!0});if(!B)return{acquired:!1};let G;try{G=await C(B)}catch(J){throw await B.release().catch(()=>{}),J}if(B.expired)throw B.markLost(),B.lost.reason;return await B.release(),{acquired:!0,value:G}}}var j={ms:1,s:1000,m:60000,h:3600000,d:86400000,w:604800000};function P(x){if(typeof x==="number"){if(!Number.isFinite(x)||x<0)throw TypeError(`A duration is 0 or more milliseconds; got ${x}.`);return Math.round(x)}let z=/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)\s*$/.exec(String(x));if(!z)throw TypeError(`"${String(x)}" is not a duration. Use milliseconds, or a number and one of ms, s, m, h, d, w ("30s", "7d").`);return Math.round(Number(z[1])*j[z[2]])}
3
- export{P as xj,K as yj,V as zj,$ as Aj};
3
+ export{P as yj,K as zj,V as Aj,$ as Bj};
4
4
 
5
- //# debugId=0F71B4DDAE66F24A64756E2164756E21
5
+ //# debugId=A8B9140A76F6F2F964756E2164756E21
@@ -7,6 +7,6 @@
7
7
  "/**\n * A length of time: milliseconds as a number, or a number and a unit, such as\n * `\"500ms\"`, `\"30s\"`, `\"5m\"`, `\"2h\"`, `\"7d\"` or `\"1w\"`.\n */\nexport type Duration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\" | \"d\" | \"w\"}`;\n\nconst UNITS: Record<string, number> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 60 * 60_000,\n d: 24 * 60 * 60_000,\n w: 7 * 24 * 60 * 60_000,\n};\n\n/** A `Duration` in milliseconds. Throws for anything else, on the caller's stack. */\nexport function toMilliseconds(duration: Duration): number {\n if (typeof duration === \"number\") {\n if (!Number.isFinite(duration) || duration < 0) {\n throw new TypeError(`A duration is 0 or more milliseconds; got ${duration}.`);\n }\n return Math.round(duration);\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h|d|w)\\s*$/.exec(String(duration));\n if (!match) {\n throw new TypeError(\n `\"${String(duration)}\" is not a duration. Use milliseconds, or a number and ` +\n `one of ms, s, m, h, d, w (\"30s\", \"7d\").`,\n );\n }\n return Math.round(Number(match[1]) * UNITS[match[2]!]!);\n}\n"
8
8
  ],
9
9
  "mappings": ";AAwFO,MAAM,UAAsB,KAAM,CAE5B,KACA,MAFX,WAAW,CACA,EACA,EACT,EAAS,8CACT,CACA,MAAM,kBAAkB,aAAgB,OAAW,IAAS,EAJnD,YACA,aAIT,KAAK,KAAO,gBAEhB,CC9EA,IAAM,EAAc,MACd,EAAY,IAEZ,EAAQ,CAAC,IAAe,IAAI,QAAQ,CAAC,IAAY,WAAW,EAAS,CAAE,CAAC,EAgBvE,MAAM,CAAS,CASD,MACR,KACA,MACA,MACA,IAZF,KACQ,WAAa,IAAI,gBAC1B,SACA,YACA,WACA,KAAO,GAEf,WAAW,CACQ,EACR,EACA,EACA,EACA,EACT,EACA,CANiB,aACR,YACA,aACA,aACA,WAGT,KAAK,KAAO,KAAK,WAAW,OAC5B,KAAK,SAAW,EAAc,EAC9B,KAAK,UAAU,KAIb,QAAO,EAAY,CACrB,OAAO,KAAK,KAAK,SAAW,YAAY,IAAI,GAAK,KAAK,cAIlD,OAAM,CAAC,EAAM,KAAK,IAAuB,CAC7C,GAAI,KAAK,KAAK,QAAS,MAAO,GAC9B,IAAM,EAAc,YAAY,IAAI,EAEpC,GAAI,CADO,MAAM,KAAK,MAAM,OAAO,KAAK,KAAM,KAAK,MAAO,KAAK,MAAO,CAAG,EAGvE,OADA,KAAK,SAAS,EACP,GAET,GAAI,KAAK,KAAM,MAAO,GAGtB,OAFA,KAAK,SAAW,KAAK,IAAI,KAAK,SAAU,EAAc,CAAG,EACzD,KAAK,UAAU,EACR,QAI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EAAG,SACH,EAAG,SACL,EAGO,SAAS,CAAc,CAAC,EAA4B,CACzD,GAAI,OAAO,IAAa,SAAU,CAChC,GAAI,CAAC,OAAO,SAAS,CAAQ,GAAK,EAAW,EAC3C,MAAU,UAAU,6CAA6C,IAAW,EAE9E,OAAO,KAAK,MAAM,CAAQ,EAE5B,IAAM,EAAQ,2CAA2C,KAAK,OAAO,CAAQ,CAAC,EAC9E,GAAI,CAAC,EACH,MAAU,UACR,IAAI,OAAO,CAAQ,iGAErB,EAEF,OAAO,KAAK,MAAM,OAAO,EAAM,EAAE,EAAI,EAAM,EAAM,GAAK",
10
- "debugId": "0F71B4DDAE66F24A64756E2164756E21",
10
+ "debugId": "A8B9140A76F6F2F964756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$i as m,_i as g,tj as k}from"./chunk-mym7egdq.js";import{Fk as p}from"./chunk-35zw2s61.js";import{bl as n}from"./chunk-aprjvzrz.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 Ii,S as Ji,_ as Ki,x as Li,b as Mi,Y as Ni,U as Oi,N as Pi,T as Qi,Mq as Ri,c as Si,Nq as Ti,Vq as Ui,Lq as Vi,Yq as Wi,$q as Xi,Xq as Yi};
2
+ import{$i as g,aj as m,uj as k}from"./chunk-vnw91fe1.js";import{Gk as p}from"./chunk-jx2mgvvt.js";import{cl as n}from"./chunk-rnp5k8m3.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 Ji,S as Ki,_ as Li,x as Mi,b as Ni,Y as Oi,U as Pi,N as Qi,T as Ri,Mq as Si,c as Ti,Nq as Ui,Vq as Vi,Lq as Wi,Yq as Xi,$q as Yi,Xq as Zi};
4
4
 
5
- //# debugId=A727D3F21B08977C64756E2164756E21
5
+ //# debugId=502B6BBC39CFD4E564756E2164756E21
@@ -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,CAC3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pC,MAAO,EAAO,CACd,GAAI,aAAiB,EACnB,EAAM,OAAS,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": "A727D3F21B08977C64756E2164756E21",
10
+ "debugId": "502B6BBC39CFD4E564756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Vj as Y,ak as K,dk as y}from"./chunk-e4ay1vg9.js";import{AsyncLocalStorage as U}from"async_hooks";var z=new U;function O(){return z.getStore()?.tx}function _(){return z.getStore()?.connection??K}function h(j,q){let v=z.getStore();if(_()===j)return q();return F(j),z.run({...v,depth:v?.depth??0,connection:j===K?void 0:j},q)}function F(j){let q=z.getStore();if(q?.tx===void 0)return;let v=q.connection??K;if(v===j)return;throw new y(v,j)}function A(j){let q=z.getStore();if(q?.tx===void 0||q.afterCommit===void 0)return!1;let v=Z.get(q.afterCommit);if(v==="committed")return!1;if(v==="rolled_back")return!0;return q.afterCommit.push(j),!0}var Z=new WeakMap;function k(j){if(A(j))return Promise.resolve();let q=(v)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",v)};try{return Promise.resolve(j()).catch(q)}catch(v){return q(v),Promise.resolve()}}function N(j){let q=z.getStore();if(q?.tx===void 0||q.commitDependsOn===void 0)return!1;return q.commitDependsOn.push(j),!0}class I extends Error{constructor(j){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${j instanceof Error?j.message:String(j)}`,{cause:j});this.name="TransactionDependencyError"}}async function W(j,q){if(j.length===q)return;let B=(await Promise.allSettled(j.slice(q))).find((J)=>J.status==="rejected");if(B)throw new I(B.reason)}function T(){let j=z.getStore();return j?.tx===void 0?null:j.depth}function x(){return z.getStore()?.system===!0}function p(j){let q=z.getStore();return z.run({...q,depth:q?.depth??0,system:!0},j)}function f(j){return z.getStore()?.trashed?.get(j)}function C(j,q,v){let B=z.getStore(),J=new Map(B?.trashed);return J.set(j,q),z.run({...B,depth:B?.depth??0,trashed:J},v)}function l(){return z.getStore()?.actor}function u(j,q){let v=z.getStore();return z.run({...v,depth:v?.depth??0,system:!1,actor:{user:j??null}},q)}function D(j){if(Bun.env.NODE_ENV!=="development")return null;if(j===!1)return null;if(j===void 0)return Y;if(!Number.isFinite(j)||j<=0)return Y;return j}function w(j){let q=D(j);if(q===null)return()=>{};let v=Error("transaction opened here"),B=setTimeout(()=>{let J=v.stack?.split(`
2
+ import{Wj as Y,bk as K,ek as y}from"./chunk-65j32dtn.js";import{AsyncLocalStorage as U}from"async_hooks";var z=new U;function O(){return z.getStore()?.tx}function _(){return z.getStore()?.connection??K}function h(j,q){let v=z.getStore();if(_()===j)return q();return F(j),z.run({...v,depth:v?.depth??0,connection:j===K?void 0:j},q)}function F(j){let q=z.getStore();if(q?.tx===void 0)return;let v=q.connection??K;if(v===j)return;throw new y(v,j)}function A(j){let q=z.getStore();if(q?.tx===void 0||q.afterCommit===void 0)return!1;let v=Z.get(q.afterCommit);if(v==="committed")return!1;if(v==="rolled_back")return!0;return q.afterCommit.push(j),!0}var Z=new WeakMap;function k(j){if(A(j))return Promise.resolve();let q=(v)=>{console.error("An after-commit callback threw. No transaction was open, so it ran immediately.",v)};try{return Promise.resolve(j()).catch(q)}catch(v){return q(v),Promise.resolve()}}function N(j){let q=z.getStore();if(q?.tx===void 0||q.commitDependsOn===void 0)return!1;return q.commitDependsOn.push(j),!0}class I extends Error{constructor(j){super(`A statement this transaction depended on failed after being issued on it, so the transaction rolled back instead of committing: ${j instanceof Error?j.message:String(j)}`,{cause:j});this.name="TransactionDependencyError"}}async function W(j,q){if(j.length===q)return;let B=(await Promise.allSettled(j.slice(q))).find((J)=>J.status==="rejected");if(B)throw new I(B.reason)}function T(){let j=z.getStore();return j?.tx===void 0?null:j.depth}function x(){return z.getStore()?.system===!0}function p(j){let q=z.getStore();return z.run({...q,depth:q?.depth??0,system:!0},j)}function f(j){return z.getStore()?.trashed?.get(j)}function C(j,q,v){let B=z.getStore(),J=new Map(B?.trashed);return J.set(j,q),z.run({...B,depth:B?.depth??0,trashed:J},v)}function l(){return z.getStore()?.actor}function u(j,q){let v=z.getStore();return z.run({...v,depth:v?.depth??0,system:!1,actor:{user:j??null}},q)}function D(j){if(Bun.env.NODE_ENV!=="development")return null;if(j===!1)return null;if(j===void 0)return Y;if(!Number.isFinite(j)||j<=0)return Y;return j}function w(j){let q=D(j);if(q===null)return()=>{};let v=Error("transaction opened here"),B=setTimeout(()=>{let J=v.stack?.split(`
3
3
  `).slice(1).join(`
4
4
  `)??"";console.warn(`[gemi] A database transaction has not settled after ${q}ms. It `+"reserves a pooled connection until it does \u2014 check for network or "+`filesystem I/O inside the callback, and move it outside the transaction if you find any.
5
5
  ${J}
6
6
  (development only; set database.slowTransactionThreshold to change the threshold, or false to switch this off)`)},q);return B.unref?.(),()=>clearTimeout(B)}async function L(j,q){if(j.length===0)return;await z.run({...q,tx:void 0,afterCommit:void 0,commitDependsOn:void 0,depth:q?.depth??0},async()=>{for(let v of j)try{await v()}catch(B){console.error("An after-commit callback threw. The transaction it was waiting on had already committed and stays committed, and the callbacks after it still ran.",B)}})}function m(j,q,v){let B=z.getStore(),J=v?.connection??K;if(F(J),B?.tx){let G=B.afterCommit,V=G?.length??0,P=B.commitDependsOn,H=P?.length??0;return B.tx.savepoint((X)=>{let R=X;return z.run({...B,tx:R,depth:B.depth+1},async()=>{let S=await q(R);if(P)await W(P,H);return S})}).catch((X)=>{if(G)G.length=V;if(P)P.length=H;throw X})}let $=w(v?.slowTransactionThreshold),Q=[],M=[];try{return j.begin((G)=>z.run({...B,tx:G,depth:0,connection:J===K?void 0:J,afterCommit:Q,commitDependsOn:M},async()=>{let V=await q(G);return await W(M,0),V})).finally($).then(async(G)=>{return Z.set(Q,"committed"),await L(Q,B),G},(G)=>{throw Z.set(Q,"rolled_back"),G})}catch(G){throw $(),G}}
7
- export{z as Cj,O as Dj,_ as Ej,h as Fj,F as Gj,A as Hj,k as Ij,N as Jj,I as Kj,T as Lj,x as Mj,p as Nj,f as Oj,C as Pj,l as Qj,u as Rj,m as Sj};
7
+ export{z as Dj,O as Ej,_ as Fj,h as Gj,F as Hj,A as Ij,k as Jj,N as Kj,I as Lj,T as Mj,x as Nj,p as Oj,f as Pj,C as Qj,l as Rj,u as Sj,m as Tj};
8
8
 
9
- //# debugId=72A39AB99139A6E564756E2164756E21
9
+ //# debugId=621A8F281B40B30164756E2164756E21
@@ -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,CA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