gemi 0.225.0 → 0.225.2

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 (223) hide show
  1. package/dist/ai/Agent.d.ts +2 -0
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/index.js +2 -2
  4. package/dist/ai/index.js.map +1 -1
  5. package/dist/ai/providers/anthropicStream.d.ts +6 -0
  6. package/dist/ai/providers/anthropicStream.d.ts.map +1 -1
  7. package/dist/ai/providers/call.d.ts +15 -0
  8. package/dist/ai/providers/call.d.ts.map +1 -1
  9. package/dist/ai/providers/endpoints.d.ts +25 -0
  10. package/dist/ai/providers/endpoints.d.ts.map +1 -1
  11. package/dist/ai/providers/errors.d.ts +12 -0
  12. package/dist/ai/providers/errors.d.ts.map +1 -1
  13. package/dist/ai/providers/stream.d.ts +3 -0
  14. package/dist/ai/providers/stream.d.ts.map +1 -1
  15. package/dist/ai/testing/index.js +2 -2
  16. package/dist/ai/testing/index.js.map +2 -2
  17. package/dist/ai/types.d.ts +6 -0
  18. package/dist/ai/types.d.ts.map +1 -1
  19. package/dist/app/index.js +1 -1
  20. package/dist/bun/plugin.js +1 -1
  21. package/dist/bun/preload.js +1 -1
  22. package/dist/{chunk-p1ern8r4.js → chunk-1jyzg1ex.js} +3 -3
  23. package/dist/{chunk-p1ern8r4.js.map → chunk-1jyzg1ex.js.map} +1 -1
  24. package/dist/{chunk-97tj0d7v.js → chunk-21hhvphe.js} +2 -2
  25. package/dist/{chunk-97tj0d7v.js.map → chunk-21hhvphe.js.map} +1 -1
  26. package/dist/{chunk-zmt5kdpb.js → chunk-2450kxym.js} +2 -2
  27. package/dist/{chunk-zmt5kdpb.js.map → chunk-2450kxym.js.map} +1 -1
  28. package/dist/{chunk-vmmjq9fn.js → chunk-3dkaz47e.js} +2 -2
  29. package/dist/{chunk-vmmjq9fn.js.map → chunk-3dkaz47e.js.map} +1 -1
  30. package/dist/{chunk-bqm79ar0.js → chunk-3e55yw7v.js} +3 -3
  31. package/dist/{chunk-bqm79ar0.js.map → chunk-3e55yw7v.js.map} +1 -1
  32. package/dist/chunk-3vgjrn2r.js +12 -0
  33. package/dist/{chunk-dpmvvwts.js.map → chunk-3vgjrn2r.js.map} +6 -6
  34. package/dist/{chunk-snmyjq03.js → chunk-40yd1n60.js} +2 -2
  35. package/dist/{chunk-snmyjq03.js.map → chunk-40yd1n60.js.map} +1 -1
  36. package/dist/{chunk-6ttbhhnn.js → chunk-421hq1rw.js} +1 -1
  37. package/dist/{chunk-k16phdjv.js → chunk-4qyp7w89.js} +1 -1
  38. package/dist/{chunk-j9abwrkv.js → chunk-5kgqfczk.js} +3 -3
  39. package/dist/{chunk-j9abwrkv.js.map → chunk-5kgqfczk.js.map} +1 -1
  40. package/dist/{chunk-wy82t7mz.js → chunk-64yf0shq.js} +2 -2
  41. package/dist/{chunk-wy82t7mz.js.map → chunk-64yf0shq.js.map} +1 -1
  42. package/dist/{chunk-8a3fqcf0.js → chunk-6et7jwp8.js} +2 -2
  43. package/dist/{chunk-8a3fqcf0.js.map → chunk-6et7jwp8.js.map} +1 -1
  44. package/dist/{chunk-0k2r6bep.js → chunk-6h1hjzj7.js} +2 -2
  45. package/dist/{chunk-0k2r6bep.js.map → chunk-6h1hjzj7.js.map} +1 -1
  46. package/dist/{chunk-nzd7z4s6.js → chunk-70jhw0ft.js} +1 -1
  47. package/dist/{chunk-b87wvmsz.js → chunk-7901z26g.js} +2 -2
  48. package/dist/{chunk-b87wvmsz.js.map → chunk-7901z26g.js.map} +1 -1
  49. package/dist/{chunk-sfrjkysf.js → chunk-7d1f5gyv.js} +2 -2
  50. package/dist/{chunk-sfrjkysf.js.map → chunk-7d1f5gyv.js.map} +1 -1
  51. package/dist/{chunk-50791bmz.js → chunk-7mvfk0q9.js} +2 -2
  52. package/dist/{chunk-50791bmz.js.map → chunk-7mvfk0q9.js.map} +1 -1
  53. package/dist/{chunk-4wh4dfgf.js → chunk-81y96dax.js} +1 -1
  54. package/dist/{chunk-2vv04thj.js → chunk-8pdke84p.js} +2 -2
  55. package/dist/{chunk-2vv04thj.js.map → chunk-8pdke84p.js.map} +1 -1
  56. package/dist/{chunk-h9nt7hm6.js → chunk-8szsd6vy.js} +2 -2
  57. package/dist/{chunk-h9nt7hm6.js.map → chunk-8szsd6vy.js.map} +1 -1
  58. package/dist/{chunk-t8ygf6zj.js → chunk-9xxgj5zk.js} +3 -3
  59. package/dist/{chunk-t8ygf6zj.js.map → chunk-9xxgj5zk.js.map} +1 -1
  60. package/dist/{chunk-8pz8yzax.js → chunk-9znec0we.js} +4 -4
  61. package/dist/{chunk-8pz8yzax.js.map → chunk-9znec0we.js.map} +3 -3
  62. package/dist/{chunk-3dkv4989.js → chunk-ads3c8m0.js} +2 -2
  63. package/dist/{chunk-3dkv4989.js.map → chunk-ads3c8m0.js.map} +1 -1
  64. package/dist/{chunk-fqhkkpq3.js → chunk-awryyak8.js} +2 -2
  65. package/dist/{chunk-fqhkkpq3.js.map → chunk-awryyak8.js.map} +1 -1
  66. package/dist/{chunk-5jvbr0e5.js → chunk-bch7xbsr.js} +2 -2
  67. package/dist/{chunk-5jvbr0e5.js.map → chunk-bch7xbsr.js.map} +1 -1
  68. package/dist/{chunk-3y91vexx.js → chunk-bwjaq694.js} +3 -3
  69. package/dist/{chunk-3y91vexx.js.map → chunk-bwjaq694.js.map} +1 -1
  70. package/dist/chunk-bzrta2sw.js +10 -0
  71. package/dist/{chunk-qs2xvc8g.js.map → chunk-bzrta2sw.js.map} +9 -4
  72. package/dist/{chunk-4v5nwqw6.js → chunk-crk4ddqa.js} +3 -3
  73. package/dist/{chunk-4v5nwqw6.js.map → chunk-crk4ddqa.js.map} +1 -1
  74. package/dist/{chunk-37209psn.js → chunk-d3a29hyg.js} +3 -3
  75. package/dist/{chunk-37209psn.js.map → chunk-d3a29hyg.js.map} +1 -1
  76. package/dist/{chunk-knfvx96p.js → chunk-ehr5pnm8.js} +2 -2
  77. package/dist/{chunk-knfvx96p.js.map → chunk-ehr5pnm8.js.map} +1 -1
  78. package/dist/{chunk-yj7pbbnm.js → chunk-enqrjcdk.js} +2 -2
  79. package/dist/{chunk-yj7pbbnm.js.map → chunk-enqrjcdk.js.map} +1 -1
  80. package/dist/{chunk-adw279ge.js → chunk-eydww2nn.js} +2 -2
  81. package/dist/{chunk-adw279ge.js.map → chunk-eydww2nn.js.map} +1 -1
  82. package/dist/{chunk-fxa72ppw.js → chunk-fjnhqbtx.js} +1 -1
  83. package/dist/{chunk-726gd69z.js → chunk-ftc9292d.js} +2 -2
  84. package/dist/{chunk-726gd69z.js.map → chunk-ftc9292d.js.map} +1 -1
  85. package/dist/{chunk-pxjptskr.js → chunk-gj0bwm41.js} +2 -2
  86. package/dist/{chunk-pxjptskr.js.map → chunk-gj0bwm41.js.map} +1 -1
  87. package/dist/{chunk-5mrtgr7q.js → chunk-hvyzp9p6.js} +2 -2
  88. package/dist/{chunk-5mrtgr7q.js.map → chunk-hvyzp9p6.js.map} +1 -1
  89. package/dist/{chunk-8vpe54ek.js → chunk-j0rhz378.js} +2 -2
  90. package/dist/{chunk-8vpe54ek.js.map → chunk-j0rhz378.js.map} +1 -1
  91. package/dist/{chunk-swmf6w3z.js → chunk-j13jmjkr.js} +2 -2
  92. package/dist/{chunk-swmf6w3z.js.map → chunk-j13jmjkr.js.map} +1 -1
  93. package/dist/{chunk-anc5v266.js → chunk-j7pzdvxr.js} +2 -2
  94. package/dist/{chunk-anc5v266.js.map → chunk-j7pzdvxr.js.map} +1 -1
  95. package/dist/{chunk-h1wmpa03.js → chunk-ja3n968b.js} +2 -2
  96. package/dist/{chunk-h1wmpa03.js.map → chunk-ja3n968b.js.map} +1 -1
  97. package/dist/{chunk-vcw98sp6.js → chunk-k657v3ed.js} +3 -3
  98. package/dist/{chunk-vcw98sp6.js.map → chunk-k657v3ed.js.map} +1 -1
  99. package/dist/{chunk-t586p2g2.js → chunk-kxc2mzzr.js} +2 -2
  100. package/dist/{chunk-t586p2g2.js.map → chunk-kxc2mzzr.js.map} +1 -1
  101. package/dist/{chunk-nqqyn3cx.js → chunk-kzz2nfzf.js} +2 -2
  102. package/dist/{chunk-nqqyn3cx.js.map → chunk-kzz2nfzf.js.map} +1 -1
  103. package/dist/{chunk-k6af7qek.js → chunk-m7v4erdg.js} +2 -2
  104. package/dist/{chunk-k6af7qek.js.map → chunk-m7v4erdg.js.map} +1 -1
  105. package/dist/{chunk-p4v71qfx.js → chunk-mca5s0bf.js} +3 -3
  106. package/dist/{chunk-p4v71qfx.js.map → chunk-mca5s0bf.js.map} +1 -1
  107. package/dist/{chunk-79wjkaa4.js → chunk-me70vszk.js} +2 -2
  108. package/dist/{chunk-79wjkaa4.js.map → chunk-me70vszk.js.map} +1 -1
  109. package/dist/{chunk-qy0k2s5f.js → chunk-mvb8m247.js} +2 -2
  110. package/dist/{chunk-qy0k2s5f.js.map → chunk-mvb8m247.js.map} +1 -1
  111. package/dist/{chunk-0av1gyns.js → chunk-mvp6fkg2.js} +3 -3
  112. package/dist/{chunk-0av1gyns.js.map → chunk-mvp6fkg2.js.map} +1 -1
  113. package/dist/{chunk-e4zxacxd.js → chunk-n2c748aw.js} +2 -2
  114. package/dist/{chunk-e4zxacxd.js.map → chunk-n2c748aw.js.map} +1 -1
  115. package/dist/{chunk-nqgeny8m.js → chunk-ng6pbd7f.js} +4 -4
  116. package/dist/{chunk-nqgeny8m.js.map → chunk-ng6pbd7f.js.map} +1 -1
  117. package/dist/{chunk-7xe5vd4w.js → chunk-pdymdjpq.js} +2 -2
  118. package/dist/{chunk-7xe5vd4w.js.map → chunk-pdymdjpq.js.map} +1 -1
  119. package/dist/{chunk-dj0nvj66.js → chunk-pn3egz75.js} +1 -1
  120. package/dist/chunk-qjn6a2ed.js +5 -0
  121. package/dist/{chunk-89egc0h3.js.map → chunk-qjn6a2ed.js.map} +1 -1
  122. package/dist/chunk-qrc2r0ce.js +5 -0
  123. package/dist/{chunk-kp7wcpx7.js.map → chunk-qrc2r0ce.js.map} +3 -3
  124. package/dist/{chunk-gyszenps.js → chunk-qtz4g4kv.js} +3 -3
  125. package/dist/{chunk-gyszenps.js.map → chunk-qtz4g4kv.js.map} +1 -1
  126. package/dist/{chunk-55btq9c7.js → chunk-qx9p15em.js} +2 -2
  127. package/dist/{chunk-55btq9c7.js.map → chunk-qx9p15em.js.map} +1 -1
  128. package/dist/{chunk-fp9yn4k8.js → chunk-rq0dpv7r.js} +2 -2
  129. package/dist/{chunk-fp9yn4k8.js.map → chunk-rq0dpv7r.js.map} +1 -1
  130. package/dist/{chunk-ps5rpy9n.js → chunk-ryh6rfts.js} +2 -2
  131. package/dist/{chunk-ps5rpy9n.js.map → chunk-ryh6rfts.js.map} +1 -1
  132. package/dist/{chunk-7etvj6w2.js → chunk-svrvb47q.js} +2 -2
  133. package/dist/{chunk-7etvj6w2.js.map → chunk-svrvb47q.js.map} +1 -1
  134. package/dist/{chunk-mdg8g8h2.js → chunk-t5aft2ra.js} +4 -4
  135. package/dist/{chunk-mdg8g8h2.js.map → chunk-t5aft2ra.js.map} +2 -2
  136. package/dist/{chunk-ncnygh0s.js → chunk-t9fh0ptd.js} +2 -2
  137. package/dist/{chunk-ncnygh0s.js.map → chunk-t9fh0ptd.js.map} +1 -1
  138. package/dist/{chunk-jf2dr481.js → chunk-tbvrv4h2.js} +2 -2
  139. package/dist/{chunk-jf2dr481.js.map → chunk-tbvrv4h2.js.map} +1 -1
  140. package/dist/{chunk-6r7956dh.js → chunk-tgy75n24.js} +2 -2
  141. package/dist/{chunk-6r7956dh.js.map → chunk-tgy75n24.js.map} +1 -1
  142. package/dist/{chunk-pxjkxhf9.js → chunk-tp1gxcke.js} +3 -3
  143. package/dist/{chunk-pxjkxhf9.js.map → chunk-tp1gxcke.js.map} +1 -1
  144. package/dist/{chunk-dgy6pf2h.js → chunk-v0fqq5z7.js} +2 -2
  145. package/dist/{chunk-dgy6pf2h.js.map → chunk-v0fqq5z7.js.map} +1 -1
  146. package/dist/{chunk-cf8bztwq.js → chunk-v4ecxbgd.js} +2 -2
  147. package/dist/{chunk-cf8bztwq.js.map → chunk-v4ecxbgd.js.map} +1 -1
  148. package/dist/{chunk-rat2827k.js → chunk-v5sg62xm.js} +2 -2
  149. package/dist/{chunk-rat2827k.js.map → chunk-v5sg62xm.js.map} +1 -1
  150. package/dist/chunk-v979k0be.js +5 -0
  151. package/dist/{chunk-zcmz311y.js.map → chunk-v979k0be.js.map} +3 -8
  152. package/dist/{chunk-rdfatx17.js → chunk-w2yd62vs.js} +2 -2
  153. package/dist/{chunk-rdfatx17.js.map → chunk-w2yd62vs.js.map} +1 -1
  154. package/dist/{chunk-rw45xz3f.js → chunk-we65r9fh.js} +3 -3
  155. package/dist/{chunk-rw45xz3f.js.map → chunk-we65r9fh.js.map} +1 -1
  156. package/dist/{chunk-2y0nr525.js → chunk-wnmpwb4s.js} +3 -3
  157. package/dist/{chunk-2y0nr525.js.map → chunk-wnmpwb4s.js.map} +1 -1
  158. package/dist/{chunk-s3gn68dy.js → chunk-wzr8tzv0.js} +2 -2
  159. package/dist/{chunk-s3gn68dy.js.map → chunk-wzr8tzv0.js.map} +1 -1
  160. package/dist/{chunk-wt4ekzp9.js → chunk-x47kwv2x.js} +2 -2
  161. package/dist/{chunk-wt4ekzp9.js.map → chunk-x47kwv2x.js.map} +1 -1
  162. package/dist/{chunk-8ddt5fa2.js → chunk-x93dpv6e.js} +2 -2
  163. package/dist/{chunk-8ddt5fa2.js.map → chunk-x93dpv6e.js.map} +1 -1
  164. package/dist/{chunk-tac25cnj.js → chunk-xpzdwhjg.js} +3 -3
  165. package/dist/{chunk-tac25cnj.js.map → chunk-xpzdwhjg.js.map} +1 -1
  166. package/dist/{chunk-ax042w6k.js → chunk-z4fhhtjh.js} +2 -2
  167. package/dist/{chunk-ax042w6k.js.map → chunk-z4fhhtjh.js.map} +1 -1
  168. package/dist/{chunk-jychsmhf.js → chunk-z5am43fj.js} +2 -2
  169. package/dist/{chunk-jychsmhf.js.map → chunk-z5am43fj.js.map} +1 -1
  170. package/dist/{chunk-5h2xj3cx.js → chunk-z6x78wb3.js} +2 -2
  171. package/dist/{chunk-5h2xj3cx.js.map → chunk-z6x78wb3.js.map} +1 -1
  172. package/dist/{chunk-q5xcjm5z.js → chunk-zvg2qsa5.js} +2 -2
  173. package/dist/{chunk-q5xcjm5z.js.map → chunk-zvg2qsa5.js.map} +1 -1
  174. package/dist/{chunk-mt82209n.js → chunk-zy56kaws.js} +2 -2
  175. package/dist/{chunk-mt82209n.js.map → chunk-zy56kaws.js.map} +1 -1
  176. package/dist/config/index.js +1 -1
  177. package/dist/console/run.js +2 -2
  178. package/dist/console/run.js.map +1 -1
  179. package/dist/container/index.js +2 -2
  180. package/dist/container/index.js.map +1 -1
  181. package/dist/database/index.js +2 -2
  182. package/dist/database/index.js.map +1 -1
  183. package/dist/email/Email.d.ts.map +1 -1
  184. package/dist/email/index.js +3 -4
  185. package/dist/email/index.js.map +4 -15
  186. package/dist/facades/index.js +2 -2
  187. package/dist/facades/index.js.map +1 -1
  188. package/dist/foundation/index.js +2 -2
  189. package/dist/foundation/index.js.map +1 -1
  190. package/dist/http/index.js +2 -2
  191. package/dist/http/index.js.map +1 -1
  192. package/dist/i18n/dictionaryRuntime.js +2 -2
  193. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  194. package/dist/i18n/index.js +2 -2
  195. package/dist/i18n/index.js.map +1 -1
  196. package/dist/kernel/index.js +2 -2
  197. package/dist/kernel/index.js.map +1 -1
  198. package/dist/orm/index.js +2 -2
  199. package/dist/orm/index.js.map +1 -1
  200. package/dist/probe/index.js +2 -2
  201. package/dist/probe/index.js.map +1 -1
  202. package/dist/server/index.js +2 -2
  203. package/dist/server/index.js.map +1 -1
  204. package/dist/services/index.js +2 -2
  205. package/dist/services/index.js.map +2 -2
  206. package/dist/services/queue/work.js +2 -2
  207. package/dist/services/queue/work.js.map +1 -1
  208. package/dist/stats/route-table.js +1 -1
  209. package/dist/support/index.js +2 -2
  210. package/dist/support/index.js.map +1 -1
  211. package/dist/vitest/index.js +1 -1
  212. package/package.json +1 -1
  213. package/dist/chunk-89egc0h3.js +0 -5
  214. package/dist/chunk-dpmvvwts.js +0 -11
  215. package/dist/chunk-kp7wcpx7.js +0 -5
  216. package/dist/chunk-qs2xvc8g.js +0 -7
  217. package/dist/chunk-zcmz311y.js +0 -8
  218. /package/dist/{chunk-6ttbhhnn.js.map → chunk-421hq1rw.js.map} +0 -0
  219. /package/dist/{chunk-k16phdjv.js.map → chunk-4qyp7w89.js.map} +0 -0
  220. /package/dist/{chunk-nzd7z4s6.js.map → chunk-70jhw0ft.js.map} +0 -0
  221. /package/dist/{chunk-4wh4dfgf.js.map → chunk-81y96dax.js.map} +0 -0
  222. /package/dist/{chunk-fxa72ppw.js.map → chunk-fjnhqbtx.js.map} +0 -0
  223. /package/dist/{chunk-dj0nvj66.js.map → chunk-pn3egz75.js.map} +0 -0
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Ke as J,Ne as A}from"../../chunk-p1ern8r4.js";import{Mk as V}from"../../chunk-wy82t7mz.js";import"../../chunk-tac25cnj.js";import"../../chunk-0k2r6bep.js";import"../../chunk-0av1gyns.js";import"../../chunk-zmt5kdpb.js";import"../../chunk-37209psn.js";import"../../chunk-fqhkkpq3.js";import{Am as _,Em as I,vm as Y,ym as N,zm as Z}from"../../chunk-6r7956dh.js";import{Im as x}from"../../chunk-5mrtgr7q.js";import"../../chunk-3dkv4989.js";import $ from"path";function X(z){if(!z.config.get("route.channels"))return null;let C=z.config.get("broadcast",{}).driver;if(!(C===void 0||C==="memory"||C instanceof V))return null;return'[gemi] Broadcasts from this worker reach no one: the broadcast driver is "memory", which delivers to the sockets of the process that emits, and a worker has none. Set `driver: "redis"` in app/config/broadcast.ts.'}class L extends Error{name="QueueWorkerRefused"}class O{kernel;stopping;keepAlive;settings;constructor(z,C={}){this.kernel=z;this.settings={..._(),...C}}async start(){if(await this.kernel.waitForBoot(),this.stopping)return;let z=this.kernel.app;if(!z.bound(J))throw new L("[gemi] `gemi queue:work` has no queue to claim from: this application does not register QueueServiceProvider.");let C=z.make(J);if(!C.durable)throw new L('[gemi] `gemi queue:work` refuses to start: the queue uses the memory driver, which keeps each job in the process that dispatched it, so a worker never sees one. Set `driver: "database"` (or another driver every process can reach) in app/config/queue.ts, or run jobs in the server and drop the worker.');C.start(),this.keepAlive=setInterval(()=>{},1073741824),console.log(`[gemi] Queue worker started: claiming up to ${C.config.concurrency} job(s) at a time.`);let E=X(z);if(E)console.warn(E)}stop(z={}){return this.stopping??=this.drain({...this.settings,...z}),this.stopping}async drain(z){let C=Date.now()+z.timeoutMs;Y();let E=this.kernel.app,F=E.resolved(J)?E.make(J):void 0;if(F)console.log(`[gemi] Shutting down: waiting for ${F.running} running job(s) (up to ${z.timeoutMs/1000}s).`),await F.drain(z.timeoutMs);let G=N()===0;if(!G){let U=C-Date.now();if(G=U>0&&await Promise.race([Z().then(()=>!0),new Promise((K)=>setTimeout(()=>K(!1),U))]),!G)console.error(`[gemi] Shutdown grace period elapsed with ${N()} held background task(s) still running; abandoning them.`)}let H=await this.kernel.shutdown({timeoutMs:z.providerTimeoutMs});clearInterval(this.keepAlive);let T=G&&(F?.running??0)===0&&H.failed.length===0&&H.timedOut.length===0;return console.log(`[gemi] Shutdown ${T?"complete":"finished with errors"}.`),T?0:1}}async function j(){let z=x();process.env.ROOT_DIR=z,process.env.APP_DIR=$.join(z,"app"),A();let C=$.join(z,"app/kernel/Kernel.ts"),{default:E}=await import(C);if(typeof E!=="function")return console.error(`[gemi] ${C} has no default export to boot the worker from.`),1;let F=new E;F.boot();let G=new O(F);I(()=>G.stop());try{await G.start()}catch(H){if(!(H instanceof L))throw H;return console.error(H.message),1}return}j().then((z)=>{if(z!==void 0)process.exit(z)},(z)=>{console.error("[gemi] The queue worker failed to start:",z),process.exit(1)});
2
+ import{Le as J,Oe as A}from"../../chunk-1jyzg1ex.js";import{Nk as V}from"../../chunk-64yf0shq.js";import"../../chunk-xpzdwhjg.js";import"../../chunk-6h1hjzj7.js";import"../../chunk-mvp6fkg2.js";import"../../chunk-2450kxym.js";import"../../chunk-d3a29hyg.js";import"../../chunk-awryyak8.js";import{Am as Z,Bm as _,Fm as I,wm as Y,zm as N}from"../../chunk-tgy75n24.js";import{Jm as x}from"../../chunk-hvyzp9p6.js";import"../../chunk-ads3c8m0.js";import $ from"path";function X(z){if(!z.config.get("route.channels"))return null;let C=z.config.get("broadcast",{}).driver;if(!(C===void 0||C==="memory"||C instanceof V))return null;return'[gemi] Broadcasts from this worker reach no one: the broadcast driver is "memory", which delivers to the sockets of the process that emits, and a worker has none. Set `driver: "redis"` in app/config/broadcast.ts.'}class L extends Error{name="QueueWorkerRefused"}class O{kernel;stopping;keepAlive;settings;constructor(z,C={}){this.kernel=z;this.settings={..._(),...C}}async start(){if(await this.kernel.waitForBoot(),this.stopping)return;let z=this.kernel.app;if(!z.bound(J))throw new L("[gemi] `gemi queue:work` has no queue to claim from: this application does not register QueueServiceProvider.");let C=z.make(J);if(!C.durable)throw new L('[gemi] `gemi queue:work` refuses to start: the queue uses the memory driver, which keeps each job in the process that dispatched it, so a worker never sees one. Set `driver: "database"` (or another driver every process can reach) in app/config/queue.ts, or run jobs in the server and drop the worker.');C.start(),this.keepAlive=setInterval(()=>{},1073741824),console.log(`[gemi] Queue worker started: claiming up to ${C.config.concurrency} job(s) at a time.`);let E=X(z);if(E)console.warn(E)}stop(z={}){return this.stopping??=this.drain({...this.settings,...z}),this.stopping}async drain(z){let C=Date.now()+z.timeoutMs;Y();let E=this.kernel.app,F=E.resolved(J)?E.make(J):void 0;if(F)console.log(`[gemi] Shutting down: waiting for ${F.running} running job(s) (up to ${z.timeoutMs/1000}s).`),await F.drain(z.timeoutMs);let G=N()===0;if(!G){let U=C-Date.now();if(G=U>0&&await Promise.race([Z().then(()=>!0),new Promise((K)=>setTimeout(()=>K(!1),U))]),!G)console.error(`[gemi] Shutdown grace period elapsed with ${N()} held background task(s) still running; abandoning them.`)}let H=await this.kernel.shutdown({timeoutMs:z.providerTimeoutMs});clearInterval(this.keepAlive);let T=G&&(F?.running??0)===0&&H.failed.length===0&&H.timedOut.length===0;return console.log(`[gemi] Shutdown ${T?"complete":"finished with errors"}.`),T?0:1}}async function j(){let z=x();process.env.ROOT_DIR=z,process.env.APP_DIR=$.join(z,"app"),A();let C=$.join(z,"app/kernel/Kernel.ts"),{default:E}=await import(C);if(typeof E!=="function")return console.error(`[gemi] ${C} has no default export to boot the worker from.`),1;let F=new E;F.boot();let G=new O(F);I(()=>G.stop());try{await G.start()}catch(H){if(!(H instanceof L))throw H;return console.error(H.message),1}return}j().then((z)=>{if(z!==void 0)process.exit(z)},(z)=>{console.error("[gemi] The queue worker failed to start:",z),process.exit(1)});
3
3
 
4
- //# debugId=07AAF52CEDF447F964756E2164756E21
4
+ //# debugId=CFE931E18EFD922964756E2164756E21
@@ -7,6 +7,6 @@
7
7
  "import type { Application, ShutdownReport } from \"../../foundation/Application\";\nimport {\n heldWork,\n heldWorkSettled,\n markShuttingDown,\n shutdownSettings,\n type ShutdownSettings,\n} from \"../../server/shutdown\";\nimport { memoryBroadcastInWorker } from \"../broadcast/workerWarning\";\nimport { QueueManager } from \"./QueueManager\";\n\n/** The part of a `Kernel` a worker drives. */\nexport type WorkerKernel = {\n readonly app: Application;\n waitForBoot(): Promise<void>;\n shutdown(options?: { timeoutMs?: number }): Promise<ShutdownReport>;\n};\n\n/**\n * A worker that was told to start in an application it cannot claim for. The\n * message is written for the operator reading the deploy's logs.\n */\nexport class QueueWorkerRefused extends Error {\n name = \"QueueWorkerRefused\";\n}\n\n/**\n * The process `gemi queue:work` runs: the application booted as a server boots\n * it, claiming from the queue, and no `Bun.serve`. It exists so job capacity\n * can be scaled apart from request traffic, which needs a driver both kinds of\n * process can reach; see `start` for why the memory driver is refused.\n *\n * The caller marks the process as a worker (`markQueueWorker`) before the\n * kernel registers, so every claim rule that asks `claimsInThisProcess` sees a\n * process that claims, whatever `GEMI_QUEUE_CLAIM` says.\n */\nexport class QueueWorker {\n private stopping: Promise<number> | undefined;\n private keepAlive: ReturnType<typeof setInterval> | undefined;\n private readonly settings: ShutdownSettings;\n\n /**\n * `settings` default to the `GEMI_SHUTDOWN_*` variables, read here rather\n * than at the signal so a bad value is warned about while the deploy is\n * being watched, as `Server.start` does.\n */\n constructor(\n private readonly kernel: WorkerKernel,\n settings: Partial<ShutdownSettings> = {},\n ) {\n this.settings = { ...shutdownSettings(), ...settings };\n }\n\n /**\n * Boots the application and starts claiming. Rejects with\n * `QueueWorkerRefused` when the application has no queue, or its queue uses\n * the memory driver.\n *\n * Refused rather than warned about, because a memory worker can never do\n * anything: its jobs live in a `Map` in the process that dispatched them,\n * so a worker's is always empty. Left running, it looks like a healthy\n * deploy — a process up, no errors — that runs nothing, and scaling it out\n * adds no capacity. An exit the platform reports as a crash loop is a form\n * of the mistake someone will see.\n */\n async start(): Promise<void> {\n await this.kernel.waitForBoot();\n // A signal during the boot has already drained and cleared the handle\n // below. Going on would start the loop again and arm a handle nothing\n // clears, holding open a worker that has finished shutting down.\n if (this.stopping) return;\n\n const application = this.kernel.app;\n // `bound`, not `make` in a try: an application built without the queue\n // provider is a configuration to name, not an unbound-token stack trace.\n if (!application.bound(QueueManager)) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` has no queue to claim from: this application \" +\n \"does not register QueueServiceProvider.\",\n );\n }\n const queue = application.make(QueueManager);\n if (!queue.durable) {\n throw new QueueWorkerRefused(\n \"[gemi] `gemi queue:work` refuses to start: the queue uses the memory \" +\n \"driver, which keeps each job in the process that dispatched it, so \" +\n 'a worker never sees one. Set `driver: \"database\"` (or another driver ' +\n \"every process can reach) in app/config/queue.ts, or run jobs in the \" +\n \"server and drop the worker.\",\n );\n }\n\n // Idempotent: a production boot with a durable driver has already started\n // it (`startClaimingIfServing`). Development has not, and a worker claims\n // in either.\n queue.start();\n // The queue's poll timer is unref'd, so that a script's queue does not\n // hold it open; here the queue is the process, and without a handle of its\n // own an idle worker would exit 0 as soon as it booted.\n this.keepAlive = setInterval(() => {}, 1 << 30);\n console.log(\n `[gemi] Queue worker started: claiming up to ${queue.config.concurrency} job(s) at a time.`,\n );\n const broadcastWarning = memoryBroadcastInWorker(application);\n if (broadcastWarning) console.warn(broadcastWarning);\n }\n\n /**\n * Stops claiming, waits for the running jobs, runs every provider's\n * `shutdown()`, and resolves with the exit code: 0 when no job was left\n * running and every provider finished in time, 1 otherwise. Idempotent.\n *\n * `gemi start`'s drain, with the jobs where the requests were:\n * `isShuttingDown()` turns true, which stops a durable queue claiming;\n * running jobs get `timeoutMs` (`GEMI_SHUTDOWN_TIMEOUT`), which a server\n * spends on requests; then `Application.shutdown` gets `providerTimeoutMs`,\n * and in it the queue provider waits for whatever is still running and\n * names it. The two budgets add up as they do for a server, so a worker\n * fits the same grace period. `delayMs` is not waited: it is for a load\n * balancer, and nothing routes to a worker.\n */\n stop(settings: Partial<ShutdownSettings> = {}): Promise<number> {\n this.stopping ??= this.drain({ ...this.settings, ...settings });\n return this.stopping;\n }\n\n private async drain(settings: ShutdownSettings): Promise<number> {\n const deadline = Date.now() + settings.timeoutMs;\n markShuttingDown();\n const application = this.kernel.app;\n // Resolving the manager now would build a driver only to stop it, which\n // is what a signal during the boot, before the provider resolved it, finds.\n const queue = application.resolved(QueueManager) ? application.make(QueueManager) : undefined;\n if (queue) {\n console.log(\n `[gemi] Shutting down: waiting for ${queue.running} running job(s) ` +\n `(up to ${settings.timeoutMs / 1000}s).`,\n );\n await queue.drain(settings.timeoutMs);\n }\n // Work held with `holdShutdown` (#1210) gets what is left of the same budget.\n let held = heldWork() === 0;\n if (!held) {\n const remaining = deadline - Date.now();\n held =\n remaining > 0 &&\n (await Promise.race([\n heldWorkSettled().then(() => true),\n new Promise<false>((resolve) => setTimeout(() => resolve(false), remaining)),\n ]));\n if (!held) {\n console.error(\n `[gemi] Shutdown grace period elapsed with ${heldWork()} held background task(s) still running; abandoning them.`,\n );\n }\n }\n\n const report = await this.kernel.shutdown({ timeoutMs: settings.providerTimeoutMs });\n clearInterval(this.keepAlive);\n const clean =\n held && (queue?.running ?? 0) === 0 && report.failed.length === 0 && report.timedOut.length === 0;\n console.log(`[gemi] Shutdown ${clean ? \"complete\" : \"finished with errors\"}.`);\n return clean ? 0 : 1;\n }\n}\n"
8
8
  ],
9
9
  "mappings": ";gdAYA,kBCDO,OAAS,DAAuB,DAAC,AAAyC,DAC/E,CAAI,DAAC,AAAY,KAAO,IAAI,gBAAgB,EAAG,OAAO,KACtD,IAAM,EAAS,EAAY,OAAO,IAAqB,YAAa,CAAC,CAAC,EAAE,OAGxE,GAAI,EADF,IAAW,QAAa,IAAW,UAAY,aAAkB,GACtD,OAAO,KACpB,MACE,uNCIG,MAAM,UAA2B,KAAM,CAC5C,KAAO,oBACT,CAYO,MAAM,CAAY,CAWJ,OAVX,SACA,UACS,SAOjB,WAAW,CACQ,EACjB,EAAsC,CAAC,EACvC,CAFiB,cAGjB,KAAK,SAAW,IAAK,EAAiB,KAAM,CAAS,OAejD,MAAK,EAAkB,CAK3B,GAJA,MAAM,KAAK,OAAO,YAAY,EAI1B,KAAK,SAAU,OAEnB,IAAM,EAAc,KAAK,OAAO,IAGhC,GAAI,CAAC,EAAY,MAAM,CAAY,EACjC,MAAM,IAAI,EACR,+GAEF,EAEF,IAAM,EAAQ,EAAY,KAAK,CAAY,EAC3C,GAAI,CAAC,EAAM,QACT,MAAM,IAAI,EACR,8SAKF,EAMF,EAAM,MAAM,EAIZ,KAAK,UAAY,YAAY,IAAM,GAAI,UAAO,EAC9C,QAAQ,IACN,+CAA+C,EAAM,OAAO,+BAC9D,EACA,IAAM,EAAmB,EAAwB,CAAW,EAC5D,GAAI,EAAkB,QAAQ,KAAK,CAAgB,EAiBrD,IAAI,CAAC,EAAsC,CAAC,EAAoB,CAE9D,OADA,KAAK,WAAa,KAAK,MAAM,IAAK,KAAK,YAAa,CAAS,CAAC,EACvD,KAAK,cAGA,MAAK,CAAC,EAA6C,CAC/D,IAAM,EAAW,KAAK,IAAI,EAAI,EAAS,UACvC,EAAiB,EACjB,IAAM,EAAc,KAAK,OAAO,IAG1B,EAAQ,EAAY,SAAS,CAAY,EAAI,EAAY,KAAK,CAAY,EAAI,OACpF,GAAI,EACF,QAAQ,IACN,qCAAqC,EAAM,iCAC/B,EAAS,UAAY,SACnC,EACA,MAAM,EAAM,MAAM,EAAS,SAAS,EAGtC,IAAI,EAAO,EAAS,IAAM,EAC1B,GAAI,CAAC,EAAM,CACT,IAAM,EAAY,EAAW,KAAK,IAAI,EAOtC,GANA,EACE,EAAY,GACX,MAAM,QAAQ,KAAK,CAClB,EAAgB,EAAE,KAAK,IAAM,EAAI,EACjC,IAAI,QAAe,CAAC,IAAY,WAAW,IAAM,EAAQ,EAAK,EAAG,CAAS,CAAC,CAC7E,CAAC,EACC,CAAC,EACH,QAAQ,MACN,6CAA6C,EAAS,2DACxD,EAIJ,IAAM,EAAS,MAAM,KAAK,OAAO,SAAS,CAAE,UAAW,EAAS,iBAAkB,CAAC,EACnF,cAAc,KAAK,SAAS,EAC5B,IAAM,EACJ,IAAS,GAAO,SAAW,KAAO,GAAK,EAAO,OAAO,SAAW,GAAK,EAAO,SAAS,SAAW,EAElG,OADA,QAAQ,IAAI,mBAAmB,EAAQ,WAAa,yBAAyB,EACtE,EAAQ,EAAI,EAEvB,CFjJA,eAAe,CAAI,EAAgC,CACjD,IAAM,EAAU,EAAY,EAI5B,QAAQ,IAAI,SAAW,EACvB,QAAQ,IAAI,QAAU,EAAK,KAAK,EAAS,KAAK,EAE9C,EAAgB,EAEhB,IAAM,EAAa,EAAK,KAAK,EAAS,sBAAsB,GACpD,QAAS,GAAY,MAAa,UAG1C,GAAI,OAAO,IAAW,WAEpB,OADA,QAAQ,MAAM,UAAU,kDAA2D,EAC5E,EAET,IAAM,EAAS,IAAI,EACnB,EAAO,KAAK,EAEZ,IAAM,EAAS,IAAI,EAAY,CAAM,EAKrC,EAAuB,IAAM,EAAO,KAAK,CAAC,EAE1C,GAAI,CACF,MAAM,EAAO,MAAM,EACnB,MAAO,EAAO,CACd,GAAI,EAAE,aAAiB,GAAqB,MAAM,EAElD,OADA,QAAQ,MAAM,EAAM,OAAO,EACpB,EAGT,OAGF,EAAK,EAAE,KACL,CAAC,IAAS,CACR,GAAI,IAAS,OAAW,QAAQ,KAAK,CAAI,GAE3C,CAAC,IAAU,CACT,QAAQ,MAAM,2CAA4C,CAAK,EAC/D,QAAQ,KAAK,CAAC,EAElB",
10
- "debugId": "07AAF52CEDF447F964756E2164756E21",
10
+ "debugId": "CFE931E18EFD922964756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import"../chunk-3dkv4989.js";import M from"path";import{writeFileSync as Q}from"fs";var L=new Set(["FILE","REDIRECT"]);function H(j){return j.run(()=>{let x=[];for(let{group:z,view:D}of j.domains().viewGroups())for(let[G,B]of Object.entries(D.flatViewRoutes)){let C=D.routeManifest[G]??B.segments.map((K)=>K.viewPath);if(C.length===0||L.has(C.at(-1)))continue;x.push({path:G,group:z,views:C,...B.static?{static:{...B.static.layout?{layout:B.static.layout}:{},...B.static.navigation?{navigation:!0}:{}}}:{}})}return x})}var J=process.argv[2];async function U(){if(!J)throw Error("usage: route-table <out.json>");let j=M.resolve(process.cwd(),"app/kernel/Kernel.ts"),x=await import(j);if(typeof x.default!=="function")throw Error(`${j} has no default export (the Kernel subclass).`);let z=new x.default;z.boot();try{Q(J,JSON.stringify(H(z)))}finally{z.destroy()}}U().then(()=>process.exit(0),(j)=>{console.error(j?.stack??String(j)),process.exit(1)});
2
+ import"../chunk-ads3c8m0.js";import M from"path";import{writeFileSync as Q}from"fs";var L=new Set(["FILE","REDIRECT"]);function H(j){return j.run(()=>{let x=[];for(let{group:z,view:D}of j.domains().viewGroups())for(let[G,B]of Object.entries(D.flatViewRoutes)){let C=D.routeManifest[G]??B.segments.map((K)=>K.viewPath);if(C.length===0||L.has(C.at(-1)))continue;x.push({path:G,group:z,views:C,...B.static?{static:{...B.static.layout?{layout:B.static.layout}:{},...B.static.navigation?{navigation:!0}:{}}}:{}})}return x})}var J=process.argv[2];async function U(){if(!J)throw Error("usage: route-table <out.json>");let j=M.resolve(process.cwd(),"app/kernel/Kernel.ts"),x=await import(j);if(typeof x.default!=="function")throw Error(`${j} has no default export (the Kernel subclass).`);let z=new x.default;z.boot();try{Q(J,JSON.stringify(H(z)))}finally{z.destroy()}}U().then(()=>process.exit(0),(j)=>{console.error(j?.stack??String(j)),process.exit(1)});
3
3
 
4
4
  //# debugId=05EB0087C5A2060D64756E2164756E21
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Se as Y}from"../chunk-qy0k2s5f.js";import{cl as M}from"../chunk-0k2r6bep.js";import{jm as P,lm as R}from"../chunk-37209psn.js";import"../chunk-fqhkkpq3.js";import{Fm as Q,Gm as U,Hm as V,Im as W}from"../chunk-5mrtgr7q.js";import"../chunk-3dkv4989.js";class S{static token;async boot(){}onShutdown(x){}static inject(){if(!this.token)throw Error(`Service [${this.name}] does not declare a \`static token\`, so the container has no key to resolve it by.`);try{return R(this)}catch(x){throw Error(`Could not inject [${this.name}]. Services are constructed when the kernel boots, so `+"inject() only works from code that runs after that \u2014 a constructor default or a method "+`body, never module top level. Check that [${this.name}] is listed in \`services\` on your Kernel.`,{cause:x})}}static with(x){let f=new this;for(let[C,g]of Object.entries(x))if(g!==void 0)f[C]=g;return f}}import{readdir as z}from"fs/promises";import{join as B,parse as j}from"path";var H=[".ts",".tsx",".js",".mjs",".jsx"];function J(x={}){let f={};for(let[C,g]of Object.entries(x))f[C]=q(g);return new P(f)}async function L(x,f=new P){let C=[];try{C=await z(x)}catch(D){return f}let g=C.filter((D)=>{let{ext:v,name:F}=j(D);return H.includes(v)&&!F.startsWith(".")}).sort();for(let D of g){let{name:v}=j(D),F=await import(B(x,D));f.set(v,q(F))}return f}function q(x){if(x&&typeof x==="object"&&"default"in x)return x.default;return x}export{M as withDefaults,Q as sourceFiles,W as projectRoot,L as loadConfigFrom,V as discoverClasses,J as createConfigRepository,Y as ServiceProvider,S as Service,P as Repository,U as DiscoveryError};
2
+ import{Te as Y}from"../chunk-mvb8m247.js";import{dl as M}from"../chunk-6h1hjzj7.js";import{km as P,mm as R}from"../chunk-d3a29hyg.js";import"../chunk-awryyak8.js";import{Gm as Q,Hm as U,Im as V,Jm as W}from"../chunk-hvyzp9p6.js";import"../chunk-ads3c8m0.js";class S{static token;async boot(){}onShutdown(x){}static inject(){if(!this.token)throw Error(`Service [${this.name}] does not declare a \`static token\`, so the container has no key to resolve it by.`);try{return R(this)}catch(x){throw Error(`Could not inject [${this.name}]. Services are constructed when the kernel boots, so `+"inject() only works from code that runs after that \u2014 a constructor default or a method "+`body, never module top level. Check that [${this.name}] is listed in \`services\` on your Kernel.`,{cause:x})}}static with(x){let f=new this;for(let[C,g]of Object.entries(x))if(g!==void 0)f[C]=g;return f}}import{readdir as z}from"fs/promises";import{join as B,parse as j}from"path";var H=[".ts",".tsx",".js",".mjs",".jsx"];function J(x={}){let f={};for(let[C,g]of Object.entries(x))f[C]=q(g);return new P(f)}async function L(x,f=new P){let C=[];try{C=await z(x)}catch(D){return f}let g=C.filter((D)=>{let{ext:v,name:F}=j(D);return H.includes(v)&&!F.startsWith(".")}).sort();for(let D of g){let{name:v}=j(D),F=await import(B(x,D));f.set(v,q(F))}return f}function q(x){if(x&&typeof x==="object"&&"default"in x)return x.default;return x}export{M as withDefaults,Q as sourceFiles,W as projectRoot,L as loadConfigFrom,V as discoverClasses,J as createConfigRepository,Y as ServiceProvider,S as Service,P as Repository,U as DiscoveryError};
3
3
 
4
- //# debugId=AB19AE6711A46B3F64756E2164756E21
4
+ //# debugId=348FC34DE9B64B8B64756E2164756E21
@@ -6,6 +6,6 @@
6
6
  "import { readdir } from \"node:fs/promises\";\nimport { join, parse } from \"node:path\";\n\nimport { Repository } from \"./Repository\";\n\nconst CONFIG_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".mjs\", \".jsx\"];\n\n// Builds a Repository from an already-imported map of config modules. The map\n// key becomes the top-level config key, so `{ mail: mailModule }` is readable\n// as `config.get(\"mail.driver\")`. Each entry may be either the module namespace\n// (its `default` export is unwrapped) or the config object itself.\nexport function createConfigRepository(\n modules: Record<string, any> = {},\n): Repository {\n const items: Record<string, any> = {};\n\n for (const [key, mod] of Object.entries(modules)) {\n items[key] = unwrap(mod);\n }\n\n return new Repository(items);\n}\n\n// Reads every config module in an app's `app/config` directory into a\n// Repository. The file's basename is the top-level key: `app/config/mail.ts`\n// populates `mail.*`. A missing directory yields an empty Repository so apps\n// that declare no config still boot.\nexport async function loadConfigFrom(\n directory: string,\n repository = new Repository(),\n): Promise<Repository> {\n let entries: string[] = [];\n\n try {\n entries = await readdir(directory);\n } catch (err) {\n return repository;\n }\n\n const files = entries\n .filter((entry) => {\n const { ext, name } = parse(entry);\n return CONFIG_EXTENSIONS.includes(ext) && !name.startsWith(\".\");\n })\n .sort();\n\n for (const file of files) {\n const { name } = parse(file);\n const mod = await import(join(directory, file));\n repository.set(name, unwrap(mod));\n }\n\n return repository;\n}\n\nfunction unwrap(mod: any) {\n if (mod && typeof mod === \"object\" && \"default\" in mod) {\n return mod.default;\n }\n return mod;\n}\n"
7
7
  ],
8
8
  "mappings": ";2RAiCO,CAAe,JAAQ,EAOrB,OAMD,AAAI,EAAkB,EAmB5B,UAAU,CAAC,EAEkD,QAmBtD,OAAS,EAKX,CACH,GAAI,CAAC,KAAK,MACR,MAAU,MACR,YAAY,KAAK,0FACnB,EAGF,GAAI,CACF,OAAO,EAAI,IAAuB,EAClC,MAAO,EAAO,CACd,MAAU,MACR,qBAAqB,KAAK,6DACxB,+FACA,6CAA6C,KAAK,kDAEpD,CAAE,OAAM,CACV,SAoBG,KAAuB,CAAoB,EAA0B,CAC1E,IAAM,EAAW,IAAI,KACrB,QAAY,EAAK,KAAU,OAAO,QAAQ,CAAS,EACjD,GAAI,IAAU,OAAW,EAAS,GAAO,EAE3C,OAAO,EAEX,CCtIA,kBAAS,oBACT,eAAS,WAAM,aAIf,IAAM,EAAoB,CAAC,MAAO,OAAQ,MAAO,OAAQ,MAAM,EAMxD,SAAS,CAAsB,CACpC,EAA+B,CAAC,EACpB,CACZ,IAAM,EAA6B,CAAC,EAEpC,QAAY,EAAK,KAAQ,OAAO,QAAQ,CAAO,EAC7C,EAAM,GAAO,EAAO,CAAG,EAGzB,OAAO,IAAI,EAAW,CAAK,EAO7B,eAAsB,CAAc,CAClC,EACA,EAAa,IAAI,EACI,CACrB,IAAI,EAAoB,CAAC,EAEzB,GAAI,CACF,EAAU,MAAM,EAAQ,CAAS,EACjC,MAAO,EAAK,CACZ,OAAO,EAGT,IAAM,EAAQ,EACX,OAAO,CAAC,IAAU,CACjB,IAAQ,MAAK,QAAS,EAAM,CAAK,EACjC,OAAO,EAAkB,SAAS,CAAG,GAAK,CAAC,EAAK,WAAW,GAAG,EAC/D,EACA,KAAK,EAER,QAAW,KAAQ,EAAO,CACxB,IAAQ,QAAS,EAAM,CAAI,EACrB,EAAM,MAAa,SAAK,EAAW,CAAI,GAC7C,EAAW,IAAI,EAAM,EAAO,CAAG,CAAC,EAGlC,OAAO,EAGT,SAAS,CAAM,CAAC,EAAU,CACxB,GAAI,GAAO,OAAO,IAAQ,UAAY,YAAa,EACjD,OAAO,EAAI,QAEb,OAAO",
9
- "debugId": "AB19AE6711A46B3F64756E2164756E21",
9
+ "debugId": "348FC34DE9B64B8B64756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ua as B,va as D}from"../chunk-gyszenps.js";import"../chunk-adw279ge.js";import"../chunk-nqqyn3cx.js";import{Pa as J}from"../chunk-h9nt7hm6.js";import"../chunk-swmf6w3z.js";import"../chunk-3dkv4989.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
2
+ import{ua as B,va as D}from"../chunk-qtz4g4kv.js";import"../chunk-eydww2nn.js";import"../chunk-kzz2nfzf.js";import{Pa as J}from"../chunk-8szsd6vy.js";import"../chunk-j13jmjkr.js";import"../chunk-ads3c8m0.js";function N(){return{name:"gemi-custom-request",enforce:"pre",async transform(G,H){let j=H.split("?",1)[0];if(j.includes("/node_modules/")||!B.test(j))return null;return{code:await D(G),map:null}}}}export{N as gemiRequestPlugin,J as gemiIslandPlugin};
3
3
 
4
4
  //# debugId=54630B516034F10064756E2164756E21
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gemi",
3
- "version": "0.225.0",
3
+ "version": "0.225.2",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "author": "Enes Tufekci <enes@gemijs.dev>",
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{Re as o}from"./chunk-vcw98sp6.js";import{Se as i}from"./chunk-qy0k2s5f.js";import{cl as t}from"./chunk-0k2r6bep.js";import{hm as r}from"./chunk-yj7pbbnm.js";class n extends i{register(){this.app.singleton(r,()=>new r(t(o(),this.app.config.get("translation",{}))))}}
3
- export{n as pb};
4
-
5
- //# debugId=3346283A1CCCAEED64756E2164756E21
@@ -1,11 +0,0 @@
1
- // @bun
2
- import{$d as t,Nd as xQ,Vd as S,Wd as s,Xd as Y5,Yd as G5,Zd as PQ,_d as k,ae as D,xd as QQ,zd as e}from"./chunk-kp7wcpx7.js";import{Nj as iQ}from"./chunk-qs2xvc8g.js";function KQ(Q,$,J){let Z=Q.on;if(Z===void 0)return!0;if(typeof Z!=="function")return Z.includes($.code);try{return Z($,J)===!0}catch{return!1}}var R5=4000,I5=60000;function gQ(Q){if(Q===void 0)return;let $=(J,Z)=>typeof J==="number"&&Number.isFinite(J)&&J>=Z;if(!Q||!$(Q.patienceMs,0)||Q.initialWaitMs!==void 0&&!$(Q.initialWaitMs,1)||Q.maxWaitMs!==void 0&&!$(Q.maxWaitMs,1)||Q.on!==void 0&&typeof Q.on!=="function"&&!(Array.isArray(Q.on)&&Q.on.every((J)=>typeof J==="string")))throw Error(`The provider's retry policy ${JSON.stringify(Q)} is not usable: patienceMs has to be a number of milliseconds (0 or more), initialWaitMs and maxWaitMs above 0, and on a list of error codes or a function.`)}function XQ(Q,$,J,Z,Y){let G=Q.patienceMs-Z;if(G<=0)return;let W=Q.maxWaitMs??I5,z=Q.initialWaitMs??R5,j=J!==void 0?Math.min(J,W):Math.round(Math.min(W,z*2**$)*(0.5+Y()*0.5));return Math.min(j,G)}var A5=500,uQ=20000;function T5(Q,$){if(!Q)return;let J=Q.trim();if(/^\d+(\.\d+)?$/.test(J))return Math.max(0,Number(J)*1000);let Z=Date.parse(J);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function r(Q,$){let J=Math.min(uQ,A5*2**Q);return Math.round(J*(0.5+$()*0.5))}function E5(Q){return Q===429||Q===408||Q===409||Q>=500}function w5(Q,$){return E5(Q)&&D($).retryable}function cQ(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function mQ(Q,$){return new Promise((J,Z)=>{let Y=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(Y),Z(cQ($))},{once:!0})})}async function BQ(Q,$,J=mQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((Y,G)=>{Z=()=>G(cQ($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function b(Q,$,J){let Z=J.fetchImpl??((V,X)=>fetch(V,X)),Y=J.sleep??mQ,G=J.random??Math.random,W=J.now??Date.now,z=Math.max(0,J.maxRetries),j=J.startedAt??W(),K=J.retry,B=(V,X,q,F)=>{let N=W()-j;try{J.onRetry?.({attempt:X+1,maxRetries:z,error:D(q),...k(q),timedOut:F,delayMs:V,elapsedMs:N,...K?{remainingMs:Math.max(0,K.patienceMs-N-V)}:{}})}catch{}return BQ(V,J.signal,Y)},H=(V,X,q,F)=>{if(!K)return;let{status:N}=k(q);if(!KQ(K,D(q),{...N?{status:N}:{},timedOut:F}))return;return XQ(K,V-z,X,W()-j,G)};for(let V=0;;V++){J.signal?.throwIfAborted();let X=new AbortController,q=()=>X.abort(J.signal?.reason);J.signal?.addEventListener("abort",q,{once:!0});let F=!1,N=J.timeoutMs>0?setTimeout(()=>{F=!0,X.abort()},J.timeoutMs):void 0,P;try{P=await Z(Q,{...$,signal:X.signal})}catch(I){if(N!==void 0)clearTimeout(N);if(J.signal?.removeEventListener("abort",q),J.signal?.aborted)throw I;let A=F?new s(J.timeoutMs):I;if(F&&J.retryTimeouts===!1)throw A;let T=V<z?r(V,G):H(V,void 0,A,F);if(T===void 0)throw A;await B(T,V,A,F);continue}if(N!==void 0)clearTimeout(N);if(P.ok)return P;J.signal?.removeEventListener("abort",q);let O=await k5(P),L=new S(P.status,O,P.headers.get("x-request-id")??P.headers.get("request-id")??void 0,T5(P.headers.get("retry-after"),W()));if(!w5(P.status,L))throw L;let g=L.retryAfter??(P.status===429?D(L).retryAfter:void 0),v=V>=z?H(V,g,L,!1):g===void 0?r(V,G):Math.min(g,uQ);if(v===void 0)throw L;await B(v,V,L,!1)}}async function k5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function dQ(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,Y=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!Y)return Q;let G=Y?performance.now()+Y:1/0,W=Q.getReader();return new ReadableStream({async pull(z){let j,K,B=Math.max(0,G-performance.now()),H=!Z||B<=Z,V=H?B:Z,X=new Promise((q,F)=>{j=setTimeout(()=>{K=H?J.max():J.idle(),F(K)},V)});try{let q=await Promise.race([W.read(),X]);if(q.done)z.close();else z.enqueue(q.value)}catch(q){let F=K??q;z.error(F),W.cancel(F).catch(()=>{})}finally{clearTimeout(j)}},cancel(z){return W.cancel(z)}},{highWaterMark:0})}var jQ=30000,pQ=10,lQ=7200,v5=600,h5="gpt-live-transcribe";function b5(Q){return Q.type==="transcription"}function y5(Q){if(Q.language!==void 0&&Q.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let Y of Q.keywords??[])if(/[<>\r\n]/.test(Y))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(Y)}.`);let $={model:Q.model??h5};if(Q.prompt!==void 0)$.prompt=Q.prompt;if(Q.keywords?.length)$.keywords=Q.keywords;if(Q.languages?.length)$.languages=Q.languages;if(Q.language!==void 0)$.language=Q.language;if(Q.delay!==void 0)$.delay=Q.delay;let J={transcription:$,turn_detection:Q.turnDetection?nQ(Q.turnDetection):null};if(Q.noiseReduction!==void 0)J.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Z={type:"transcription",audio:{input:J}};if(Q.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...Q.vendor}}function f5(Q){if(!Q)return{type:"object",properties:{}};return iQ(Q)?Q.toJSONSchema():Q}function a(Q,$){if(b5(Q))return y5(Q);let J={type:"realtime"},Z=Q.model??$;if(Z)J.model=Z;if(Q.instructions!==void 0)J.instructions=Q.instructions;if(Q.outputModalities)J.output_modalities=Q.outputModalities;if(Q.maxOutputTokens!==void 0)J.max_output_tokens=Q.maxOutputTokens;if(Q.truncation!==void 0)J.truncation=Q.truncation;if(Q.tools)J.tools=Q.tools.map((W)=>({type:"function",name:W.name,...W.description?{description:W.description}:{},parameters:f5(W.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let Y={};if(Q.turnDetection!==void 0)Y.turn_detection=Q.turnDetection&&nQ(Q.turnDetection);if(Q.transcription!==void 0)Y.transcription=Q.transcription;if(Q.noiseReduction!==void 0)Y.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let G={};if(Q.voice!==void 0)G.voice=Q.voice;if(Q.speed!==void 0)G.speed=Q.speed;if(Object.keys(Y).length||Object.keys(G).length)J.audio={...Object.keys(Y).length?{input:Y}:{},...Object.keys(G).length?{output:G}:{}};return{...J,...Q.vendor}}function nQ(Q){let $={type:Q.type};if(Q.createResponse!==void 0)$.create_response=Q.createResponse;if(Q.interruptResponse!==void 0)$.interrupt_response=Q.interruptResponse;if(Q.type==="semantic_vad"){if(Q.eagerness!==void 0)$.eagerness=Q.eagerness}else{if(Q.threshold!==void 0)$.threshold=Q.threshold;if(Q.prefixPaddingMs!==void 0)$.prefix_padding_ms=Q.prefixPaddingMs;if(Q.silenceDurationMs!==void 0)$.silence_duration_ms=Q.silenceDurationMs;if(Q.idleTimeoutMs!==void 0)$.idle_timeout_ms=Q.idleTimeoutMs}return $}function zQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},Y=Q?.input_token_details??Q?.input_tokens_details,G=Q?.output_token_details??Q?.output_tokens_details;if(typeof Y?.cached_tokens==="number")Z.cachedInputTokens=Y.cached_tokens;if(typeof Y?.audio_tokens==="number")Z.audioInputTokens=Y.audio_tokens;let W=Y?.cached_tokens_details?.audio_tokens;if(typeof W==="number")Z.cachedAudioInputTokens=W;if(typeof Y?.image_tokens==="number"&&Y.image_tokens>0)Z.imageInputTokens=Y.image_tokens;if(typeof G?.audio_tokens==="number")Z.audioOutputTokens=G.audio_tokens;return Z}class m extends Error{code;retryable;status;constructor(Q,$={}){super(Q.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=Q.code,this.retryable=Q.retryable,$.status!==void 0)this.status=$.status}}var g5=60;class o{model;target;options;constructor(Q,$){this.target=Q,this.options=$,this.model=$.model}url(Q){return`${this.target.base}/realtime${Q}${this.target.query}`}sidebandUrl(Q){let $=this.target.base.replace(/^http(s?):/i,(Z,Y)=>`ws${Y}:`),J=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${J}call_id=${encodeURIComponent(Q)}`}async createCall(Q){let $=Q.flow??this.options.callFlow??"unified",J,Z;if($==="ephemeral")J={authorization:`Bearer ${(await this.clientSecret({session:Q.session,ttlSeconds:g5,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let j=new FormData;j.set("sdp",Q.sdp),j.set("session",JSON.stringify(a(Q.session??{},this.model))),J=await this.target.headers(),Z=j}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=this.url("/calls"),G=await this.request(Q.webrtcFilter?`${Y}${Y.includes("?")?"&":"?"}webrtcfilter=on`:Y,{method:"POST",headers:J,body:Z},Q.signal),W=await G.text(),z=c5(G);if(!z)throw new m({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:W,callId:z}}async clientSecret(Q={}){let $=Q.ttlSeconds??v5;if(!Number.isInteger($)||$<pQ||$>lQ)throw RangeError(`ttlSeconds must be a whole number from ${pQ} to ${lQ}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let Y=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:a(Q.session??{},this.model)})},Q.signal)).json();if(typeof Y?.value!=="string")throw new m({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:Y.value,expiresAt:Number(Y.expires_at??0),session:Y.session,callsUrl:this.url("/calls")}}async hangup(Q,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(Q)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(J){if(u5(J,Q))return;throw J}}sideband(Q,$={}){return new HQ({...$,callId:Q,url:this.sidebandUrl(Q),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(Q)})}async request(Q,$,J){try{return await b(Q,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:J,fetchImpl:this.options.fetchImpl})}catch(Z){if(J?.aborted)throw Z;throw new m(D(Z),{cause:Z,...Z instanceof S?{status:Z.status}:{}})}}}function u5(Q,$){if(!(Q instanceof m)||Q.status!==404)return!1;let J=Q.cause instanceof S?Q.cause.body:void 0,Z=J?.error??J,Y=String(Z?.code??"").toLowerCase(),G=String(Z?.message??"").toLowerCase();if(Y.includes("call"))return!0;if(G.includes($.toLowerCase()))return!0;return/\bcall\b/.test(G)&&/not (be )?found|does not exist|no longer|ended/.test(G)}function c5(Q){let $=Q.headers.get("location");if(!$)return;let J=$.split("?")[0].replace(/\/+$/,""),Z=J.slice(J.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}var m5={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function d5(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=m5[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=zQ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=zQ($.usage);return $}var rQ=1,p5=500;function l5(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new J(Q,{headers:$.headers})}class HQ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(Q){this.init=Q,this.callId=Q.callId,this.ready=new Promise(($,J)=>{this.resolveReady=$,this.rejectReady=J}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(Q){if(this.finished||this.closing)return;let $=JSON.stringify(Q);if(this.socket?.readyState===rQ)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:a(Q)})}addItem(Q){this.send({type:"conversation.item.create",item:Q})}addNote(Q){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:Q}]})}functionOutput(Q,$){this.addItem({type:"function_call_output",call_id:Q,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(Q={}){let $={};if(Q.instructions!==void 0)$.instructions=Q.instructions;if(Q.toolChoice!==void 0)$.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};if(Q.outputModalities)$.output_modalities=Q.outputModalities;if(Q.conversation)$.conversation=Q.conversation;if(Q.metadata)$.metadata=Q.metadata;Object.assign($,Q.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(Q){this.send(Q?{type:"response.cancel",response_id:Q}:{type:"response.cancel"})}on(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}[Symbol.asyncIterator](){let Q={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(Q),{next:async()=>{for(;;){let J=Q.queue.shift();if(J)return{value:J,done:!1};if(Q.done)return this.subscribers.delete(Q),{value:void 0,done:!0};await new Promise((Z)=>Q.wake=Z),Q.wake=void 0}},return:async()=>{return Q.done=!0,Q.queue.length=0,this.subscribers.delete(Q),{value:void 0,done:!0}}}}close(Q=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=rQ)this.socket.close(Q,$);else this.finish(Q,$,!0)}async hangup(){try{await this.init.hangup()}catch(Q){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw Q}this.close(1000,"hangup")}async open(){let Q;try{let J=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);Q=(this.init.webSocket??l5)(this.init.url,{headers:J})}catch(J){return this.dropped(1006,J instanceof Error?J.message:String(J),!1)}this.socket=Q;let $=!1;Q.addEventListener("open",()=>{$=!0;let J=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let Y of this.outbox.splice(0))Q.send(Y);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=d5(J.data);if(Z)this.emit(Z)}),Q.addEventListener("close",(J)=>{if(this.socket!==Q)return;this.dropped(J.code??1006,J.reason??"",$)}),Q.addEventListener("error",()=>{})}dropped(Q,$,J){if(this.socket=void 0,this.closing)return this.finish(Q,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((Q!==1000||!J)&&this.failures<Z))return this.finish(Q,$,!1);this.failures+=1;let G=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),G)}finish(Q,$,J){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:Q,reason:$,byClient:J};this.finalEvent=Z,this.emit(Z);for(let Y of this.subscribers)Y.done=!0,Y.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${Q} ${$}).`));this.resolveClosed(Z)}emit(Q){if(this.backlog){if(this.backlog.push(Q),this.backlog.length>p5)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var oQ=3;function qQ(Q){let $=new Map;for(let J of Q)for(let Z of J.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function tQ(Q,$,J=new Map){if(!($ instanceof S))return[];if($.status!==400&&$.status!==404)return[];let Z=UQ($.body);if(!Z)return[];let Y=i5(Q.input);if(Y.length===0)return[];let G=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(G){let K=Q.input[Number(G[1])],B=FQ(K)[Number(G[2])],H=B&&typeof B.file_id==="string"?B.file_id:void 0;if(H)return[H]}let W=Z.message??"",z=aQ(Y.map((K)=>K.fileId).filter((K)=>n5(W,K)));if(z.length>0)return z;let j=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(W);if(j){let K=j[1].toLowerCase()==="image type"?"input_image":"input_file",B=j[2].toLowerCase(),H=aQ(Y.filter((X)=>X.type===K).map((X)=>X.fileId)),V=H.filter((X)=>(J.get(X)?.name??"").trim().toLowerCase().endsWith(`.${B}`));if(V.length===1)return V;if(V.length===0&&H.length===1)return H}return[]}function eQ(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let Y=FQ(Z);if(!Y.some((G)=>sQ(G,$)))return Z;return{...Z,content:Y.map((G)=>sQ(G,$)?{type:"input_text",text:d(J.get(String(G.file_id))?.name)}:G)}})}}function d(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function sQ(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function FQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function i5(Q){let $=[];for(let J of Q)for(let Z of FQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function UQ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof J.message==="string"?J.message:void 0,param:typeof J.param==="string"?J.param:void 0}}function n5(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function aQ(Q){return[...new Set(Q)]}function Q5(Q,$){if(!($ instanceof S))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=UQ($.body)?.message??"",Y=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!Y)return null;let G=(W)=>W?.type==="reasoning";if(!J.some((W)=>G(W)&&W.id===Y))return null;return{...Q,input:J.filter((W)=>!G(W))}}async function*NQ(Q){let $="",J="",Z=[],Y,G=()=>{if(Z.length===0&&!J)return null;let j={event:J,data:Z.join(`
3
- `),id:Y};return J="",Z=[],Y=void 0,j.data?j:null},W=(j)=>{let K=j.endsWith("\r")?j.slice(0,-1):j;if(K==="")return G();if(K.startsWith(":"))return null;let B=K.indexOf(":"),H=B===-1?K:K.slice(0,B),V=B===-1?"":K.slice(B+1);if(V.startsWith(" "))V=V.slice(1);if(H==="event")J=V;else if(H==="data")Z.push(V);else if(H==="id")Y=V;return null};for await(let j of Q){$+=j;let K=$.indexOf(`
4
- `);while(K!==-1){let B=$.slice(0,K);$=$.slice(K+1);let H=W(B);if(H)yield H;K=$.indexOf(`
5
- `)}}if($.length>0){let j=W($);if(j)yield j}let z=G();if(z)yield z}async function*$5(Q,$={}){let J=new Map,Z=new Set,Y,G=!1,W,z=(j,K)=>({type:"finish",reason:j,usage:K,...W?{model:W}:{}});for await(let j of NQ(Q)){if(j.data==="[DONE]")break;let K;try{K=JSON.parse(j.data)}catch{continue}let B=typeof K.type==="string"?K.type:j.event,H=K.response?.model;if(typeof H==="string"&&H)W=H;switch(B){case"response.output_text.delta":{let V=String(K.delta??"");if(!V)break;yield $.structuredOutput?{type:"output-delta",delta:V}:{type:"text-delta",delta:V};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let V=String(K.delta??"");if(!V)break;yield{type:"reasoning-delta",delta:V,id:K.item_id};break}case"response.output_item.added":{let V=K.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??K.item_id??V.call_id??"");J.set(X,{callId:String(V.call_id??X),name:String(V.name??""),namespace:typeof V.namespace==="string"&&V.namespace?V.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let V=J.get(String(K.item_id??""));if(!V)break;let X=String(K.delta??"");if(!X)break;yield{type:"tool-call-delta",toolCallId:V.callId,name:V.name,argsDelta:X,...V.namespace?{namespace:V.namespace}:{}};break}case"response.function_call_arguments.done":{let V=String(K.item_id??""),X=J.get(V);if(!X)break;X.done=!0,yield{type:"tool-call",toolCallId:X.callId,name:X.name,args:String(K.arguments??""),...X.namespace?{namespace:X.namespace}:{}};break}case"response.output_item.done":{let V=K.item;if(!V)break;if(V.type==="function_call"){let X=String(V.id??K.item_id??V.call_id??""),q=J.get(X);if(q?.done)break;let F=(typeof V.namespace==="string"?V.namespace:"")||q?.namespace;if(yield{type:"tool-call",toolCallId:String(V.call_id??X),name:String(V.name??q?.name??""),args:String(V.arguments??""),...F?{namespace:F}:{}},q)q.done=!0;break}if(V.type==="tool_search_call"||V.type==="tool_search_output"){if(V.type==="tool_search_call"&&V.arguments!==void 0)Y=V.arguments;let X=r5(V);if(X.loaded.length===0&&X.namespaces.length===0)break;let q=String(V.tool_search_call_id??V.id??"");if(Z.has(q))break;Z.add(q);let F=Y;Y=void 0,yield{type:"tool-search",...X,...F!==void 0&&F!==null?{arguments:F}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(K.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{G=!0,yield z("stop",CQ(K.response?.usage));break}case"response.incomplete":{G=!0;let V=CQ(K.response?.usage),X=K.response?.incomplete_details?.reason;if(X==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:s5(K.response?.content_filters),retryable:!1}},yield z("error",V);break}yield z(X==="max_output_tokens"?"length":"stop",V);break}case"response.failed":case"error":{G=!0;let V=K.response?.error??K.error??K;yield{type:"error",error:a5(V),...t(V)},yield z("error",CQ(K.response?.usage));break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield z("error",M())}function r5(Q){let $=[],J=[];return J5(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:LQ($),namespaces:LQ(J)}}function J5(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let Y of Q){if(typeof Y==="string"){$.push(Y);continue}if(!Y||typeof Y!=="object")continue;let G=Y,W=typeof G.name==="string"?G.name:typeof G.tool_name==="string"?G.tool_name:"",z=G.tools??G.functions;if(Array.isArray(z)){if(W)J.push(W);J5(z,$,J,Z+1);continue}if(W)$.push(W)}}function LQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function s5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let J=[];for(let Z of Q){if(!Z||typeof Z!=="object")continue;let Y=Z,G=Y.content_filter_results;if(!G||typeof G!=="object")continue;for(let[W,z]of Object.entries(G))if(z&&typeof z==="object"&&z.filtered===!0)J.push(`${W} (${String(Y.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${LQ(J).join(", ")}.`}function a5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",J=String(Q?.code??"").toLowerCase();if(J==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(J==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(J.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function CQ(Q){if(!Q)return M();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},Y=Q.output_tokens_details?.reasoning_tokens;if(typeof Y==="number")Z.reasoningTokens=Y;let G=Q.input_tokens_details?.cached_tokens;if(typeof G==="number")Z.cachedInputTokens=G;return Z}async function*Z5(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:Y,value:G}=await $.read();if(Y)break;if(G)yield J.decode(G,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function $Q(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,streamIdleTimeoutMs:Q.streamIdleTimeoutMs,streamMaxDurationMs:Q.streamMaxDurationMs,maxToolArgumentChars:Q.maxToolArgumentChars,maxRetries:Q.maxRetries,...Q.retry?{retry:Q.retry}:{}}}async function*JQ(Q,$,J){let Z=J.parse??$5,Y=$,G=new Set,W=0,z=!1,j=Math.max(0,Q.maxRetries),K=Q.random??Math.random,B,H=(O)=>{if(!B)return O;let L=e(e(M(),B),O.usage);return B=void 0,{...O,usage:L}},V=()=>H({type:"finish",reason:"aborted",usage:M()}),X=Q.streamIdleTimeoutMs??0,q=Q.streamMaxDurationMs??0,F=Q.maxToolArgumentChars??0,N=Q.now??Date.now,P=N();for(let O=0;;O++){let L=new AbortController,g=J.signal?AbortSignal.any([J.signal,L.signal]):L.signal,v;while(v===void 0)try{let C=[],U=()=>{},R=b(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(Y)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:g,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:P,...Q.retry?{retry:Q.retry}:{},onRetry:(h)=>{C.push({type:"retry",...h,phase:"request"}),U()}}),w=R.then(()=>!0,()=>!0);for(;;){let h=new Promise((n)=>U=()=>n(!1)),c=await Promise.race([w,h]);if(yield*C.splice(0),c)break}v=await R}catch(C){let U=Y,R=J.files&&W<oQ?tQ(U,C,J.files).filter((c)=>!G.has(c)):[];if(R.length>0){W++;let c=D(C).message;for(let n of R)G.add(n),yield{type:"file-rejected",fileId:n,message:c,...k(C)};Y=eQ(U,new Set(R),J.files);continue}let w=z?null:Q5(Y,C);if(w){z=!0,Y=w;continue}let h=D(C);if(h.code==="aborted"){yield V();return}yield{type:"error",error:h,...k(C)},yield H({type:"finish",reason:"error",usage:M()});return}let I=[],A=!1,T,WQ=!1,_,u=new Map;try{let C=dQ(v.body,{idleMs:X,maxMs:q},{idle:()=>{let U=new Y5(X);return L.abort(U),U},max:()=>{let U=new G5(q);return L.abort(U),U}});for await(let U of Z(Z5(C),{structuredOutput:J.structuredOutput})){if(U.type==="tool-call-delta"){let R=(u.get(U.toolCallId)??0)+U.argsDelta.length;if(u.set(U.toolCallId,R),F>0&&R>F){let w=new PQ(F,U.name,U.toolCallId,R);throw L.abort(w),w}yield U;continue}if(U.type==="tool-call")u.delete(U.toolCallId);if(A){yield U.type==="finish"?H(U):U;continue}if(QQ(U)){A=!0,yield*I.splice(0),yield U;continue}if(U.type==="error")T=U.error;I.push(U)}}catch(C){WQ=C instanceof s;let U=D(C);if(U.code==="aborted"||J.signal?.aborted){yield V();return}if(C instanceof PQ)_=C.detail;if(A){yield{type:"error",error:U,..._?{toolArgumentsTooLong:_}:{}},yield H({type:"finish",reason:"error",usage:M()});return}T=U,I.push({type:"error",error:U,..._?{toolArgumentsTooLong:_}:{}},{type:"finish",reason:"error",usage:M()})}if(A)return;let l={};for(let C of I)if(C.type==="error")l=k(C);let i=!T?.retryable||J.signal?.aborted||_&&J.retryToolArgumentsTooLong===!1?void 0:O<j?r(O,K):Q.retry&&KQ(Q.retry,T,{...l.status!==void 0?{status:l.status}:{},timedOut:WQ,..._?{toolArgumentsTooLong:_}:{}})?XQ(Q.retry,O-j,T.retryAfter,N()-P,K):void 0;if(i!==void 0){for(let U of I)if(U.type==="finish")B=e(B??M(),U.usage);if(u.size>0)yield{type:"tool-call-discard",toolCallIds:[...u.keys()]};let C=N()-P;yield{type:"retry",attempt:O+1,maxRetries:j,error:T,...l,phase:"stream",timedOut:WQ,..._?{toolArgumentsTooLong:_}:{},delayMs:i,elapsedMs:C,...Q.retry?{remainingMs:Math.max(0,Q.retry.patienceMs-C-i)}:{}};try{await BQ(i,J.signal,Q.sleep)}catch{yield V();return}continue}for(let C of I)yield C.type==="finish"?H(C):C;return}}async function ZQ(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let G=await(await b(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}async function YQ(Q,$){let J=Q.filesUrl.indexOf("?"),Z=J===-1?Q.filesUrl:Q.filesUrl.slice(0,J),Y=J===-1?"":Q.filesUrl.slice(J);try{await(await b(`${Z}/${encodeURIComponent($)}${Y}`,{method:"DELETE",headers:await Q.headers()},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl,...Q.sleep?{sleep:Q.sleep}:{},...Q.random?{random:Q.random}:{}})).body?.cancel()}catch(G){if(G instanceof S&&G.status===404)return;throw G}}function DQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:o5(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let Y=V6(Q.tools,J);if(Y.length>0){if(Z.tools=Y,!J.parallelToolCalls)Z.parallel_tool_calls=!1;if(Q.toolChoice!==void 0)Z.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name}}if(Q.output)Z.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&J.reasoning)Z.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")Z.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")Z.max_output_tokens=Q.maxOutputTokens;if(Q.promptCacheKey)Z.prompt_cache_key=Q.promptCacheKey;return Z}function o5(Q,$,J){let Z=[],Y=new Map;if($.toolSearch){for(let G of J??[])if(GQ(G))Y.set(G.name,G)}for(let G of Q){let W=G.role,z=!Z6.has(G.finishReason),j=[],K=()=>{if(j.length===0)return;Z.push({type:"message",role:W,content:j}),j=[]};for(let B of G.content??[])switch(B.type){case"text":{if(!B.text)break;j.push(y(W,B.text));break}case"output":{if(B.partial)break;j.push(y(W,JSON.stringify(B.value)));break}case"file":{if(W==="assistant")break;let H=OQ(B);if(!$.fileInput){if(H)j.push(y(W,p(B,!1)));break}if(MQ(B,H),B.providerRejected){if(H)j.push(y(W,p(B,!1)));j.push(y(W,d(B.name)));break}if(H)j.push(y(W,p(B,!!B.fileId)));if(B.fileId)j.push(Q6(B));break}case"reasoning":{if(K(),!z)break;let H=Y6(B);if(H)Z.push(H);break}case"tool-call":{if(B.partial)break;if(K(),$.toolSearch&&Array.isArray(B.toolSearches))for(let V of B.toolSearches)Z.push(...G6(V,J??[]));let H={type:"function_call",call_id:B.toolCallId,name:String(B.name),arguments:JSON.stringify(B.input??{})};if(B.namespace&&Y.has(B.namespace))H.namespace=B.namespace;Z.push(H);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:B.toolCallId,output:_Q(B)});break}}K()}return e5(Z)}var t5="No result was recorded for this tool call. Assume it did not complete.";function e5(Q){let $=new Set,J=new Set,Z=[];for(let G of Q){if(G.type==="function_call"){let W=String(G.call_id);if($.has(W))continue;$.add(W)}else if(G.type==="function_call_output"){let W=String(G.call_id);if(!$.has(W)||J.has(W))continue;J.add(W)}Z.push(G)}if(J.size===$.size)return Z;let Y=[];for(let G of Z){if(Y.push(G),G.type!=="function_call")continue;let W=String(G.call_id);if(J.has(W))continue;J.add(W),Y.push({type:"function_call_output",call_id:W,output:t5})}return Y}function y(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function OQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(xQ)?$:void 0}function p(Q,$){let J=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)J.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)J.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let Z=`attachment ${J.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function Q6(Q){return{type:SQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function SQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":$6(Q.name)}function MQ(Q,$){if(Q.fileId?.startsWith(xQ))throw Error(`FilePart.fileId holds a gemi attachment id (${Q.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Q.fileId&&!$)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.")}function $6(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&J6.has($[1])}var J6=new Set(["jpeg","jpg","png","gif","webp"]),Z6=new Set(["error","aborted","interrupted"]);function Y6(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function _Q(Q){if(Q.status==="ok"){let $=Q.modelOutput!==void 0?Q.modelOutput:Q.output;return typeof $==="string"?$:JSON.stringify($??null)}if(Q.status==="running"){let $=Q.job?.summary===void 0?"":` Started with: ${JSON.stringify(Q.job.summary)}.`;return`Started background job ${Q.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;if(Q.cause==="denied-earlier")return`The user already declined this tool call earlier in this conversation, so it did not run and they were not asked again. Do not ask for it again; carry on without it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function G6(Q,$){let J=new Set(V5(Q?.loaded)),Z=V5(Q?.namespaces),Y=new Set(Z),G=[];for(let z of $)if(GQ(z)){if(!Y.has(z.name))continue;let j=z.tools.filter((K)=>J.size===0||J.has(K.name));if(j.length===0)continue;G.push({type:"namespace",name:z.name,description:z.description,tools:j.map((K)=>f(K,!0))})}else if(z.deferred&&J.has(z.name))G.push(f(z,!0));if(G.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:Z.length>0?Z:[...J]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:G}]}function V5(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function GQ(Q){return Array.isArray(Q.tools)}function V6(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let Y=[];for(let G of Q)if(GQ(G))for(let W of G.tools)Y.push(f(W,!1));else Y.push(f(G,!1));return Y}let J=[],Z=!1;for(let Y of Q)if(GQ(Y)){let G=Y.tools.map((W)=>{if(W.deferred)Z=!0;return f(W,!0)});J.push({type:"namespace",name:Y.name,description:Y.description,tools:G})}else{if(Y.deferred)Z=!0;J.push(f(Y,!0))}if(Z)J.push({type:"tool_search"});return J}function f(Q,$){let J={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)J.defer_loading=!0;return J}var W6=64000;function W5(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??W6,messages:L6(Q.messages,$.capabilities),stream:!0},Z=Q.output,Y=!!Z?.strict&&!F6(Z.schema),G=Z&&!Y?U6(Z.schema):void 0,W=[Q.systemPrompt,G].filter(Boolean);if(W.length>0)J.system=[{type:"text",text:W.join(`
6
-
7
- `)}];let z=$.capabilities.reasoning?Q.reasoning:void 0;if(z==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(z)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:X6(z,$.modelId)};else if($.capabilities.reasoning&&K6(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&Y)J.output_config={...J.output_config,format:{type:"json_schema",schema:q6(Z.schema)}};let j=I6(Q.tools);if(j.length>0){J.tools=j;let K=C6(Q.toolChoice,$.forcedToolChoice);if(!$.capabilities.parallelToolCalls)K.disable_parallel_tool_use=!0;if(Q.toolChoice!==void 0||K.disable_parallel_tool_use)J.tool_choice=K}return B6(J)}function K6(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var RQ="thinking-binding-controls-2026-08-01";function K5(Q){if(/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(Q))return"thinking";if(/schema is too complex/i.test(Q))return"schema";return}function X5(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((G)=>G.type!=="thinking"&&G.type!=="redacted_thinking");if(Z.length===0)continue;let Y=$.at(-1);if(Y?.role===J.role)Y.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function X6(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function B6(Q){let $=(Z)=>{if(Z)Z.cache_control={type:"ephemeral"}};$(Q.tools?.at(-1)),$(Q.system?.at(-1));let J=Q.messages.at(-1)?.content??[];return $([...J].reverse().find((Z)=>Z.type!=="thinking"&&Z.type!=="redacted_thinking")),Q}var H6=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),j6=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),z6=/\\[1-9]|\(\?<?[=!]|\\[bB]/,B5=new Set(["properties","patternProperties","$defs","definitions"]);function q6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!E(J))return J;let Z={},Y=[];for(let[G,W]of Object.entries(J)){if(H6.has(G)||G==="minItems"&&typeof W==="number"&&W>1||G==="format"&&typeof W==="string"&&!j6.has(W)||G==="pattern"&&typeof W==="string"&&z6.test(W)){Y.push(`${G}: ${JSON.stringify(W)}`);continue}Z[G]=B5.has(G)&&E(W)?Object.fromEntries(Object.entries(W).map(([j,K])=>[j,$(K)])):$(W)}if(Y.length>0){let G=`{${Y.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${G}`:G}if(Z.type==="object"||E(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function F6(Q){let $=0,J=0,Z=(Y)=>{if(Array.isArray(Y))return Y.forEach(Z);if(!E(Y))return;if(Array.isArray(Y.anyOf)||Array.isArray(Y.type))J++;if(E(Y.properties)){let G=new Set(Array.isArray(Y.required)?Y.required:[]);$+=Object.keys(Y.properties).filter((W)=>!G.has(W)).length}for(let[G,W]of Object.entries(Y))if(B5.has(G)&&E(W))Object.values(W).forEach(Z);else Z(W)};return Z(Q),$>24||J>16}function U6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
8
- ${JSON.stringify(Q)}`}function C6(Q,$){if(Q==="none")return{type:"none"};if(Q==="required")return $?{type:"any"}:{type:"auto"};if(Q&&typeof Q==="object")return $?{type:"tool",name:Q.name}:{type:"auto"};return{type:"auto"}}function L6(Q,$){let J=[],Z=new Map;for(let B of Q){let H=B.role==="assistant"?"assistant":"user";J.push("step-end");for(let V of B.content??[])switch(V.type){case"text":{if(H==="assistant"?!!V.text:!!V.text?.trim())J.push({role:H,block:{type:"text",text:V.text}});break}case"output":{if(V.partial)break;let X=V.text??JSON.stringify(V.value);J.push({role:H,block:{type:"text",text:X}});break}case"file":{if(H==="assistant")break;for(let X of S6(V,$))J.push({role:H,block:X});break}case"reasoning":{let X=H==="assistant"?O6(V):void 0;if(X)J.push({role:H,block:X});break}case"tool-call":{if(V.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:V.toolCallId,name:String(V.name),input:E(V.input)?V.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(V.toolCallId))break;Z.set(V.toolCallId,{type:"tool_result",tool_use_id:V.toolCallId,content:_Q(V),...V.status==="error"?{is_error:!0}:{}});break}}}let Y=[],G=(B,H)=>{let V=Y[Y.length-1];if(V&&V.role===B)V.content.push(H);else Y.push({role:B,content:[H]})},W=new Set,z=[],j=!1,K=()=>{for(let B of z)G("user",Z.get(B)??D6(B));z=[],j=!1};for(let B of J){if(B==="step-end"){j=!0;continue}let{role:H,block:V}=B;if(j||H==="user")K();if(V.type==="tool_use"){let X=String(V.id);if(W.has(X))continue;W.add(X),z.push(X)}G(H,V)}if(K(),Y[0]?.role==="assistant")Y.unshift({role:"user",content:[{type:"text",text:N6}]});if(Y.at(-1)?.role==="assistant")Y.push({role:"user",content:[{type:"text",text:P6}]});return Y}var N6="(The conversation continues from an earlier point.)",P6="Continue.",x6="No result was recorded for this tool call. Assume it did not complete.";function D6(Q){return{type:"tool_result",tool_use_id:Q,content:x6}}function O6(Q){let $=Q.providerMetadata?.anthropic;if(!E($))return;if($.type==="thinking"&&typeof $.signature==="string")return{type:"thinking",thinking:Q.text??"",signature:$.signature};if($.type==="redacted_thinking"&&typeof $.data==="string")return{type:"redacted_thinking",data:$.data};return}function S6(Q,$){let J=OQ(Q),Z=(G)=>J?[{type:"text",text:p(Q,G)}]:[];if(!$.fileInput)return Z(!1);if(MQ(Q,J),!Q.fileId)return Z(!1);let Y=Q.providerRejected?void 0:_6(Q);if(!Y)return[...Z(!1),{type:"text",text:d(Q.name)}];return[...Z(!0),{type:Y,source:{type:"file",file_id:Q.fileId}}]}var M6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function _6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(SQ(Q))return!$||M6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function E(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function R6(Q){return Array.isArray(Q.tools)}function I6(Q){let $=[];for(let J of Q??[])for(let Z of R6(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*q5(Q,$={}){let J=new Map,Z=[],Y,G={},W,z,j=!1,K=(B)=>({type:"finish",reason:B,usage:k6(G),...Y?{model:Y}:{}});for await(let B of NQ(Q)){let H;try{H=JSON.parse(B.data)}catch{continue}switch(typeof H.type==="string"?H.type:B.event){case"message_start":{let X=H.message??{};if(typeof X.model==="string"&&X.model)Y=X.model;G=z5(G,X.usage);break}case"content_block_start":{let X=Number(H.index),q=H.content_block??{},F={type:String(q.type??""),id:typeof q.id==="string"?q.id:void 0,name:typeof q.name==="string"?q.name:void 0,args:"",signature:typeof q.signature==="string"?q.signature:""};if(J.set(X,F),F.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(q.data??"")}}};if(F.type==="text"&&typeof q.text==="string"&&q.text)yield j5(q.text,$);break}case"content_block_delta":{let X=J.get(Number(H.index)),q=H.delta??{};if(!X)break;if(q.type==="text_delta"){let F=String(q.text??"");if(F)yield j5(F,$)}else if(q.type==="thinking_delta"){let F=String(q.thinking??"");if(F)yield{type:"reasoning-delta",delta:F}}else if(q.type==="signature_delta")X.signature+=String(q.signature??"");else if(q.type==="input_json_delta"&&X.type==="tool_use"){let F=String(q.partial_json??"");if(!F)break;X.args+=F,yield{type:"tool-call-delta",toolCallId:X.id??"",name:X.name??"",argsDelta:F}}break}case"content_block_stop":{let X=Number(H.index),q=J.get(X);if(J.delete(X),q?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:q.signature}}};if(q?.type==="tool_use")if(q.args||="{}",A6(q.args))yield H5(q);else Z.push(q);break}case"message_delta":{if(typeof H.delta?.stop_reason==="string")W=H.delta.stop_reason;if(H.delta?.stop_details)z=H.delta.stop_details;G=z5(G,H.usage);break}case"message_stop":{if(j=!0,W==="refusal"){yield{type:"error",error:E6(z)},yield K("error");break}let X=T6(W);if(Z.length>0&&X==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((q)=>q.id??"")};else for(let q of Z)yield H5(q);yield K(X);break}case"error":{j=!0;let X=H.error??H;yield{type:"error",error:w6(X),...t(X)},yield K("error");break}}if(j)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function H5(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function A6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function j5(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function T6(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function E6(Q){let $=typeof Q?.explanation==="string"?Q.explanation:"",J=typeof Q?.category==="string"?` (${Q.category})`:"";return{code:"content_filtered",message:$||`The model declined to answer${J}.`,retryable:!1}}function w6(Q){let $=String(Q?.type??"").toLowerCase(),J=typeof Q?.message==="string"?Q.message:"The provider stream failed.";if($==="rate_limit_error")return{code:"rate_limited",message:J,retryable:!0};if($==="invalid_request_error"||$==="request_too_large")return{code:/prompt is too long|request_too_large/i.test(`${$} ${J}`)?"context_length_exceeded":"provider_error",message:J,retryable:!1};if($==="authentication_error"||$==="permission_error"||$==="billing_error"||$==="not_found_error")return{code:"provider_error",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function z5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let Y of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[Y]==="number")J[Y]=$[Y];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function k6(Q){if(!Q)return M();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),Y=Q.output_tokens??0,G={inputTokens:Z,outputTokens:Y,totalTokens:Z+Y};if(typeof $==="number")G.cachedInputTokens=$;if(typeof J==="number")G.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")G.reasoningTokens=Q.thinking_tokens;return G}function IQ(Q){let $=TQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:!0};let J=h6($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:F5(J),supportsForcedToolChoice:!0};if(J?.kind==="gpt")return{reasoning:J.major>=5,structuredOutput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:F5(J),supportsForcedToolChoice:!0};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0,supportsForcedToolChoice:!0}}function F5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function AQ(Q){let $=TQ(Q),J=/^claude-(?:opus|sonnet|haiku)-4(?:-(\d{1,2}))?(?:-\d{8})?$/.exec($);return{reasoning:!(/^claude-(?:3|2|instant)/.test($)||!!J&&Number(J[1]??0)<=5),structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!1,supportsForcedToolChoice:v6(Q)}}function v6(Q){let $=TQ(Q);return/^claude-(?:3|2|instant)/.test($)||/^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test($)||/^claude-(?:opus|sonnet|fable|mythos)-5(?:-\d{8})?$/.test($)||/^claude-haiku-5-5(?:-\d{8})?$/.test($)}function TQ(Q){return Q.trim().toLowerCase()}function h6(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let J=/^o(\d+)(?:[-.]|$)/.exec(Q);if(J?.[1])return{kind:"o",major:Number(J[1]),minor:0};return null}var EQ=120000,wQ=2,kQ=120000,vQ=300000;function x(Q){return typeof process>"u"?void 0:process.env?.[Q]}var b6="preview";function U5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function y6(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function hQ(Q,$={}){return{base:(Q.baseURL??x("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??x("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??EQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??kQ,streamMaxDurationMs:Q.streamMaxDurationMs??vQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??wQ,...yQ(Q)}}function C5(Q){let $=Q.baseURL??Q.endpoint??x("AZURE_OPENAI_ENDPOINT");if($)return U5($);let J=Q.resourceName??x("AZURE_OPENAI_RESOURCE_NAME")??x("AZURE_RESOURCE_NAME");return J?U5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function bQ(Q,$={}){let J=Q.apiVersion??x("AZURE_OPENAI_API_VERSION")??b6;return{base:`${C5(Q)}${y6(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??x("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??EQ,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??kQ,streamMaxDurationMs:Q.streamMaxDurationMs??vQ,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??wQ,...yQ(Q)}}var f6="2026-10-21";function L5(Q,$={}){let J=Q.baseURL??x("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return P5(J,Q,$,async()=>{let Z=Q.workspaceId??x("ANTHROPIC_WORKSPACE_ID"),Y=Z?{"anthropic-workspace-id":Z}:{},G=Q.apiKey??x("ANTHROPIC_API_KEY");if(G)return{"x-api-key":G,...Y};let W=x("ANTHROPIC_AUTH_TOKEN");return W?{authorization:`Bearer ${W}`,...Y}:Y})}function N5(Q,$={}){let J=Q.resourceName??x("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??x("ANTHROPIC_FOUNDRY_BASE_URL")??(J?`https://${J.trim()}.services.ai.azure.com/anthropic`:"");if(!Z.trim())throw Error("AzureAnthropicProvider has no Foundry endpoint. Set `endpoint` (the deployment's Target URI without `/v1/messages`, e.g. `https://<resource>.services.ai.azure.com/anthropic`) or `resourceName`, or the ANTHROPIC_FOUNDRY_BASE_URL or ANTHROPIC_FOUNDRY_RESOURCE environment variable.");return P5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let Y=Q.apiKey??x("ANTHROPIC_FOUNDRY_API_KEY");return Y?{"api-key":Y}:{}})}function P5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":f6,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??EQ,streamIdleTimeoutMs:$.streamIdleTimeoutMs??kQ,streamMaxDurationMs:$.streamMaxDurationMs??vQ,maxToolArgumentChars:$.maxToolArgumentChars??0,maxRetries:$.maxRetries??wQ,...yQ($)}}function x5(Q,$={}){return{...bQ(Q,$),base:`${C5(Q)}/v1`,query:""}}function yQ(Q){return gQ(Q.retry),Q.retry?{retry:Q.retry}:{}}class VQ{static models(){return[]}normalizeError(Q){return D(Q)}}var D5=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class O5 extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=IQ(Q),this.config=$}static model(Q,$){return new O5(Q,$)}static models(){return D5}stream(Q){let $=DQ(Q,{model:this.model,capabilities:this.capabilities});return JQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:qQ(Q.messages)})}upload(Q){return ZQ(this.endpoint(),Q)}deleteFile(Q){return YQ(this.endpoint(),Q)}endpoint(){return $Q(hQ(this.config))}get realtime(){return new o(hQ(this.config,{timeoutMs:jQ}),{model:this.model})}}var g6=["claude-opus-5-5","claude-sonnet-5-5","claude-haiku-5-5","claude-fable-5-2","claude-fable-5-1","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-opus-4-8","claude-sonnet-4-6","claude-haiku-4-5"];class fQ extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=AQ(Q),this.config=$}static model(Q,$){return new fQ(Q,$)}static models(){return g6}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let Y=this.request($);if(J)Y=X5(Y);let G,W=!1;for await(let z of JQ(this.endpointFor(Y),Y,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),parse:q5})){if(G)continue;if(!W&&z.type==="error"&&z.status===400){let j=K5(z.error.message);if(j&&!Z.has(j)){Z.add(j),G=j;continue}}if(QQ(z))W=!0;yield z}if(!G)return;if(G==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return W5(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:this.capabilities.supportsForcedToolChoice!==!1,blockBinding:this.bindsThinking()})}endpointFor(Q){let $=this.endpoint();if(!(Q.thinking?.type==="adaptive"&&Q.thinking.block_binding))return $;return{...$,headers:async()=>{let Z=await $.headers(),Y=Z["anthropic-beta"];return{...Z,"anthropic-beta":Y?`${Y},${RQ}`:RQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return ZQ(this.endpoint(),Q,null)}deleteFile(Q){return YQ(this.endpoint(),Q)}endpoint(){return S5(L5(this.config))}}function S5(Q){return{...$Q(Q),responsesUrl:`${Q.base}/messages`}}class M5 extends fQ{constructor(Q,$={}){super(Q,$);this.capabilities={...AQ(Q),fileInput:!1}}static model(Q,$){return new M5(Q,$)}upload(Q){return Promise.reject(Error("AzureAnthropicProvider does not upload files: the Files API is not available on Azure-hosted Foundry deployments. The file is still stored by gemi and named to the model by its attachment id."))}deleteFile(Q){return Promise.reject(Error("AzureAnthropicProvider does not delete files: the Files API is not available on Azure-hosted Foundry deployments."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return S5(N5(this.config))}}class _5 extends VQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=IQ(Q),this.config=$}static model(Q,$){return new _5(Q,$)}static models(){return D5}stream(Q){let $=DQ(Q,{model:this.deployment(),capabilities:this.capabilities});return JQ(this.endpoint(),$,{signal:Q.signal,retryToolArgumentsTooLong:Q.retryToolArgumentsTooLong,structuredOutput:Boolean(Q.output),files:qQ(Q.messages)})}upload(Q){return ZQ(this.endpoint(),Q,"assistants")}deleteFile(Q){return YQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return $Q(bQ(this.config))}get realtime(){return new o(x5(this.config,{timeoutMs:jQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
9
- export{b as ca,hQ as da,bQ as ea,HQ as fa,h5 as ga,zQ as ha,m as ia,o as ja,u5 as ka,VQ as la,O5 as ma,fQ as na,M5 as oa,_5 as pa};
10
-
11
- //# debugId=84C6C2E434920B7C64756E2164756E21
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{Qj as P}from"./chunk-qs2xvc8g.js";class X extends Error{retryable;constructor(J,Q={}){super(J,Q.cause!==void 0?{cause:Q.cause}:void 0);this.name="ToolError",this.retryable=Q.retryable??!0}}var I={provider_error:"The model provider returned an error.",rate_limited:"The model provider is rate limiting requests. Try again shortly.",context_length_exceeded:"The conversation is too long for the model.",content_filtered:"The model provider's content filter blocked this request.",invalid_tool_input:"The model provider rejected the request.",tool_error:"A tool failed.",unknown:"The run failed unexpectedly."};function U(J,Q){if(Q.source==="tool"){if(Q.cause instanceof X)return J;return{...J,message:`The tool "${Q.toolName}" failed with an unexpected error.`}}let V=I[J.code];return V===void 0?J:{...J,message:V}}function l(J,Q,V,Y){let Z;try{Z=(J??U)(Q,V)}catch(K){Y(K),Z=U(Q,V)}return{code:Z.code,message:Z.message,...Z.toolCallId!==void 0?{toolCallId:Z.toolCallId}:{},retryable:Z.retryable}}var _=new WeakMap;function h(J,Q){if(J!==Q)_.set(J,Q)}function c(J){return _.get(J)??J}class O extends X{id;code="attachment_not_found";constructor(J){super(`No attachment ${J}.`);this.id=J;this.name="AttachmentNotFoundError"}}class q extends X{code="invalid_attachment_scope";constructor(J){super(J);this.name="InvalidAttachmentScopeError"}}function B(J){if(!J||typeof J.key!=="string"||J.key.length===0)throw new q("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return J}var T="gemi_att_";function S(){return`${T}${crypto.randomUUID()}`}class F{store;storage;scope;lifetime;constructor(J,Q,V,Y=null){this.store=J;this.storage=Q;this.scope=V;this.lifetime=Y;B(V)}withLifetime(J){return new F(this.store,this.storage,this.scope,J)}get scopeKey(){return this.scope.key}async get(J){let Q=await this.store.find(this.scope,J);if(!Q||Q.scopeKey!==this.scope.key||j(Q,Date.now()))throw new O(J);return Q}async read(J){return await this.readRecord(J,await this.get(J))}async readRecord(J,Q){if(!Q.objectName)throw new O(J);return await this.storage.read({name:Q.objectName})}async file(J){let Q=await this.get(J),Y=(await this.readRecord(J,Q)).body,Z=Y instanceof Blob?Y:Y?await new Response(Y).blob():new Blob([]);return new File([Z],Q.name,{type:Q.mimeType})}async put(J,Q={}){let V=S(),Y=Q.mimeType??J.type??"",Z=Q.name??(J instanceof File?J.name:V),K=await this.storage.put({name:E(V,Z),body:J,contentType:Y||void 0}),$={id:V,scopeKey:this.scope.key,objectName:K,name:Z,mimeType:Y||"application/octet-stream",size:J.size,createdAt:new Date().toISOString(),destination:Q.fileId?"both":"storage",...Q.fileId?{fileId:Q.fileId}:{},...this.lifetime?this.lifetime.next():{}};return await this.store.put(this.scope,$),this.lifetime?.onPut?.($),$}}function j(J,Q){if(!J.expiresAt)return!1;let V=Date.parse(J.expiresAt);return Number.isFinite(V)&&V<=Q}function i(J,Q,V=Date.now()){if(J===null||J===void 0)return null;if(J==="turn")return{expiresAt:new Date(V+Q).toISOString(),deleteAfterTurn:!0};let Y=J?.ttlMs;if(typeof Y!=="number"||!Number.isFinite(Y)||Y<=0)throw Error(`attachmentRetention() must answer "turn", { ttlMs } with a positive number of milliseconds, or null; it answered ${JSON.stringify(J)}.`);return{expiresAt:new Date(V+Y).toISOString()}}async function s(J,Q){if(J.objectName){if(!Q.storage.delete)throw Error(`Cannot delete attachment ${J.id}: the controller's attachmentStorage has no delete().`);await Q.storage.delete({name:J.objectName})}if(J.fileId){if(!Q.provider?.deleteFile)throw Error(`Cannot delete the provider copy of attachment ${J.id}: the agent's provider has no deleteFile().`);await Q.provider.deleteFile(J.fileId),await Q.fileOwners?.delete?.(J.fileId)}if(!Q.store.delete)throw Error(`Cannot delete attachment ${J.id}: the controller's attachment store has no delete().`);await Q.store.delete({key:J.scopeKey},J.id)}function E(J,Q){let V=/\.([A-Za-z0-9]{1,8})$/.exec(Q);return`attachments/${J}${V?`.${V[1].toLowerCase()}`:""}`}class C{rows=new Map;async put(J,Q){B(J),this.rows.set(Q.id,{...Q,scopeKey:J.key})}async find(J,Q){B(J);let V=this.rows.get(Q);if(!V||V.scopeKey!==J.key)return null;return V}async delete(J,Q){B(J);let V=this.rows.get(Q);if(V&&V.scopeKey===J.key)this.rows.delete(Q)}async expired(J,Q){let V=[];for(let Y of this.rows.values()){if(V.length>=Q)break;if(j(Y,J.getTime()))V.push(Y)}return V}get size(){return this.rows.size}}var o=new C;class z extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function t(J,Q){if(Q.aborted)return Promise.reject(new z);return new Promise((V,Y)=>{let Z=()=>Y(new z);Q.addEventListener("abort",Z,{once:!0}),J.then(V,Y).finally(()=>Q.removeEventListener("abort",Z))})}function e(J){switch(J.type){case"text-delta":case"reasoning-delta":case"tool-call-delta":case"tool-call":case"tool-search":case"output-delta":return!0;default:return!1}}function JJ(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function QJ(J,Q){if(!Q)return J;let V={inputTokens:J.inputTokens+(Q.inputTokens??0),outputTokens:J.outputTokens+(Q.outputTokens??0),totalTokens:J.totalTokens+(Q.totalTokens??0)};for(let Y of M)if(Q[Y]!==void 0||J[Y]!==void 0)V[Y]=(J[Y]??0)+(Q[Y]??0);return V}var M=["reasoningTokens","cachedInputTokens","cacheWriteInputTokens","imageInputTokens","imageOutputTokens","audioInputTokens","cachedAudioInputTokens","audioOutputTokens"];function A(J){if(!J.trim())return{};try{return JSON.parse(J)}catch{}let Q=[],V=!1,Y=!1;for(let $ of J){if(V){if(Y)Y=!1;else if($==="\\")Y=!0;else if($==='"')V=!1;continue}if($==='"')V=!0;else if($==="{")Q.push("}");else if($==="[")Q.push("]");else if($==="}"||$==="]")Q.pop()}let Z=J;if(V)Z+='"';Z=Z.replace(/[,:]\s*$/,"");let K=Q.reverse().join("");try{return JSON.parse(Z+K)}catch{try{return JSON.parse(Z.replace(/,?\s*"[^"]*"\s*$/,"")+K)}catch{return{}}}}function VJ(J){return{name:"output",schema:J.toJSONSchema(),strict:P(J)}}function YJ(J,Q){let V=J.safeParse(A(Q));if(V.ok===!0)return{ok:!0,value:V.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${V.errors.join(", ")}`,retryable:!0}}}function ZJ(J){if(J.length>0)J[0];return J}function $J(J,Q,V){let Y=J.content[J.content.length-1];if(Y&&Y.type===Q){Y.text=(Y.text??"")+V;return}J.content.push(Q==="text"?{type:"text",text:V}:{type:"reasoning",text:V})}function KJ(J,Q,V,Y){let Z=J.content[J.content.length-1];if(Z&&Z.type==="reasoning"&&Z.id===Q&&!Z.providerMetadata){if(Z.text=(Z.text??"")+V,Y)Z.providerMetadata=Y;return}J.content.push({type:"reasoning",...Q?{id:Q}:{},text:V,...Y?{providerMetadata:Y}:{}})}class R extends Error{status;body;requestId;retryAfter;constructor(J,Q,V,Y){super(`Provider request failed with status ${J}: ${k(Q)}`);if(this.name="ProviderHttpError",this.status=J,this.body=Q,this.requestId=V,Y!==void 0)this.retryAfter=Y}}class D extends Error{timeoutMs;constructor(J){super(`Provider request timed out after ${J}ms`);this.name="ProviderTimeoutError",this.timeoutMs=J}}class x extends D{constructor(J){super(J);this.name="ProviderStreamIdleError",this.message=`Provider stream sent nothing for ${J}ms (streamIdleTimeoutMs)`}}class f extends D{constructor(J){super(J);this.name="ProviderStreamDurationError",this.message=`Provider stream was still going after ${J}ms (streamMaxDurationMs)`}}class N extends Error{limit;detail;constructor(J,Q,V="",Y=J+1){super(`Provider streamed more than ${J} characters of arguments for "${Q}" without finishing the call (maxToolArgumentChars)`);this.name="ProviderToolArgumentsTooLongError",this.limit=J,this.detail={tool:Q,toolCallId:V,limit:J,chars:Y}}}function k(J){let Q=G(J);if(Q?.message)return Q.message;if(typeof J==="string")return J.slice(0,500);return"no error body"}function G(J){if(!J||typeof J!=="object")return null;let Q=J,Y=Q.error&&typeof Q.error==="object"?Q.error:J;if(typeof Y.message!=="string"&&typeof Y.code!=="string"&&typeof Y.type!=="string")return null;let Z=Y.innererror?.code??Y.code;return{message:Y.message,type:Y.type,code:Z,param:Y.param}}function WJ(J){if(!J||typeof J!=="object")return{};let Q=J,{status:V,requestId:Y}=Q,Z=v(Q.body),K=W(Q.providerType)??Z.providerType,$=W(Q.providerCode)??Z.providerCode,L=W(Q.providerParam)??Z.providerParam;return{...typeof V==="number"&&V>=100&&V<=599?{status:V}:{},...typeof Y==="string"&&Y?{requestId:Y}:{},...K?{providerType:K}:{},...$?{providerCode:$}:{},...L?{providerParam:L}:{}}}function v(J){let Q=G(J),V=W(Q?.type),Y=W(Q?.code),Z=W(Q?.param);return{...V?{providerType:V}:{},...Y?{providerCode:Y}:{},...Z?{providerParam:Z}:{}}}function W(J){return typeof J==="string"&&J?J:void 0}function XJ(J){if(J instanceof D||J instanceof N)return{code:"provider_error",message:J.message,retryable:!0};if(p(J))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(J instanceof R)return w(J.status,G(J.body),J.message,J.retryAfter);if(J instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${J.message}`,retryable:!0};if(J instanceof Error)return{code:"provider_error",message:J.message,retryable:!1};return{code:"unknown",message:String(J),retryable:!1}}function w(J,Q,V,Y){let Z=Q?.message??V,K=(Q?.code??"").toLowerCase(),$=(Q?.type??"").toLowerCase(),L=`${K} ${$} ${Z}`.toLowerCase().replace(/https?:\/\/\S+/g,"");if(J===429){if(!b.has(K)&&(K==="insufficient_quota"||L.includes("quota")))return{code:"rate_limited",message:Z,retryable:!1};let H=Y??u(Z);return{code:"rate_limited",message:Z,retryable:!0,...H!==void 0?{retryAfter:H}:{}}}if(J>=500||J===408||J===409)return{code:"provider_error",message:Z,retryable:!0};if(g(L))return{code:"context_length_exceeded",message:Z,retryable:!1};if(y(L))return{code:"content_filtered",message:Z,retryable:!1};if(Q?.param?.startsWith("tools")||L.includes("invalid schema for function"))return{code:"invalid_tool_input",message:Z,retryable:!1};return{code:"provider_error",message:Z,retryable:!1}}var b=new Set(["ratelimitreached","rate_limit_exceeded","too_many_requests"]);function u(J){let Q=/retry after (\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s)\b/i.exec(J);if(!Q)return;let V=Number(Q[1]);return/^m(s|illi)/i.test(Q[2])?V:V*1000}function g(J){return J.includes("context_length_exceeded")||J.includes("maximum context length")||J.includes("context window")||J.includes("reduce the length")||J.includes("prompt is too long")||J.includes("request_too_large")}function y(J){return J.includes("content_filter")||J.includes("content_policy_violation")||J.includes("responsibleaipolicyviolation")||J.includes("content management policy")||J.includes("moderation_blocked")||J.includes("rejected by the safety system")||J.includes("safety_violations")}function p(J){if(!J||typeof J!=="object")return!1;let Q=J;return Q.name==="AbortError"||Q.code==="ABORT_ERR"}
3
- export{z as vd,t as wd,e as xd,JJ as yd,QJ as zd,A as Ad,VJ as Bd,YJ as Cd,ZJ as Dd,$J as Ed,KJ as Fd,X as Gd,U as Hd,l as Id,h as Jd,c as Kd,O as Ld,q as Md,T as Nd,S as Od,F as Pd,i as Qd,s as Rd,E as Sd,C as Td,o as Ud,R as Vd,D as Wd,x as Xd,f as Yd,N as Zd,WJ as _d,v as $d,XJ as ae};
4
-
5
- //# debugId=7BBBF48880D8D96E64756E2164756E21
@@ -1,7 +0,0 @@
1
- // @bun
2
- function I(B){if(!B.definition)throw Error(`gemi/ai: the recursive schema "${B.name}" was used before its definition returned; \`self\` can be nested into the schema, but not parsed or emitted inside the callback`);return B.definition}var k=new WeakMap;function MB(B){return typeof B==="object"&&B!==null&&k.has(B)}function x(B){let F=k.get(B);if(!F)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return F}function o(B){let F={defs:{},cells:new Map},G=B;if(B.node.kind==="ref"){let Q=I(B.node.cell);G={...Q,...B.description?{description:B.description}:{},optional:B.optional,nullable:B.nullable||Q.nullable}}let H=K(G,F);return Object.keys(F.defs).length>0?{...H,$defs:F.defs}:H}function K(B,F){let G=(B.optional||B.nullable)&&B.node.kind!=="json",H=n(l(B.node,F),G),Q=[B.description,t(B.node)].filter(Boolean).join(" ");if(Q&&H.$ref!==void 0)H={anyOf:[H]};return Q?{description:Q,...H}:H}function t(B){let F=[];if(B.kind==="string"||B.kind==="enum"){let G=B.checks;if(G?.format)F.push(`Format: ${G.format.name}.`);if(G?.minLength!==void 0)F.push(`At least ${G.minLength} characters.`);if(G?.maxLength!==void 0)F.push(`At most ${G.maxLength} characters.`)}else if(B.kind==="number"){let G=B.checks;if(G?.minimum!==void 0)F.push(`Minimum ${G.minimum}.`);if(G?.exclusiveMinimum!==void 0)F.push(`Greater than ${G.exclusiveMinimum}.`);if(G?.maximum!==void 0)F.push(`Maximum ${G.maximum}.`);if(G?.exclusiveMaximum!==void 0)F.push(`Less than ${G.exclusiveMaximum}.`)}else if(B.kind==="array"){let G=B.checks;if(G?.minItems!==void 0)F.push(`At least ${G.minItems} items.`);if(G?.maxItems!==void 0)F.push(`At most ${G.maxItems} items.`)}return F.join(" ")}function l(B,F){switch(B.kind){case"string":return{type:"string"};case"number":return{type:B.checks?.integer?"integer":"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof B.value,const:B.value};case"enum":return{type:"string",enum:B.values};case"array":return{type:"array",items:K(B.item,F)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(B.shape).map(([G,H])=>[G,K(H,F)])),required:Object.keys(B.shape),additionalProperties:!1};case"union":return{anyOf:B.members.map((G)=>K(G,F))};case"json":return{};case"ref":{let{cell:G}=B,H=F.cells.get(G.name);if(H&&H!==G)throw Error(`gemi/ai: two different recursive schemas are named "${G.name}" in one schema; give each s.recursive(...) its own name`);if(!H)F.cells.set(G.name,G),F.defs[G.name]={},F.defs[G.name]=K(I(G),F);return{$ref:`#/$defs/${G.name}`}}}}function n(B,F){if(!F)return B;if(B.anyOf)return{...B,anyOf:[...B.anyOf,{type:"null"}]};if(B.enum||B.const!==void 0)return{anyOf:[B,{type:"null"}]};if(typeof B.type==="string")return{...B,type:[B.type,"null"]};return{anyOf:[B,{type:"null"}]}}function i(B){if(B===null)return"null";if(Array.isArray(B))return"array";return typeof B}function s(B,F){if(typeof F==="number"&&!Number.isFinite(F))return String(F);if(B.kind==="literal"||B.kind==="enum"){if(typeof F==="string"||typeof F==="number"||typeof F==="boolean")return JSON.stringify(F)}return i(F)}function d(B){let F=B.node,G=(()=>{switch(F.kind){case"number":return F.checks?.integer?"integer":"number";case"string":case"boolean":return F.kind;case"literal":return JSON.stringify(F.value);case"enum":return`one of ${F.values.map((H)=>JSON.stringify(H)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants";case"json":return"a JSON value";case"ref":return d({...I(F.cell),optional:!1,nullable:!1})}})();return B.optional||B.nullable?`${G} or null`:G}function a(B){let F="";for(let G of B)F+=typeof G==="number"?`[${G}]`:F?`.${G}`:G;return F}function e(B){let F=a(B);return F?`${F}: `:""}function p(B){return`${e(B.path)}${B.message}`}function O(B,F){if(F===null||F===void 0)return B.optional||B.nullable?1:0;let G=B.node;switch(G.kind){case"string":return typeof F==="string"?1:0;case"number":return typeof F==="number"?1:0;case"boolean":return typeof F==="boolean"?1:0;case"literal":return F===G.value?10:0;case"enum":return typeof F==="string"&&G.values.includes(F)?10:0;case"array":return Array.isArray(F)?1:0;case"object":{if(typeof F!=="object"||Array.isArray(F))return 0;let H=F,Q=1;for(let[X,$]of Object.entries(G.shape))Q+=O($,H[X]);return Q}case"union":return G.members.reduce((H,Q)=>Math.max(H,O(Q,F)),0);case"json":return 1;case"ref":return m(G.cell,F,()=>1,()=>O(I(G.cell),F))}}function m(B,F,G,H){if(typeof F!=="object"||F===null)return H();if(B.active.has(F))return G();B.active.add(F);try{return H()}finally{B.active.delete(F)}}function R(B,F,G,H){if(B.optional&&(F===null||F===void 0))return{drop:!0,value:void 0};if(B.nullable&&F===null)return{drop:!1,value:null};return{drop:!1,value:BB(B,F,G,H)}}function BB(B,F,G,H){let Q=B.node,X=()=>{let $=F===void 0?"required":Q.kind==="literal"?"const":Q.kind==="enum"&&typeof F==="string"?"enum":"type",M=$==="const"?{allowedValue:Q.value}:$==="enum"?{allowedValues:Q.values}:{};H.push({path:G,code:$,message:`expected ${d(B)}, got ${s(Q,F)}`,params:M});return};switch(Q.kind){case"string":if(typeof F!=="string")return X();return r(Q.checks,F,G,H),F;case"number":if(typeof F!=="number"||!Number.isFinite(F))return X();if(Q.checks?.integer&&!Number.isInteger(F))return X();return GB(Q.checks,F,G,H),F;case"boolean":return typeof F==="boolean"?F:X();case"literal":return F===Q.value?F:X();case"enum":if(typeof F!=="string"||!Q.values.includes(F))return X();return r(Q.checks,F,G,H),F;case"array":{if(!Array.isArray(F))return X();let $=F.map((V,Y)=>{let L=R(Q.item,V,[...G,Y],H);return L.drop?void 0:L.value}),{minItems:M,maxItems:A}=Q.checks??{};if(M!==void 0&&F.length<M)H.push({path:G,code:"minItems",message:`expected at least ${M} items, got ${F.length}`,params:{limit:M}});if(A!==void 0&&F.length>A)H.push({path:G,code:"maxItems",message:`expected at most ${A} items, got ${F.length}`,params:{limit:A}});return $}case"object":{if(typeof F!=="object"||F===null||Array.isArray(F))return X();let $=F,M={};for(let[A,V]of Object.entries(Q.shape)){let Y=R(V,$[A],[...G,A],H);if(!Y.drop)M[A]=Y.value}if(Q.unknownKeys)for(let A of Object.keys($)){if(Object.hasOwn(Q.shape,A)||$[A]===void 0)continue;if(Q.unknownKeys==="error"){H.push({path:[...G,A],code:"additionalProperties",message:"unknown key",params:{additionalProperty:A}});continue}N($[A],[...G,A],H,new Set),Object.defineProperty(M,A,{value:$[A],enumerable:!0,writable:!0,configurable:!0})}return M}case"union":{let $;for(let M of Q.members){let A=[],V=R(M,F,G,A);if(A.length===0)return V.drop?void 0:V.value;let Y=O(M,F);if(!$||Y>$.score)$={issues:A,score:Y}}H.push({path:G,code:"anyOf",message:`no matching variant; closest: ${$.issues.map(p).join("; ")}`,params:{closest:$.issues}});return}case"json":if(F===void 0)return X();return N(F,G,H,new Set),F;case"ref":return m(Q.cell,F,()=>{H.push({path:G,code:"type",message:"expected a finite tree, got a circular reference",params:{}});return},()=>R(I(Q.cell),F,G,H).value)}}function FB(B){let F=0;for(let G of B)F++;return F}function r(B,F,G,H){if(!B)return;let{minLength:Q,maxLength:X,format:$}=B;if(Q!==void 0||X!==void 0){let M=FB(F);if(Q!==void 0&&M<Q)H.push({path:G,code:"minLength",message:`expected at least ${Q} characters, got ${M}`,params:{limit:Q}});if(X!==void 0&&M>X)H.push({path:G,code:"maxLength",message:`expected at most ${X} characters, got ${M}`,params:{limit:X}})}if($){let M=!1;try{M=$.test(F)===!0}catch{}if(!M)H.push({path:G,code:"format",message:`expected a string in format "${$.name}"`,params:{format:$.name}})}}function GB(B,F,G,H){if(!B)return;let Q=(X,$,M,A)=>{if($===void 0||M($))return;H.push({path:G,code:X,message:`expected ${A} ${$}, got ${F}`,params:{limit:$}})};Q("minimum",B.minimum,(X)=>F>=X,"at least"),Q("exclusiveMinimum",B.exclusiveMinimum,(X)=>F>X,"more than"),Q("maximum",B.maximum,(X)=>F<=X,"at most"),Q("exclusiveMaximum",B.exclusiveMaximum,(X)=>F<X,"less than")}function N(B,F,G,H,Q=!0){let X=(M)=>{G.push({path:F,code:"type",message:`expected a JSON value, got ${M}`,params:{}})};switch(typeof B){case"undefined":case"string":case"boolean":return;case"number":if(!Number.isFinite(B))X(String(B));return;case"bigint":return X("a bigint");case"function":return X("a function");case"symbol":return X("a symbol")}if(B===null)return;let $=B;if(H.has($))return X("a circular reference");H.add($);try{let M=Q?$.toJSON:void 0;if(typeof M==="function"){let A;try{A=M.call($)}catch{return X("a toJSON that threw")}if(A===void 0)return X("a toJSON that returns undefined");return N(A,F,G,H,!1)}if(Array.isArray(B))B.forEach((A,V)=>N(A,[...F,V],G,H));else for(let[A,V]of Object.entries($))N(V,[...F,A],G,H)}finally{H.delete($)}}function D(B){return g(B)}function g(B){let F={toJSONSchema:()=>o(B),parse(G){let H=[],Q=R(B,G,[],H);if(H.length>0)throw Error(H.map(p).join("; "));return Q.drop?void 0:Q.value},safeParse(G){let H=[],Q=R(B,G,[],H);if(H.length>0)return{ok:!1,errors:H.map(p)};return{ok:!0,value:Q.drop?void 0:Q.value}},validate(G){let H=[],Q=R(B,G,[],H);if(H.length>0)return{ok:!1,issues:H};return{ok:!0,value:Q.drop?void 0:Q.value}},describe:(G)=>g({...B,description:G}),optional:()=>g({...B,optional:!0}),nullable:()=>g({...B,nullable:!0,optional:!1})};return k.set(F,B),F}function T(B){return{node:B,optional:!1,nullable:!1}}var h=["strip","error","passthrough"];class u extends Error{problems;constructor(B){super(`gemi/ai: s.fromJSONSchema cannot model this schema:
3
- ${B.map((F)=>`- ${F}`).join(`
4
- `)}`);this.name="JSONSchemaError",this.problems=B}}var HB=new Set(["title","$schema","$id","$comment","examples","default","deprecated","readOnly","writeOnly"]),E={string:["minLength","maxLength","format"],number:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],integer:["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],boolean:[],object:["properties","required","additionalProperties"],array:["items","minItems","maxItems"]};function S(B){return typeof B==="object"&&B!==null&&!Array.isArray(B)}function y(B,F,G,H){let Q=(Z,_=G)=>{H.push(_?`${_}: ${Z}`:Z);return},X=(Z)=>G?`${G}.${Z}`:Z;if(!S(B))return Q("expected a schema object");let $=new Set(F.ignoreKeywords??[]),M=(Z)=>HB.has(Z)||Z.startsWith("x-")||$.has(Z),A=!1,V=B.type;if(Array.isArray(V)){let Z=V.filter((_)=>_!=="null");if(Z.length!==1)return Q(`type ${JSON.stringify(V)} is not supported; only one type, optionally with "null". Use anyOf for alternatives`,X("type"));A=Z.length<V.length,V=Z[0]}if(V!==void 0&&(typeof V!=="string"||!(V in E)))return Q(`type ${JSON.stringify(V)} is not supported; expected one of ${Object.keys(E).join(", ")}`,X("type"));let Y=new Set(["type","description","enum","const","anyOf",...V?E[V]:[]]),L=!1;for(let Z of Object.keys(B)){if(Y.has(Z)||M(Z))continue;L=!0;let _=Object.entries(E).find(([,z])=>z.includes(Z));Q(_&&_[0]!==V?`"${Z}" applies to type ${_[0]}, and this schema is ${V?`type ${V}`:"untyped"}`:`"${Z}" is not supported by s.fromJSONSchema`,X(Z))}if(L)return;if(B.description!==void 0&&typeof B.description!=="string")return Q("expected a string",X("description"));let w=B.description,U=(Z)=>({node:Z,optional:!1,nullable:A,...w?{description:w}:{}});if(B.anyOf!==void 0){if(V!==void 0||B.enum!==void 0||B.const!==void 0)return Q("anyOf cannot be combined with type, enum or const here",X("anyOf"));if(!Array.isArray(B.anyOf)||B.anyOf.length===0)return Q("expected a non-empty array",X("anyOf"));let Z=[],_=!1;if(B.anyOf.forEach((z,q)=>{if(S(z)&&z.type==="null"&&Object.keys(z).length===1){A=!0;return}let P=y(z,F,X(`anyOf[${q}]`),H);if(P)Z.push(P);else _=!0}),_)return;if(Z.length===0)return Q("anyOf has only null in it",X("anyOf"));if(Z.length===1){let z=Z[0];return{...z,nullable:z.nullable||A,...w?{description:w}:{}}}return U({kind:"union",members:Z})}if(B.const!==void 0){let Z=B.const;if(typeof Z!=="string"&&typeof Z!=="number"&&typeof Z!=="boolean")return Q("only a string, number or boolean const is supported",X("const"));if(V!==void 0&&typeof Z!==(V==="integer"?"number":V))return Q(`const ${JSON.stringify(Z)} is not of type ${V}`,X("const"));return U({kind:"literal",value:Z})}let W;if(V==="string"){if(W=QB(B,F,X,H),W===null)return}if(B.enum!==void 0){if(!Array.isArray(B.enum)||B.enum.length===0)return Q("expected a non-empty array",X("enum"));let Z=B.enum.filter((q)=>q!==null);if(Z.length<B.enum.length)A=!0;let _=Z.find((q)=>!(typeof q==="string"||typeof q==="number"||typeof q==="boolean")||V!==void 0&&typeof q!==(V==="integer"?"number":V));if(_!==void 0||Z.length===0)return Q(V?`every value must be of type ${V}${Z.length===0?", and there must be one":`; ${JSON.stringify(_)} is not`}`:"only strings, numbers and booleans are supported",X("enum"));if(Z.every((q)=>typeof q==="string"))return U({kind:"enum",values:[...new Set(Z)],...W?{checks:W}:{}});let z=[...new Set(Z)];if(z.length===1)return U({kind:"literal",value:z[0]});return U({kind:"union",members:z.map((q)=>T({kind:"literal",value:q}))})}switch(V){case void 0:return Q("a schema needs a type, an enum, a const or an anyOf");case"string":return U({kind:"string",...W?{checks:W}:{}});case"number":case"integer":{let Z=V==="integer"?{integer:!0}:{},_=!1;for(let z of E.number){let q=B[z];if(q===void 0)continue;if(typeof q!=="number"||!Number.isFinite(q)){Q("expected a number",X(z)),_=!0;continue}Z[z]=q}if(_)return;return U({kind:"number",...Object.keys(Z).length>0?{checks:Z}:{}})}case"boolean":return U({kind:"boolean"});case"array":{if(!S(B.items))return Q('an array needs "items" to be one schema (tuples are not supported)',X("items"));let Z={},_=!1;for(let q of["minItems","maxItems"]){let P=B[q];if(P===void 0)continue;if(typeof P!=="number"||!Number.isInteger(P)||P<0){Q("expected a non-negative integer",X(q)),_=!0;continue}Z[q]=P}let z=y(B.items,F,X("items"),H);if(!z||_)return;return U({kind:"array",item:z,...Object.keys(Z).length>0?{checks:Z}:{}})}case"object":{let Z=B.properties??{};if(!S(Z))return Q("expected an object",X("properties"));if(B.additionalProperties!==void 0&&B.additionalProperties!==!1)return Q("only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())",X("additionalProperties"));let _=B.required??[];if(!Array.isArray(_)||!_.every((C)=>typeof C==="string"))return Q("expected an array of property names",X("required"));let z=_.filter((C)=>!Object.hasOwn(Z,C));if(z.length>0)return Q(`lists properties the schema doesn't have: ${z.join(", ")}`,X("required"));let q={},P=!1;for(let[C,c]of Object.entries(Z)){let f=y(c,F,X(`properties.${C}`),H);if(!f){P=!0;continue}q[C]=_.includes(C)?f:{...f,optional:!0}}if(P)return;let b=F.unknownKeys;return U({kind:"object",shape:q,...b==="error"||b==="passthrough"?{unknownKeys:b}:{}})}}return}function QB(B,F,G,H){let Q={},X=!1;for(let $ of["minLength","maxLength"]){let M=B[$];if(M===void 0)continue;if(typeof M!=="number"||!Number.isInteger(M)||M<0){H.push(`${G($)}: expected a non-negative integer`),X=!0;continue}Q[$]=M}if(B.format!==void 0){let $=B.format,M=typeof $==="string"?F.formats?.[$]:void 0;if(typeof $!=="string")H.push(`${G("format")}: expected a string`),X=!0;else if(!M||!Object.hasOwn(F.formats,$))H.push(`${G("format")}: unknown format ${JSON.stringify($)}; pass a check for it in the formats option`),X=!0;else Q.format={name:$,test:XB(M)}}if(X)return null;return Object.keys(Q).length>0?Q:void 0}function XB(B){if(B===!0)return()=>!0;if(B instanceof RegExp)return(F)=>{return B.lastIndex=0,B.test(F)};return B}var VB={string:()=>D(T({kind:"string"})),number:()=>D(T({kind:"number"})),boolean:()=>D(T({kind:"boolean"})),literal:(B)=>D(T({kind:"literal",value:B})),enum:(B)=>D(T({kind:"enum",values:B})),object:(B)=>D(T({kind:"object",shape:Object.fromEntries(Object.entries(B).map(([F,G])=>[F,x(G)]))})),array:(B)=>D(T({kind:"array",item:x(B)})),union:(B)=>D(T({kind:"union",members:B.map(x)})),json:()=>D(T({kind:"json"})),recursive:$B,fromJSONSchema:(B,F={})=>{let G=[];if(F.unknownKeys!==void 0&&!h.includes(F.unknownKeys))throw Error(`gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${h.map((Q)=>JSON.stringify(Q)).join(", ")}, got ${JSON.stringify(F.unknownKeys)}`);let H=y(B,F,"",G);if(!H||G.length>0)throw new u(G.length>0?G:["unreadable schema"]);return D(H)}};function AB(B){let F=k.get(B);if(F)return J(F.node);return j(B.toJSONSchema())}function j(B){if(!(B.$ref!==void 0||B.type!==void 0||B.enum!==void 0||B.const!==void 0||B.anyOf!==void 0||B.properties!==void 0||B.items!==void 0))return!1;for(let G of Object.values(B.properties??{}))if(!j(G))return!1;if(B.items&&!j(B.items))return!1;for(let G of B.anyOf??[])if(!j(G))return!1;for(let G of Object.values(B.$defs??{}))if(!j(G))return!1;return!0}function J(B,F=new Set){switch(B.kind){case"string":case"number":case"boolean":case"literal":case"enum":return!0;case"object":return Object.values(B.shape).every((G)=>J(G.node,F));case"array":return J(B.item.node,F);case"union":return B.members.every((G)=>J(G.node,F));case"json":return!1;case"ref":if(F.has(B.cell))return!0;return F.add(B.cell),J(I(B.cell).node,F)}}function v(B,F,G=new Set){let H=B.node;if(H.kind==="union")return H.members.some((Q)=>v(Q,F,G));if(H.kind!=="ref")return!1;if(H.cell===F)return!0;if(G.has(H.cell)||!H.cell.definition)return!1;return G.add(H.cell),v(H.cell.definition,F,G)}var ZB=/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;function $B(B,F){if(typeof B!=="string"||!ZB.test(B))throw Error(`gemi/ai: s.recursive needs a name of letters, digits, "_" and "-" (starting with a letter or "_", at most 64), got ${JSON.stringify(B)}`);let G={name:B,active:new Set},H=()=>T({kind:"ref",cell:G}),Q=x(F(D(H())));if(Q.optional)throw Error(`gemi/ai: the recursive schema "${B}" is optional() as a whole; mark the places that use it optional instead`);if(v(Q,G))throw Error(`gemi/ai: the recursive schema "${B}" refers to itself outside any object or array, so it describes no finite value; nest \`self\` in an s.object(...) field or an s.array(...)`);return G.definition=Q,D(H())}
5
- export{MB as Nj,u as Oj,VB as Pj,AB as Qj};
6
-
7
- //# debugId=112B69F843666D5964756E2164756E21
@@ -1,8 +0,0 @@
1
- // @bun
2
- import{Cj as L,Dj as Y1,Ej as G1}from"./chunk-h1wmpa03.js";import{Jj as I1,Mj as E}from"./chunk-t586p2g2.js";import{Nj as A1}from"./chunk-qs2xvc8g.js";import{hm as X0}from"./chunk-yj7pbbnm.js";import{lm as X1}from"./chunk-37209psn.js";import{Im as r}from"./chunk-5mrtgr7q.js";import{Qm as w4}from"./chunk-3dkv4989.js";class h1{static kind="controller";constructor(){}}class k0 extends h1{}function D1(K){let Q=new Map;if(!K)return Q;for(let Z of K.split(";")){let J=Z.indexOf("=");if(J===-1)continue;let $=Z.slice(0,J).trim();if(!$)continue;Q.set($,Z.slice(J+1).trim())}return Q}function m4(K){return D1(K.headers.get("cookie"))}function m(K){if(!/^\d+$/.test(K))return null;let Q=Number(K);return Number.isSafeInteger(Q)?Q:null}function m1(K){if(!K)return null;let Q=K.trim();if(!/^bytes=/i.test(Q))return null;let J=Q.slice(6).split(",").map((V)=>V.trim()).filter((V)=>V!=="");if(J.length!==1)return null;let $=J[0],X=$.indexOf("-");if(X===-1)return null;let Y=$.slice(0,X),W=$.slice(X+1);if(Y===""){let V=m(W);if(V===null)return null;return{kind:"suffix",suffixLength:V}}let G=m(Y);if(G===null)return null;if(W==="")return{kind:"offset",start:G,end:null};let H=m(W);if(H===null||H<G)return null;return{kind:"offset",start:G,end:H}}function c1(K,Q){if(!Number.isFinite(Q)||Q<=0)return null;let Z,J;if(K.kind==="suffix"){if(K.suffixLength<=0)return null;Z=Math.max(0,Q-K.suffixLength),J=Q-1}else{if(K.start>=Q)return null;if(Z=K.start,J=K.end===null?Q-1:Math.min(K.end,Q-1),J<Z)return null}return{start:Z,end:J,length:J-Z+1}}function p4(K){if(K.kind==="suffix")return`bytes=-${K.suffixLength}`;return K.end===null?`bytes=${K.start}-`:`bytes=${K.start}-${K.end}`}function u4(K){if(!K)return null;let Q=/^bytes\s+(\d+)-(\d+)\/(\d+)$/i.exec(K.trim());if(!Q)return null;let Z=m(Q[1]),J=m(Q[2]),$=m(Q[3]);if(Z===null||J===null||$===null||J<Z)return null;return{start:Z,end:J,total:$}}function d4(K,Q,Z){return`bytes ${K}-${Q}/${Z}`}function p1(K){return`bytes */${K}`}import{randomBytes as E0}from"crypto";var M1=new WeakMap;function R1(K){let Q=M1.get(K);if(!Q)Q=E0(16).toString("base64"),M1.set(K,Q);return Q}function o4(K){return M1.get(K)}function s4(){let K=E.getStore()?.req?.rawRequest;if(!K)throw Error("cspNonce() is only available while a request is being handled.");return R1(K)}class o extends L{errors={};constructor(K){super("Validation error");this.name="ValidationError",this.errors=K,this.payload={api:{status:400,data:{error:{kind:"validation_error",messages:K,status:400}},headers:{"Content-Type":"application/json"}},view:{status:400}}}}function d1(K){let[Q,Z]=K.match(/\d+|\D+/g)??[];if(!Q||!Z)return 0;let J=Number.parseInt(Q);switch(Z){case"B":return J;case"KB":return J*1024;case"MB":return J*1024*1024;case"GB":return J*1024*1024*1024;case"TB":return J*1024*1024*1024*1024;default:return 0}}function x0(K){switch(K){case"image":return"image";case"png":return"image/png";case"jpg":return"image/jpeg";case"jpeg":return"image/jpeg";case"ttf":return"font/ttf";case"excel":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"csv":return"text/csv";case"word":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"pdf":return"application/pdf";case"json":return"application/json";default:return K}}function u1(K){if(typeof K==="string"||Array.isArray(K))return K.length;return}function B1(K){return typeof K==="number"&&!Number.isNaN(K)}var q0=["required","string","boolean","number","email","password","min","max","gte","lte","file","fileType","fileSize","array","object","in"];class x extends Error{name="InvalidValidationRuleError"}function $1(K,Q){let Z=Q===void 0||Q.trim()===""?Number.NaN:Number(Q);if(Number.isNaN(Z))throw new x(`Validation rule "${K}:${Q??""}" needs a number, e.g. "${K}:3"`);return Z}function l1(K){let Q=!1,Z=0;for(let J of Object.values(K)){if(!J||typeof J!=="object")continue;for(let $ of Object.keys(J)){let X=$.indexOf(":"),Y=X===-1?$:$.slice(0,X);if(Y!=="file"&&Y!=="fileType"&&Y!=="fileSize")continue;if(Q=!0,Y==="fileSize")Z+=d1($.slice(X+1))}}return Q?Z:null}function i1(K){let Q=K.indexOf(":"),Z=Q===-1?K:K.slice(0,Q),J=Q===-1?void 0:K.slice(Q+1);switch(Z){case"required":return($)=>{if($ instanceof Blob)return $.size>0;if($===null||$===void 0)return!1;if(typeof $==="string"||Array.isArray($))return $.length>0;return!0};case"string":return($)=>typeof $==="string";case"boolean":return($)=>typeof $==="boolean";case"number":return($)=>B1($);case"password":return($)=>{return typeof $==="string"&&/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/.test($)};case"min":{let $=$1(Z,J);return(X)=>{let Y=u1(X);return Y!==void 0&&Y>=$}}case"max":{let $=$1(Z,J);return(X)=>{let Y=u1(X);return Y!==void 0&&Y<=$}}case"gte":{let $=$1(Z,J);return(X)=>B1(X)&&X>=$}case"lte":{let $=$1(Z,J);return(X)=>B1(X)&&X<=$}case"email":return($)=>{return typeof $==="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($)};case"file":return($)=>{return $ instanceof Blob};case"fileType":{if(!J)throw new x('Validation rule "fileType" needs a type, e.g. "fileType:png" or "fileType:image"');let $=x0(J);return(X)=>X instanceof Blob&&X.type.startsWith($)}case"fileSize":{let $=d1(J??"");if($===0&&!/^0+(B|KB|MB|GB|TB)$/.test(J??""))throw new x(`Validation rule "fileSize:${J??""}" needs a whole size in B, KB, MB, GB or TB, e.g. "fileSize:5MB"`);return(X)=>X instanceof Blob&&X.size<=$}case"array":return($)=>Array.isArray($);case"object":return($)=>typeof $==="object"&&$!==null&&!Array.isArray($)&&!($ instanceof Blob);case"in":{let $=(J??"").split(",").filter((X)=>X!=="");if($.length===0)throw new x('Validation rule "in" needs a comma-separated list, e.g. "in:draft,published"');return(X)=>typeof X==="string"&&$.includes(X)}default:throw new x(`Unknown validation rule "${K}". Known rules: ${q0.join(", ")}`)}}class L1 extends L{limit;constructor(K){super("The request body is too large.",{status:413});this.limit=K}}var n1={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function QK(K){if(typeof K==="number"){if(Number.isFinite(K)&&K>=0)return Math.floor(K);if(K===1/0)return 1/0}else{let Q=K.trim().toLowerCase();if(Q==="none"||Q==="off")return 1/0;let Z=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Q);if(Z&&(Z[2]===""||(Z[2]in n1)))return Math.floor(Number(Z[1])*(n1[Z[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify(K)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var p=new WeakMap;function ZK(K){return p.has(K)}function JK(K){return p.get(K)?.limit??null}function $K(K){let Q=p.get(K);return Q?Q.read>Q.limit:!1}function b0(K){let Q=K.headers.get("Content-Length");if(Q===null||!/^\s*\d+\s*$/.test(Q))return null;return Number(Q)}function C1(K,Q){let Z=b0(K);if(Z!==null&&Z>Q)throw new L1(Q)}function XK(K,Q,Z={}){let J=Z.uploadLimit??null,$=p.get(K);if($)$.limit=Q,$.uploadLimit=J;else{let X={limit:Q,uploadLimit:J,read:0,stream:void 0,used:!1};p.set(K,X),f0(K,X)}if(Z.checkDeclared!==!1)C1(K,Q)}function s1(K,Q){let Z=p.get(K);if(!Z||Z.uploadLimit===null||Z.used||Z.read>0)return;Z.limit=Math.max(Z.limit,Z.uploadLimit,Q+Z.limit),Z.uploadLimit=null}function v0(K){return Reflect.get(Object.getPrototypeOf(K),"body",K)??null}function N1(K,Q){if(Q.stream!==void 0)return Q.stream;let Z=v0(K);if(!Z)return Q.stream=null;let J;return Q.stream=new ReadableStream({async pull($){J??=Z.getReader();let{done:X,value:Y}=await J.read();if(X){$.close();return}if(Q.read+=Y.byteLength,Q.read>Q.limit){let W=new L1(Q.limit);$.error(W),J.cancel(W).catch(()=>{});return}$.enqueue(Y)},cancel($){return J?J.cancel($):Z.cancel($)}},{highWaterMark:0}),Q.stream}async function c(K,Q){if(C1(K,Q.limit),Q.used||Q.stream?.locked)throw TypeError("Body already used");Q.used=!0;let Z=N1(K,Q);if(!Z)return new Uint8Array(0);let J=Z.getReader(),$=[],X=0;for(;;){let{done:G,value:H}=await J.read();if(G)break;$.push(H),X+=H.byteLength}let Y=new Uint8Array(X),W=0;for(let G of $)Y.set(G,W),W+=G.byteLength;return Y}function o1(K){return K.headers.get("Content-Type")??""}function f0(K,Q){let Z=(J,$)=>Object.defineProperty(K,J,{configurable:!0,...$});Z("body",{get:()=>N1(K,Q)}),Z("bodyUsed",{get:()=>Q.used||Boolean(Q.stream?.locked)||Reflect.get(Object.getPrototypeOf(K),"bodyUsed",K)}),Z("bytes",{value:()=>c(K,Q)}),Z("arrayBuffer",{value:async()=>{let J=await c(K,Q);return J.buffer.slice(J.byteOffset,J.byteOffset+J.byteLength)}}),Z("text",{value:async()=>new TextDecoder().decode(await c(K,Q))}),Z("json",{value:async()=>JSON.parse(new TextDecoder().decode(await c(K,Q)))}),Z("blob",{value:async()=>new Blob([await c(K,Q)],{type:o1(K)})}),Z("formData",{value:async()=>new Response(await c(K,Q),{headers:{"Content-Type":o1(K)}}).formData()}),Z("clone",{value:()=>{C1(K,Q.limit);let J=N1(K,Q),$=null;if(J){let[X,Y]=J.tee();Q.stream=X,$=Y}return new Request(K.url,{method:K.method,headers:K.headers,body:$,signal:K.signal,duplex:"half"})}})}function a1(K){if(typeof K!=="string")return null;let[Q]=K.split(";",1),Z=Q.trim().toLowerCase();return Z===""?null:Z}function t1(K){if(K===null)return!1;if(K==="application/json")return!0;let Q=K.indexOf("/");return Q>0&&K.endsWith("+json")&&K.length>Q+1+5}var s=new WeakMap;function WK(K,Q,Z,J){s.set(K,{clientAddress:Q,...Z?{grant:Object.freeze({...Z,scopes:Object.freeze([...Z.scopes])})}:{},...J?{progress:J}:{}})}function r1(K){return s.get(K)?.progress}function e1(K){return s.get(K)?.grant}function K0(K){return s.has(K)}function HK(K){return s.get(K)?.clientAddress}var Q0=new WeakMap;function OK(K,Q){Q0.set(K,Q)}function Z0(K){return Q0.get(K)??null}var _1=new WeakMap;function jK(K,Q){let Z=_1.get(K)??[];if(!Z.includes(Q))_1.set(K,[...Z,Q])}function zK(K){return _1.get(K)??[]}class u{data;constructor(K){this.data=K}get(K){return this.data[K]}has(K){return this.data[K]!==void 0}toJSON(){return this.data}}function J0(K){return typeof K==="object"&&K!==null&&!(K instanceof Blob)}function y0(K,Q){if(!Q.includes(".")||Object.hasOwn(K,Q))return[{path:[Q],value:K[Q]}];let Z=[{path:[],value:K}];for(let J of Q.split(".")){let $=[];for(let{path:X,value:Y}of Z){if(J==="*"){if(Array.isArray(Y))Y.forEach((W,G)=>$.push({path:[...X,G],value:W}));else if(J0(Y))for(let[W,G]of Object.entries(Y))$.push({path:[...X,W],value:G});continue}if(Array.isArray(Y)&&/^\d+$/.test(J)){$.push({path:[...X,Number(J)],value:Y[Number(J)]});continue}$.push({path:[...X,J],value:J0(Y)&&Object.hasOwn(Y,J)?Y[J]:void 0})}Z=$}return Z}function $0(K){return K.join(".")}class g0{kind;rawRequest;headers;cookies;search;schema={};routePath;params;domain;state;constructor(K,Q,Z,J){if(!K){let G=E.getStore().req;this.params=G.params,this.rawRequest=G.rawRequest,this.kind=G.kind,this.routePath=G.routePath,this.domain=G.domain??null,this.state=G.state??new I1}else this.params=Q,this.rawRequest=K,this.routePath=J,this.kind=Z??"api",this.domain=Z0(K),this.state=new I1;this.headers=this.rawRequest.headers;let $=D1(this.rawRequest.headers.get("Cookie")),X=new URL(this.rawRequest.url),Y=new Map;for(let[G,H]of X.searchParams)if(Y.has(G)){let V=Y.get(G);if(Array.isArray(V))V.push(H),Y.set(G,V);else Y.set(G,[V,H])}else Y.set(G,H);let W=Object.fromEntries(Y.entries());this.search=new u(W),this.cookies=$}locale(){let K=E.getStore();if(K.locale)return K.locale;let Q=X1(X0);return Q.isLocaleAware?Q.detectLocale(K.req):K.locale}ctx(){return E.getStore()}isModelOriginated(){return K0(this.rawRequest)}mcpGrant(){return e1(this.rawRequest)??null}cspNonce(){return R1(this.rawRequest)}reportProgress(K){let Q=r1(this.rawRequest);if(!Q)return!1;return Q(K),!0}get signal(){return this.rawRequest.signal}range(){return m1(this.rawRequest.headers.get("Range"))}refine(K){return{}}async parseBody(){let K=a1(this.rawRequest.headers.get("Content-Type"));if(t1(K))return new u(await this.parseJsonBody());if(K==="application/x-www-form-urlencoded"||K==="multipart/form-data"){if(K==="multipart/form-data"&&!A1(this.schema)){let J=l1(this.schema??{});if(J!==null)s1(this.rawRequest,J)}let Q;try{Q=await this.rawRequest.formData()}catch(J){if(J instanceof L)throw J;throw new L("The request body could not be read as a form.")}let Z=new Map;for(let[J,$]of Q.entries())if(Z.has(J)){let X=Z.get(J);if(Array.isArray(X))X.push($);else Z.set(J,[X,$])}else Z.set(J,$);return new u(Object.fromEntries(Z.entries()))}return new u({})}async parseJsonBody(){if(!this.rawRequest.body)return{};let K;try{K=await this.rawRequest.text()}catch(Z){if(Z instanceof L)throw Z;throw new L("The request body could not be read.")}if(K.trim()==="")return{};let Q;try{Q=JSON.parse(K)}catch{throw new L("The request body is not valid JSON.")}if(Q===null||typeof Q!=="object")throw new L("The request body must be a JSON object.");return Q}validateInput(K){if(A1(this.schema))return this.validateWithSchema(K);let Q=K.toJSON()??{},Z={},J=Object.entries(this.schema).map(([$,X])=>({key:$,rules:Object.entries(X).map(([Y,W])=>({rule:Y,message:W,check:typeof W==="function"?null:this.ruleFor($,Y)}))}));for(let{key:$,rules:X}of J)for(let{path:Y,value:W}of y0(Q,$)){let G=this.checkField(W,X);if(G.length>0){let H=Z[$0(Y)]??=[];for(let V of G)if(!H.includes(V))H.push(V)}}if(this.addRefinements(Z,Q),Object.keys(Z).length>0)throw new o(Z);return K}checkField(K,Q){let Z=Q.some(({rule:X})=>X==="required"),J=K===void 0||K===null||K==="",$=[];for(let{rule:X,message:Y,check:W}of Q){let G=Y,H=!1;if(typeof Y==="function")G=Y(K),H=typeof G>"u";else H=W(K);if(H)continue;if(J&&!Z)continue;if(X==="required")return[String(G)];if(!$.includes(String(G)))$.push(String(G))}return $}validateWithSchema(K){let Q=this.schema.validate(K.toJSON()),Z={};if("issues"in Q)for(let $ of Q.issues){let X=$0($.path),Y=Z[X]??=[];if(!Y.includes($.message))Y.push($.message)}let J="value"in Q?new u(Q.value):K;if(this.addRefinements(Z,J.toJSON()),Object.keys(Z).length>0)throw new o(Z);return J}addRefinements(K,Q){for(let[Z,J]of Object.entries(this.refine(Q)??{})){let $=K[Z]??[];K[Z]=$.includes(J)?$:[...$,J]}}ruleFor(K,Q){try{return i1(Q)}catch(Z){if(Z instanceof x)throw new x(`${this.constructor.name}.schema.${K}: ${Z.message}`);throw Z}}async input(){return this.validateInput(await this.parseBody())}async safeInput(){let K=await this.parseBody();try{return{isValid:!0,errors:{},input:this.validateInput(K)}}catch(Q){if(!(Q instanceof o))throw Q;return{isValid:!1,errors:Q.errors,input:K}}}}var Y0="x-gemi-sign-in";class h0 extends L{error;constructor(K="Not authorized"){super(K);this.name="AuthorizationError",this.error=K,this.payload={api:{status:401,data:{error:G1("authorization",this.error,401)}},view:{}}}}class F1 extends L{static apiStatus=403;error;constructor(K="Insufficient permissions"){super(K);this.name="InsufficientPermissionsError",this.error=K,this.payload={api:{status:F1.apiStatus,data:{error:G1("permission",this.error,F1.apiStatus)}},view:{status:403}}}}class w1 extends L{total;constructor(K){super("Range not satisfiable");this.total=K;this.name="RangeNotSatisfiableError",this.payload={api:{status:416,data:{error:Y1("range_not_satisfiable","Range not satisfiable",416)},headers:{"Content-Range":p1(K),"Accept-Ranges":"bytes","Cache-Control":"no-store"}},view:{}}}}class m0 extends L{constructor(K="Not found"){super(K);this.name="NotFoundError",this.payload={api:{status:404,data:{error:Y1("not_found",K,404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class v extends L{fileName;constructor(K){super("File not found");this.fileName=K;this.name="FileNotFoundError",this.payload={api:{status:404,data:{error:Y1("not_found","Not found",404)},headers:{"Cache-Control":"no-store"}},view:{status:404}}}}class c0 extends L{constructor(K={}){super("Authentication error");this.name="AuthenticationError";let Q=K.redirectTo??"/auth/sign-in";this.payload={api:{status:401,data:{error:G1("authentication","Authentication error",401)},headers:{[Y0]:Q}},viewData:{status:200,data:{},headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate"},directive:{kind:"Redirect",path:Q}},view:{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:Q}}}}}class a{static getFacadeAccessor(){throw Error(`Facade [${this.name}] does not implement getFacadeAccessor().`)}static getFacadeRoot(){return X1(this.getFacadeAccessor())}}import{Buffer as p0}from"buffer";function W1(K){if(typeof K!=="string"||/^[\s/.]*$/.test(K))throw Error(`Refusing to delete by prefix ${JSON.stringify(K)}: it would match the whole store`)}class t{async putStream({body:K,...Q},Z={}){Z.signal?.throwIfAborted();let J=[],$=K.getReader();try{for(;;){Z.signal?.throwIfAborted();let{done:X,value:Y}=await $.read();if(X)break;J.push(Y)}}catch(X){throw await $.cancel(X).catch(()=>{}),X}return this.put({...Q,body:p0.concat(J)},Z)}async*objects(K,Q={}){throw Error(`${this.constructor.name} does not implement objects(). Override it to list objects in this backend.`)}async deletePrefix(K,Q={}){W1(K);let Z=[];for await(let J of this.objects(K,Q))Z.push(J.name);for(let J of Z)Q.signal?.throwIfAborted(),await this.delete({name:J,bucket:Q.bucket});return Z.length}async delete(K){throw Error(`${this.constructor.name} does not implement delete(). Override it to remove objects from this backend.`)}async read(K){let Q=typeof K==="string"?{name:K}:K,Z=await this.fetch({name:Q.name,bucket:Q.bucket});if(!Z.ok)throw new v(Q.name);let J=Z.headers.get("Content-Type")??"application/octet-stream",$=Z.headers.get("ETag")??void 0,X=Z.headers.get("Last-Modified"),Y=X?new Date(X):void 0;if(Q.range){let H=await Z.blob();return{body:H,start:0,end:H.size-1,total:H.size,partial:!1,type:J,etag:$,lastModified:Y,name:Q.name}}let W=Number(Z.headers.get("Content-Length")),G=Number.isFinite(W)?W:0;return{body:Z.body,start:0,end:G-1,total:G,partial:!1,type:J,etag:$,lastModified:Y,name:Q.name}}async size(K){let Q=typeof K==="string"?K:K.name,Z=typeof K==="string"?void 0:K.bucket,J=await this.fetch({name:Q,bucket:Z});if(!J.ok)throw new v(Q);let $=Number(J.headers.get("Content-Length"));if(Number.isFinite($))return await J.body?.cancel(),$;return(await J.blob()).size}}function G0(K,Q){if(!Q)return K;let Z=K.getReader(),J=!1,$,X=()=>{if(J=!0,$)Q.removeEventListener("abort",$)};return new ReadableStream({start(Y){if($=()=>{if(J)return;X(),Y.error(Q.reason),Z.cancel(Q.reason).catch(()=>{})},Q.aborted)$();else Q.addEventListener("abort",$,{once:!0})},async pull(Y){let W;try{W=await Z.read()}catch(G){if(J)return;X(),Y.error(G);return}if(J)return;if(W.done){X(),Y.close();return}Y.enqueue(W.value)},cancel(Y){return X(),Z.cancel(Y)}},{highWaterMark:0})}import{mkdir as u0,open as d0,readdir as T1,rename as l0,rmdir as i0,stat as n0,unlink as W0}from"fs/promises";import{dirname as o0,isAbsolute as H0,relative as H1,resolve as V1,sep as y}from"path";class S1 extends t{configured;constructor(K){super();this.configured=K}get folderPath(){return this.configured??`${r()}/storage`}resolveObjectPath(K,Q){if(!K)throw Error("Object name has to be specified");let Z=V1(this.folderPath),J=V1(Z,K),$=H1(Z,J),X=K.includes("\x00");if(X||!$||$===".."||$.startsWith(`..${y}`)||H0($)){if(Q==="read")throw new v(K);if(X)throw Error(`Refusing to ${Q} an object name containing a NUL byte`);throw Error(`Refusing to ${Q} "${K}": it is outside the storage folder`)}return J}async put(K,{signal:Q}={}){Q?.throwIfAborted();let Z,J;if(K instanceof Blob)Z=K,J=`${Bun.randomUUIDv7()}.${K.type.split("/")[1].split(";")[0]}`;else Z=K.body,J=K.name;let $=this.resolveObjectPath(J,"write"),X=Z instanceof Buffer?Z:Z instanceof Blob||Z instanceof File?Buffer.from(await Z.arrayBuffer()):"";return Q?.throwIfAborted(),await Bun.write($,X),J}async putStream({name:K,body:Q},{signal:Z}={}){let J=Q.getReader(),$=null;try{Z?.throwIfAborted();let X=this.resolveObjectPath(K,"write");await u0(o0(X),{recursive:!0}),$=`${X}.${Bun.randomUUIDv7()}.partial`;let Y=await d0($,"wx");try{for(;;){Z?.throwIfAborted();let{done:W,value:G}=await J.read();if(W)break;for(let H=0;H<G.byteLength;){let{bytesWritten:V}=await Y.write(G,H);H+=V}}}finally{await Y.close()}return Z?.throwIfAborted(),await l0($,X),K}catch(X){if(await J.cancel(X).catch(()=>{}),$)await W0($).catch(()=>{});throw X}}async fetch(K,{signal:Q}={}){Q?.throwIfAborted();let Z=typeof K==="string"?K:K.name,J=Bun.file(this.resolveObjectPath(Z,"read")),$=G0(J.stream(),Q),X=new Date(J.lastModified).toUTCString();return new Response($,{headers:{"Content-Type":J.type,"Content-Length":String(J.size),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":X}})}async read(K){let Q=typeof K==="string"?{name:K}:K,{name:Z,range:J=null}=Q,$=Bun.file(this.resolveObjectPath(Z,"read"));if(!await $.exists())throw new v(Z);let X=$.size,Y=J?c1(J,X):null;if(J&&!Y)throw new w1(X);let W=Y?.start??0,G=Y?Y.end:X-1;return{body:Y?$.slice(W,G+1):$,start:W,end:G,total:X,partial:Boolean(Y),type:$.type||"application/octet-stream",lastModified:new Date($.lastModified),name:Z}}async size(K){let Q=typeof K==="string"?K:K.name,Z=Bun.file(this.resolveObjectPath(Q,"read"));if(!await Z.exists())throw new v(Q);return Z.size}async delete(K){let Q=typeof K==="string"?K:K.name,Z=this.resolveObjectPath(Q,"delete");try{await W0(Z)}catch(J){if(J?.code==="ENOENT")return;throw J}}resolvePrefix(K){let Q=V1(this.folderPath),Z=K.lastIndexOf("/"),J=Z===-1?"":K.slice(0,Z),$=Z===-1?K:K.slice(Z+1),X=V1(Q,J),Y=H1(Q,X);if(Y===".."||Y.startsWith(`..${y}`)||H0(Y))throw Error(`Refusing to list "${K}": it is outside the storage folder`);let W=Y.split(y).join("/");return{root:Q,dir:X,match:W?`${W}/${$}`:$}}async*objects(K,{signal:Q}={}){Q?.throwIfAborted();let{root:Z,dir:J,match:$}=this.resolvePrefix(K),X=[],Y=async(W)=>{let G;try{G=await T1(W,{withFileTypes:!0})}catch(H){if(H?.code==="ENOENT"||H?.code==="ENOTDIR")return;throw H}for(let H of G){let V=`${W}${y}${H.name}`,O=H1(Z,V).split(y).join("/");if(H.isDirectory()){if(`${O}/`.startsWith($)||$.startsWith(`${O}/`))await Y(V)}else if(H.isFile()&&O.startsWith($))X.push(O)}};await Y(J),X.sort();for(let W of X){Q?.throwIfAborted();let G;try{G=await n0(`${Z}/${W}`)}catch(H){if(H?.code==="ENOENT")continue;throw H}yield{name:W,size:G.size,lastModified:G.mtime}}}async deletePrefix(K,Q={}){W1(K);let{root:Z,match:J}=this.resolvePrefix(K);W1(J);let $=await super.deletePrefix(K,Q);if($>0)await this.pruneEmptyDirs(Z,J);return $}async pruneEmptyDirs(K,Q){let Z=[],J=async($)=>{let X;try{X=await T1($,{withFileTypes:!0})}catch{return}for(let Y of X){if(!Y.isDirectory())continue;let W=`${$}${y}${Y.name}`,G=H1(K,W).split(y).join("/");if(`${G}/`.startsWith(Q)||Q.startsWith(`${G}/`)){if(await J(W),`${G}/`.startsWith(Q))Z.push(W)}}};await J(K);for(let $ of Z)try{await i0($)}catch{}}async list(){return await T1(this.folderPath)}}var f=30000;function tK(K){return K}function V0(){return{driver:new S1,fetchTimeoutMs:f,fetchIdleTimeoutMs:f}}class k1{static token="filesystem";driver;fetchTimeoutMs;fetchIdleTimeoutMs;constructor(K={}){this.driver=K.driver??V0().driver,this.fetchTimeoutMs=K.fetchTimeoutMs??f,this.fetchIdleTimeoutMs=K.fetchIdleTimeoutMs??f}}class O0 extends Error{driver;limit;timeoutMs;object;code="storage-fetch-timeout";constructor(K,Q,Z,J){super(Q==="fetchTimeoutMs"?`${K}: no response for "${J}" within ${Z}ms (fetchTimeoutMs)`:`${K}: the body of "${J}" sent nothing for ${Z}ms (fetchIdleTimeoutMs)`);this.driver=K;this.limit=Q;this.timeoutMs=Z;this.object=J;this.name="StorageFetchTimeoutError"}}async function j0(K,Q,Z,J){let{fetchTimeoutMs:$,fetchIdleTimeoutMs:X}=J;if(Z.signal||!$&&!X)return K.fetch(Q,Z);let Y=new AbortController,W=K.constructor?.name||"FileStorageDriver",G=typeof Q==="string"?Q:Q.name,H=(B,z)=>{let U=new O0(W,B,z,G);return Y.abort(U),U},V=Promise.resolve(K.fetch(Q,{...Z,signal:Y.signal})),O;if($){let B,z=new Promise((U,D)=>{B=setTimeout(()=>D(H("fetchTimeoutMs",$)),$)});try{O=await Promise.race([V,z])}catch(U){if(Y.signal.aborted)throw V.then((D)=>D.body?.cancel(Y.signal.reason).catch(()=>{}),()=>{}),Y.signal.reason;throw U}finally{clearTimeout(B)}}else O=await V;if(!X||!O.body)return O;return new Response(s0(O.body,X,()=>H("fetchIdleTimeoutMs",X)),{status:O.status,statusText:O.statusText,headers:O.headers})}function s0(K,Q,Z){let J=K.getReader();return new ReadableStream({async pull($){let X,Y,W=new Promise((G,H)=>{X=setTimeout(()=>{Y=Z(),H(Y)},Q)});try{let G=await Promise.race([J.read(),W]);if(G.done)$.close();else $.enqueue(G.value)}catch(G){let H=Y??G;$.error(H),J.cancel(H).catch(()=>{})}finally{clearTimeout(X)}},cancel($){return J.cancel($)}},{highWaterMark:0})}class A extends Error{code="safe-fetch";url;constructor(K,Q,Z){super(K,Z);this.name=new.target.name,this.url=Q}}class g extends A{reason;code="invalid-url";constructor(K,Q,Z){super(Z,K);this.reason=Q}}class O1 extends A{host;reason;code="blocked-host";constructor(K,Q,Z){super(Z==="denied"?`Requests to ${Q} are not allowed.`:`${Q} is not on the list of hosts this request may reach.`,K);this.host=Q;this.reason=Z}}class d extends A{host;address;range;code="blocked-address";constructor(K,Q,Z,J){super(Q===Z?`${Z} is not a public address (${J}).`:`${Q} resolves to ${Z}, which is not a public address (${J}).`,K);this.host=Q;this.address=Z;this.range=J}}class j1 extends A{host;code="dns";constructor(K,Q,Z){super(`Couldn't resolve ${Q}.`,K,{cause:Z});this.host=Q}}class z1 extends A{phase;ms;code="timeout";constructor(K,Q,Z){super(Q==="connect"?`Couldn't connect within ${Z} ms.`:`The request didn't finish within ${Z} ms.`,K);this.phase=Q;this.ms=Z}}class P1 extends A{limit;code="too-large";constructor(K,Q){super(`The response is larger than ${Q} bytes.`,K);this.limit=Q}}class e extends A{contentType;allowed;code="content-type";constructor(K,Q,Z){super(`The response is ${Q??"of no content type"}, not ${Z.join(" or ")}.`,K);this.contentType=Q;this.allowed=Z}}class E1 extends A{limit;code="too-many-redirects";constructor(K,Q){super(`More than ${Q} redirects.`,K);this.limit=Q}}class l extends A{code="network";constructor(K,Q){super(`The request failed: ${Q instanceof Error?Q.message:String(Q)}`,K,{cause:Q})}}class x1 extends A{status;code="http-status";constructor(K,Q){super(`The server answered ${Q}.`,K);this.status=Q}}function a0(K){if(K==="")return null;let Q=K.split(".");if(Q.length>1&&Q[Q.length-1]==="")Q.pop();if(Q.length===0||Q.length>4)return null;let Z=[];for(let X of Q){let Y=t0(X);if(Y===null)return null;Z.push(Y)}let J=Z.pop();for(let X of Z)if(X>255)return null;if(J>=256**(4-Z.length))return null;let $=J;return Z.forEach((X,Y)=>{$+=X*256**(3-Y)}),new Uint8Array([Math.floor($/16777216)&255,Math.floor($/65536)&255,Math.floor($/256)&255,$&255])}function t0(K){if(K==="")return null;let Q=K,Z=10;if(/^0x/i.test(Q)){if(Q=Q.slice(2),Z=16,Q==="")return 0}else if(Q.length>1&&Q.startsWith("0"))Q=Q.slice(1),Z=8;if(!(Z===16?/^[0-9a-f]+$/i:Z===8?/^[0-7]+$/:/^[0-9]+$/).test(Q))return null;let $=parseInt(Q,Z);return Number.isSafeInteger($)?$:null}function z0(K){let Q=K;if(Q.startsWith("[")&&Q.endsWith("]"))Q=Q.slice(1,-1);let Z=Q.indexOf("%");if(Z!==-1)Q=Q.slice(0,Z);if(!Q.includes(":"))return null;let J=Q.split("::");if(J.length>2)return null;let $=(H,V)=>{if(H==="")return[];let O=[],B=H.split(":");for(let z=0;z<B.length;z++){let U=B[z];if(V&&z===B.length-1&&U.includes(".")){if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(U))return null;let D=U.split(".").map(Number);if(D.some((F)=>F>255))return null;O.push(D[0]<<8|D[1],D[2]<<8|D[3]);continue}if(!/^[0-9a-f]{1,4}$/i.test(U))return null;O.push(parseInt(U,16))}return O},X=$(J[0],J.length===1),Y=J.length===2?$(J[1],!0):[];if(!X||!Y)return null;let W;if(J.length===2){let H=8-X.length-Y.length;if(H<1)return null;W=[...X,...Array.from({length:H},()=>0),...Y]}else W=X;if(W.length!==8)return null;let G=new Uint8Array(16);return W.forEach((H,V)=>{G[V*2]=H>>8,G[V*2+1]=H&255}),G}function K1(K){let Q=z0(K);if(Q)return{family:6,bytes:Q};let Z=a0(K);if(Z)return{family:4,bytes:Z};return null}function h(K){if(K.family===6&&r0(K.bytes))return{family:4,bytes:K.bytes.slice(12)};return K}function r0(K){for(let Q=0;Q<10;Q++)if(K[Q]!==0)return!1;return K[10]===255&&K[11]===255}function Q1(K){if(K.family===4)return Array.from(K.bytes).join(".");let Q=[];for(let Z=0;Z<16;Z+=2)Q.push((K.bytes[Z]<<8|K.bytes[Z+1]).toString(16));return Q.join(":")}function i(K){let Q=K.lastIndexOf("/"),Z=Q===-1?K:K.slice(0,Q),J=/^[0-9.]+$/.test(Z)?e0(Z):z0(Z);if(!J)return null;let $=h(J.length===4?{family:4,bytes:J}:{family:6,bytes:J}),X=$.family===4?32:128,Y=X;if(Q!==-1){let W=K.slice(Q+1);if(!/^\d{1,3}$/.test(W))return null;if(Y=Number(W),J.length===16&&$.family===4)Y-=96;if(Y<0||Y>X)return null}return{family:$.family,bytes:$.bytes,prefix:Y}}function e0(K){return/^\d{1,3}(\.\d{1,3}){3}$/.test(K)&&K.split(".").every((Q)=>Number(Q)<=255)?new Uint8Array(K.split(".").map(Number)):null}function q(K,Q){let Z=h(K);if(Z.family!==Q.family)return!1;let J=Q.prefix;for(let $=0;J>0;$++){let X=Math.min(8,J),Y=255<<8-X&255;if((Z.bytes[$]&Y)!==(Q.bytes[$]&Y))return!1;J-=X}return!0}var P=(K,Q)=>({cidr:i(K),kind:Q,text:K}),K4=[P("0.0.0.0/8","unspecified"),P("10.0.0.0/8","private"),P("100.64.0.0/10","shared"),P("127.0.0.0/8","loopback"),P("169.254.169.254/32","metadata"),P("169.254.0.0/16","link-local"),P("168.63.129.16/32","metadata"),P("172.16.0.0/12","private"),P("192.0.0.0/24","reserved"),P("192.0.2.0/24","documentation"),P("192.88.99.0/24","reserved"),P("192.168.0.0/16","private"),P("198.18.0.0/15","benchmarking"),P("198.51.100.0/24","documentation"),P("203.0.113.0/24","documentation"),P("224.0.0.0/4","multicast"),P("255.255.255.255/32","broadcast"),P("240.0.0.0/4","reserved")],Q4=[P("::/128","unspecified"),P("::1/128","loopback"),P("64:ff9b:1::/48","private"),P("::/8","reserved"),P("100::/64","reserved"),P("2001:db8::/32","documentation"),P("2001::/23","reserved"),P("3fff::/20","documentation"),P("fd00:ec2::254/128","metadata"),P("fc00::/7","unique-local"),P("fe80::/10","link-local"),P("fec0::/10","private"),P("ff00::/8","multicast")],Z4=i("64:ff9b::/96"),J4=i("2002::/16"),$4=i("2000::/3");function U1(K){let Q=typeof K==="string"?K1(K):K;if(!Q)return{kind:"reserved",range:"not an IP address"};let Z=h(Q);if(Z.family===4){let $=K4.find((X)=>q(Z,X.cidr));return $?{kind:$.kind,range:$.text}:null}if(q(Z,Z4))return U1({family:4,bytes:Z.bytes.slice(12)});if(q(Z,J4))return U1({family:4,bytes:Z.bytes.slice(2,6)});let J=Q4.find(($)=>q(Z,$.cidr));if(J)return{kind:J.kind,range:J.text};return q(Z,$4)?null:{kind:"reserved",range:"outside 2000::/3"}}function P0(K,Q){let Z=h(K),J=h(Q);return Z.family===J.family&&Z.bytes.every(($,X)=>$===J.bytes[X])}import{lookup as X4}from"dns/promises";import*as Y4 from"http";import*as G4 from"https";import*as n from"zlib";class q1 extends Response{#K;#Q;address;constructor(K,Q,Z){super(K,Q);this.#K=Z.url,this.#Q=Z.redirected,this.address=Z.address}get url(){return this.#K}get redirected(){return this.#Q}}var Z1={timeout:30000,connectTimeout:1e4,maxSize:10485760,maxRedirects:5,ports:[80,443]},W4=new Set([301,302,303,307,308]),H4=new Set([101,103,204,205,304]),V4=["host","connection","content-length","transfer-encoding","keep-alive","upgrade"],O4=["authorization","cookie","proxy-authorization"];async function M0(K,Q={}){let Z=j4(Q),J=Q.signal;J?.throwIfAborted();let $=new AbortController,X=$.signal,Y=String(K),W=(O)=>{if(!X.aborted)$.abort(O)},G=setTimeout(()=>W(new z1(Y,"total",Z.timeout)),Z.timeout),H=()=>W(J.reason);J?.addEventListener("abort",H,{once:!0});let V=()=>{clearTimeout(G),J?.removeEventListener("abort",H)};try{let O=D0(Y,Z),B=(Q.method??"GET").toUpperCase(),z=new Headers(Q.headers);for(let D of V4)z.delete(D);if(!z.has("accept"))z.set("accept","*/*");if(!z.has("user-agent"))z.set("user-agent","gemi");if(!z.has("accept-encoding"))z.set("accept-encoding","gzip, deflate, br");let U=await D4(B,Q.body,z);for(let D=0;;D++){Y=O.href;let{request:F,response:N,address:S}=await M4(O,B,z,U,Z,X),_=N.statusCode??0,I=N.headers.location;if(W4.has(_)&&I&&Q.redirect!=="manual"){if(F.destroy(),D>=Z.maxRedirects)throw new E1(O.href,Z.maxRedirects);let k;try{k=new URL(I,O)}catch{throw new g(I,"malformed",`The redirect to "${I}" is not a URL.`)}if(_===303?B!=="HEAD":(_===301||_===302)&&B==="POST"){B="GET",U=null;let R=[];z.forEach((M,j)=>{if(j.startsWith("content-"))R.push(j)});for(let M of R)z.delete(M)}if(k.origin!==O.origin)for(let R of O4)z.delete(R);O=D0(k.href,Z);continue}return R4({url:O,hop:D,method:B,request:F,response:N,address:S,policy:Z,signal:X,release:V})}}catch(O){throw V(),X.aborted?X.reason:O}}function j4(K){let Q=(J,$)=>{let X={hosts:[],ranges:[]};for(let Y of J){let W=Y.includes("/")||Y.includes(":")||/^[\d.]+$/.test(Y),G=W?i(Y):null;if(G)X.ranges.push(G);else if(!W&&/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*\.?$/i.test(Y))X.hosts.push(R0(Y));else throw TypeError(`safeFetch: "${Y}" in ${$} is not a host name or an IP range.`)}return X},Z=K.allowPrivate;return{timeout:K.timeout??Z1.timeout,connectTimeout:K.connectTimeout??Z1.connectTimeout,maxSize:K.maxSize??Z1.maxSize,maxRedirects:K.maxRedirects??Z1.maxRedirects,ports:K.ports??Z1.ports,allow:K.allow&&K.allow.length>0?Q(K.allow,"allow"):null,deny:Q(K.deny??[],"deny"),allowPrivate:Z===!0?!0:Q(Z||[],"allowPrivate").ranges,contentTypes:K.contentTypes?.length?K.contentTypes:null,resolve:K.resolve??z4}}async function z4(K){return(await X4(K,{all:!0,verbatim:!0})).map((Z)=>Z.address)}function R0(K){return K.toLowerCase().replace(/\.$/,"")}function U0(K,Q){return Q.some((Z)=>Z.startsWith("*.")?K.endsWith(Z.slice(1)):K===Z)}function D0(K,Q){let Z;try{Z=new URL(K)}catch{throw new g(K,"malformed",`"${K}" is not a URL.`)}if(Z.protocol!=="http:"&&Z.protocol!=="https:")throw new g(Z.href,"scheme",`Only http and https URLs can be fetched, not ${Z.protocol.slice(0,-1)}.`);if(Z.username||Z.password)throw new g(Z.href,"credentials","The URL has a username or password in it.");let J=B0(Z);if(Q.ports!=="any"&&!Q.ports.includes(J))throw new g(Z.href,"port",`Port ${J} is not allowed.`);return Z}function B0(K){return K.port?Number(K.port):K.protocol==="https:"?443:80}async function P4(K,Q,Z){let J=R0(K.hostname.replace(/^\[(.*)\]$/,"$1")),$=K1(J),X=$!==null&&(J.includes(":")||/^\d+\.\d+\.\d+\.\d+$/.test(J));if(!X&&U0(J,Q.deny.hosts))throw new O1(K.href,J,"denied");let Y=!X&&Q.allow!==null&&U0(J,Q.allow.hosts);if(Q.allow&&!Y&&Q.allow.ranges.length===0)throw new O1(K.href,J,"not-allowed");let W;if(X)W=[$];else{let G;try{G=await U4(Q.resolve(J),Z)}catch(H){if(Z.aborted)throw Z.reason;throw new j1(K.href,J,H)}if(W=G.map((H)=>K1(H)).filter((H)=>H!==null),W.length===0)throw new j1(K.href,J)}for(let G of W){let H=Q1(G);if(Q.deny.ranges.some((O)=>q(G,O)))throw new d(K.href,J,H,"denied");if(Q.allow&&!Y&&!Q.allow.ranges.some((O)=>q(G,O)))throw new d(K.href,J,H,"not-allowed");let V=U1(G);if(V&&Q.allowPrivate!==!0&&!Q.allowPrivate.some((O)=>q(G,O)))throw new d(K.href,J,H,V.kind)}return{host:J,addresses:W,isLiteral:X}}function U4(K,Q){if(Q.aborted)return Promise.reject(Q.reason);return new Promise((Z,J)=>{let $=()=>J(Q.reason);Q.addEventListener("abort",$,{once:!0}),K.then((X)=>{Q.removeEventListener("abort",$),Z(X)},(X)=>{Q.removeEventListener("abort",$),J(X)})})}async function D4(K,Q,Z){if(Q===void 0||Q===null)return null;if(K==="GET"||K==="HEAD")throw TypeError(`safeFetch: a ${K} request can't have a body.`);let J=new Request("http://body.invalid/",{method:"POST",body:Q}),$=J.headers.get("content-type");if($&&!Z.has("content-type"))Z.set("content-type",$);return new Uint8Array(await J.arrayBuffer())}async function M4(K,Q,Z,J,$,X){let Y=new AbortController,W=setTimeout(()=>Y.abort(new z1(K.href,"connect",$.connectTimeout)),$.connectTimeout),G=AbortSignal.any([X,Y.signal]);try{let{host:H,addresses:V,isLiteral:O}=await P4(K,$,G),B=K.protocol==="https:",z={};if(Z.forEach((U,D)=>{z[D]=U}),J)z["content-length"]=String(J.byteLength);return await new Promise((U,D)=>{let F={method:Q,host:H,port:B0(K),path:`${K.pathname}${K.search}`,headers:z,agent:!1,lookup:(R,M,j)=>{let w=M?.family,C=V.filter((J1)=>!w||J1.family===w);if(C.length===0)j(Object.assign(Error(`No IPv${w} address for ${H}`),{code:"ENOTFOUND"}));else if(M?.all)j(null,C.map((J1)=>({address:Q1(J1),family:J1.family})));else j(null,Q1(C[0]),C[0].family)}};if(B&&!O)F.servername=H;let N=(B?G4:Y4).request(F),S=null,_=(R)=>{G.removeEventListener("abort",I),N.destroy(),D(R)},I=()=>_(G.aborted?G.reason:X.reason);G.addEventListener("abort",I,{once:!0});let k=(R)=>{let M=R?.remoteAddress;if(!M||S!==null)return!0;let j=K1(M);if(!j||!V.some((w)=>P0(w,j)))return _(new d(K.href,H,M,"not-allowed")),!1;return S=Q1(h(j)),!0};N.once("socket",(R)=>{let M=()=>{if(k(R)&&!B)clearTimeout(W)};if(R.connecting)R.once("connect",M);else M();if(B)R.once("secureConnect",()=>clearTimeout(W))}),N.once("response",(R)=>{if(clearTimeout(W),R.on("error",()=>{}),!k(R.socket))return;G.removeEventListener("abort",I),U({request:N,response:R,address:S})}),N.on("error",(R)=>{if(G.aborted)return _(G.reason);_(R instanceof A?R:new l(K.href,R))}),N.end(J??void 0)})}finally{clearTimeout(W)}}function R4({url:K,hop:Q,method:Z,request:J,response:$,address:X,policy:Y,signal:W,release:G}){let H=$.statusCode??0;if(H<200||H>599)throw J.destroy(),new l(K.href,Error(`Unexpected status ${H}`));let V=new Headers,O=$.rawHeaders;for(let M=0;M<O.length;M+=2)V.append(O[M],O[M+1]);if(Y.contentTypes){let M=V.get("content-type")?.split(";")[0].trim().toLowerCase()??null;if(!M||!Y.contentTypes.some((j)=>B4(M,j)))throw J.destroy(),new e(K.href,M,Y.contentTypes)}let B={url:K.href,redirected:Q>0,address:X},z={status:H,statusText:$.statusMessage??"",headers:V};if(Z==="HEAD"||H4.has(H))return J.destroy(),G(),new q1(null,z,B);let U=V.get("content-encoding")?.trim().toLowerCase(),D=U==="gzip"||U==="x-gzip"?n.createGunzip():U==="deflate"?n.createInflate():U==="br"?n.createBrotliDecompress():null,F=Number(V.get("content-length"));if(!D&&Number.isFinite(F)&&F>Y.maxSize)throw J.destroy(),new P1(K.href,Y.maxSize);if(D)V.delete("content-encoding"),V.delete("content-length");let N=D?$.pipe(D):$,S=0,_=!1,I=()=>{},k=()=>{_=!0,W.removeEventListener("abort",I),G()},R=new ReadableStream({start(M){let j=(C)=>{if(_)return;if(k(),C===void 0)M.close();else J.destroy(),D?.destroy(),M.error(C)};if(I=()=>j(W.reason),W.addEventListener("abort",I,{once:!0}),W.aborted)return I();N.on("data",(C)=>{if(_)return;if(S+=C.byteLength,S>Y.maxSize)return j(new P1(K.href,Y.maxSize));if(M.enqueue(new Uint8Array(C)),(M.desiredSize??1)<=0)N.pause()}),N.once("end",()=>j());let w=(C)=>j(C instanceof A?C:new l(K.href,C));if(N.on("error",w),D)$.on("error",w);$.once("aborted",()=>j(new l(K.href,Error("The response was cut off."))))},pull(){N.resume()},cancel(){if(_)return;k(),J.destroy(),D?.destroy()}});return new q1(R,z,B)}function B4(K,Q){let Z=Q.toLowerCase();return Z.endsWith("/*")?K.startsWith(Z.slice(0,-1)):K===Z}function L0(K){return C4(K)??I4(K)??A4(K)}var b1=4096,N4={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/avif":"avif","image/heic":"heic","image/heif":"heif","image/bmp":"bmp","image/tiff":"tiff","image/x-icon":"ico","image/svg+xml":"svg","audio/mpeg":"mp3","audio/aac":"aac","audio/mp4":"m4a","audio/ogg":"ogg","audio/flac":"flac","audio/wav":"wav","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm","video/x-matroska":"mkv","video/x-msvideo":"avi","font/woff":"woff","font/woff2":"woff2","font/ttf":"ttf","font/otf":"otf","application/pdf":"pdf","application/zip":"zip","application/gzip":"gz","application/xml":"xml","text/html":"html","text/plain":"txt","application/octet-stream":"bin"};function C0(K){return N4[K]??"bin"}function T(K,Q,Z=0){if(K.length<Z+Q.length)return!1;return Q.every((J,$)=>K[Z+$]===J)}function b(K,Q,Z){return String.fromCharCode(...K.subarray(Q,Z))}var L4={avif:"image/avif",avis:"image/avif",heic:"image/heic",heix:"image/heic",hevc:"image/heic",hevx:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif","qt ":"video/quicktime","M4A ":"audio/mp4","M4B ":"audio/mp4"};function C4(K){if(T(K,[137,80,78,71,13,10,26,10]))return"image/png";if(T(K,[255,216,255]))return"image/jpeg";if(K.length>=6&&(b(K,0,6)==="GIF87a"||b(K,0,6)==="GIF89a"))return"image/gif";if(K.length>=12&&b(K,0,4)==="RIFF"){let Q=b(K,8,12);if(Q==="WEBP")return"image/webp";if(Q==="WAVE")return"audio/wav";if(Q==="AVI ")return"video/x-msvideo"}if(K.length>=12&&b(K,4,8)==="ftyp"){let Q=b(K,8,12);return L4[Q]??"video/mp4"}if(T(K,[73,73,42,0])||T(K,[77,77,0,42]))return"image/tiff";if(T(K,[66,77])&&T(K,[0,0,0,0],6))return"image/bmp";if(T(K,[0,0,1,0])&&K.length>=6&&K[4]>0)return"image/x-icon";if(T(K,[37,80,68,70,45]))return"application/pdf";if(T(K,[80,75,3,4]))return"application/zip";if(T(K,[31,139]))return"application/gzip";if(T(K,[26,69,223,163]))return b(K,0,Math.min(K.length,64)).includes("webm")?"video/webm":"video/x-matroska";if(K.length>=4){let Q=b(K,0,4);if(Q==="OggS")return"audio/ogg";if(Q==="fLaC")return"audio/flac";if(Q==="wOFF")return"font/woff";if(Q==="wOF2")return"font/woff2";if(Q==="OTTO")return"font/otf"}if(T(K,[0,1,0,0,0]))return"font/ttf";if(K.length>=3&&b(K,0,3)==="ID3")return"audio/mpeg";if(K.length>=2&&K[0]===255){if((K[1]&246)===240)return"audio/aac";if((K[1]&224)===224&&(K[1]&6)!==0)return"audio/mpeg"}return null}var _4=["!doctype html","html","head","script","iframe","h1","div","font","table","a","style","title","b","body","br","p","!--"];function I4(K){let Q=new TextDecoder("utf-8",{fatal:!1}).decode(K);if(Q.charCodeAt(0)===65279)Q=Q.slice(1);if(Q=Q.trimStart(),!Q.startsWith("<"))return null;let Z=Q.toLowerCase(),J=Z;for(;;){J=J.trimStart();let $=/^(<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!doctype[^>]*>)/.exec(J);if(!$)break;J=J.slice($[0].length)}if(/^<svg[\s>/]/.test(J))return"image/svg+xml";for(let $ of _4){if(!Z.startsWith(`<${$}`))continue;if(/^[\s>]/.test(Z.charAt($.length+1)))return"text/html"}if(/^<(html|head|body)[\s>]/.test(J))return"text/html";if(Z.startsWith("<?xml"))return"application/xml";return null}function A4(K){if(K.length===0)return"application/octet-stream";for(let Q of K)if(Q<32&&Q!==9&&Q!==10&&Q!==12&&Q!==13&&Q!==27)return"application/octet-stream";try{return new TextDecoder("utf-8",{fatal:!0}).decode(K,{stream:!0}),"text/plain"}catch{return"application/octet-stream"}}var F4=new Set(["text/html","application/xhtml+xml","image/svg+xml","text/xml","application/xml","text/xsl","application/xslt+xml"]);function N0(K){let Q=K.split(";")[0].trim().toLowerCase();return F4.has(Q)||Q.endsWith("+xml")}function _0(K,Q){let Z=K.split(";")[0].trim().toLowerCase();return Q.some((J)=>{let $=J.split(";")[0].trim().toLowerCase();if($==="*/*"||$==="*")return!N0(Z);if($.endsWith("/*"))return Z.startsWith($.slice(0,-1))&&!N0(Z);return Z===$})}import{Buffer as S4}from"buffer";async function I0(K){try{return(await import("sharp")).default}catch(Q){throw Error(`${K} requires the 'sharp' package. Install it with \`bun add sharp\`.`,{cause:Q})}}async function A0(K,Q,Z={}){let{name:J,directory:$,bucket:X,maxSize:Y,timeout:W,contentTypes:G,signal:H}=Z;if(J!==void 0&&$!==void 0)throw TypeError("Storage.putFromUrl(): pass `name` or `directory`, not both.");if(J!==void 0&&!J)throw TypeError("Storage.putFromUrl(): `name` is empty.");let V=await M0(Q,{...Z.fetch,method:"GET",redirect:"follow",contentTypes:void 0,signal:H,timeout:W,maxSize:Y});if(!V.ok)throw await V.body?.cancel().catch(()=>{}),new x1(V.url,V.status);let O=(V.body??new Response(new Uint8Array).body).getReader(),B=async(j)=>{throw await O.cancel(j).catch(()=>{}),j},z=[],U=0,D=!1;while(U<b1){let{done:j,value:w}=await O.read();if(j){D=!0;break}z.push(w),U+=w.byteLength}let F=T4(z,U),N=L0(F.subarray(0,Math.min(U,b1))),S=G?.length?G:["*/*"];if(!_0(N,S))await B(new e(V.url,N,S));let _=J??[($??"").replace(/\/+$/,""),`${Bun.randomUUIDv7()}.${C0(N)}`].filter(Boolean).join("/"),I=U,k=new ReadableStream({start(j){if(U>0)j.enqueue(F);if(D)j.close()},async pull(j){let{done:w,value:C}=await O.read();if(w){j.close();return}I+=C.byteLength,j.enqueue(C)},cancel(j){return O.cancel(j)}}),R={name:_,bucket:X,body:k,contentType:N},M;try{M=K.putStream?await K.putStream(R,{signal:H}):await t.prototype.putStream.call(K,R,{signal:H})}catch(j){throw await B(j),j}return{name:M,contentType:N,size:I,url:V.url}}function T4(K,Q){if(K.length===1)return K[0];let Z=new Uint8Array(Q),J=0;for(let $ of K)Z.set($,J),J+=$.byteLength;return Z}class k4 extends a{static getFacadeAccessor(){return k1}static async put(K,Q={}){return this.getFacadeRoot().driver.put(K,Q)}static async putFromUrl(K,Q={}){return A0(this.getFacadeRoot().driver,K,Q)}static async metadata(K){let Q=S4.from(await K.arrayBuffer()),Z=await I0("Storage.metadata()");try{return await Z(Q).metadata()}catch{return{}}}static async fetch(K,Q={}){Q.signal?.throwIfAborted();let Z=this.getFacadeRoot();return j0(Z.driver,K,Q,{fetchTimeoutMs:Z.fetchTimeoutMs??f,fetchIdleTimeoutMs:Z.fetchIdleTimeoutMs??f})}static async read(K,Q={}){let Z=typeof K==="string"?{name:K}:{...K},J="range"in Q?Q.range??null:Z.range!==void 0?Z.range:E.getStore()?.rangeRequest??null;return this.getFacadeRoot().driver.read({...Z,range:J})}static list(K){return this.getFacadeRoot().driver.list(K)}static objects(K,Q={}){return this.getFacadeRoot().driver.objects(K,Q)}static async deletePrefix(K,Q={}){return this.getFacadeRoot().driver.deletePrefix(K,Q)}static async delete(K){return this.getFacadeRoot().driver.delete(K)}}var F0=["cookie","set-cookie","authorization","proxy-authorization","x-api-key"];function IQ(K){return K}function AQ(){let K=Bun.env.NODE_ENV==="development";return{maxFileSize:10485760,console:K,consoleFormat:K?"text":"json",requestFields:[],redactHeaders:[],onLogFileClosed:()=>{},onLogCreated:()=>{}}}import{mkdir as f1,readdir as b4,access as v4}from"fs/promises";var v1=["debug","info","notice","warning","error","critical","alert","emergency"],E4=v1.indexOf("warning");function T0(K){if(!K)return-1;if(K===!0)return 0;let Q=v1.indexOf(K);return Q===-1?0:Q}function x4(){let K=new WeakSet;return function(Q,Z){if(typeof Z==="bigint")return Z.toString();if(Z instanceof Error){let J={name:Z.name,message:Z.message,stack:Z.stack};for(let $ of Object.keys(Z))J[$]=Z[$];if(Z.cause!==void 0)J.cause=Z.cause;return J}if(Z!==null&&typeof Z==="object"){if(K.has(Z))return"[Circular]";K.add(Z)}return Z}}function w0(K){try{return JSON.stringify(K,x4())}catch{return'"[Unserializable]"'}}function q4(K,Q){if(Q==="json")return w0({...K.metadata,timestamp:K.timestamp,level:K.level,message:K.message});let Z=Object.keys(K.metadata).length>0;return`${K.timestamp} ${K.level.toUpperCase()} ${K.message}${Z?` ${w0(K.metadata)}`:""}`}function S0(K,Q){let Z=v1.indexOf(K.level);if(Q.threshold===-1||Z<Q.threshold)return;try{let J=q4(K,Q.format)+`
3
- `;if(Z>=E4)process.stderr.write(J);else process.stdout.write(J)}catch{}}async function y1(K){try{return await v4(K),!0}catch{return!1}}class g1{config;static token="log";writer;isReady=!1;flushTimeout;fileSize=0;writerSize=0;isCreatingFile=!1;bootPromise=null;currentLogFilePath;get logsDirPath(){return`${r()}/storage/logs`}consoleThreshold;redactedHeaders;constructor(K){this.config=K;this.consoleThreshold=T0(K.console),this.redactedHeaders=new Set([...F0,...K.redactHeaders??[]].map((Q)=>Q.toLowerCase()))}requestMetadata(K){let Q=new URL(K.url),Z={method:K.method,path:Q.pathname,userAgent:K.headers.get("user-agent")??void 0},J=K.headers.get("x-request-id");if(J)Z.requestId=J;let $=this.config.requestFields??[];if($.includes("url"))Z.url=K.url;if($.includes("headers")){let X={};K.headers.forEach((Y,W)=>{X[W]=this.redactedHeaders.has(W)?"[redacted]":Y}),Z.headers=X}return Z}boot(){if(!this.bootPromise)this.bootPromise=this.createStorage().catch((K)=>{console.error("Log storage unavailable, file logging disabled",K)}).then(()=>{this.isReady=!0});return this.bootPromise}async createStorage(){let K=`${r()}/storage`;if(!await y1(K))await f1(K);if(!await y1(this.logsDirPath))await f1(this.logsDirPath);await this.newLogFile()}async newLogFile(){if(!await y1(this.logsDirPath))await f1(this.logsDirPath);if(this.isCreatingFile=!0,this.currentLogFilePath){this.writer.flush(),this.writer.end(),this.writer=null;let Z=new File([await Bun.file(this.currentLogFilePath).arrayBuffer()],this.currentLogFilePath.split("/").pop(),{type:"text/plain"});this.config.onLogFileClosed(Z),this.fileSize=0,this.writerSize=0}let Q=(await b4(this.logsDirPath)).sort().reverse()[0];if(Q){let Z=Bun.file(`${this.logsDirPath}/${Q}`);if(Z.size<this.config.maxFileSize)this.currentLogFilePath=`${this.logsDirPath}/${Q}`,this.writer=Z.writer(),this.writer.write(await Z.text()),this.writer.write(`
4
- `),this.writer.flush(),this.fileSize=Z.size}if(!this.writer){let Z=`${new Date(Date.now()).toISOString()}.log`.replaceAll(":","-");this.currentLogFilePath=`${this.logsDirPath}/${Z}`;let J=Bun.file(`${this.logsDirPath}/${Z}`);this.writer=J.writer(),this.fileSize=0,this.writerSize=0}this.isCreatingFile=!1}async log(K,Q,Z={}){if(!this.isReady)await this.boot();let J=E.getStore(),$={},X={};if(J)X={method:J.req.rawRequest.method,path:new URL(J.req.rawRequest.url).pathname},$=this.requestMetadata(J.req.rawRequest);let Y={timestamp:new Date(Date.now()).toISOString(),env:Bun.env.NODE_ENV,level:K,message:Q,metadata:{...$,...Z}};if(this.consoleThreshold!==-1)S0({timestamp:Y.timestamp,level:K,message:Q,metadata:{...X,...Z}},{threshold:this.consoleThreshold,format:this.config.consoleFormat});let W="";try{W=JSON.stringify(Y)}catch(G){console.log("Error parsing log object",G)}try{let G=this.config.onLogCreated(Y);if(G instanceof Promise)G.catch((H)=>console.error("Error in onLogCreated",H))}catch(G){console.error("Error in onLogCreated",G)}if(!this.writer)return;this.writerSize+=W.length,this.fileSize+=W.length;try{this.writer.write(W),this.writer.write(`
5
- `),this.tryFlush()}catch(G){console.error("Error writing log",G)}}async tryFlush(){if(this.fileSize>this.config.maxFileSize){if(!this.isCreatingFile)await this.newLogFile()}if(this.writerSize>this.config.maxFileSize/2)await this.writer.flush(),this.writerSize=0,await this.newLogFile();else clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(async()=>{await this.writer.flush(),this.writerSize=0},100)}}class f4 extends a{static getFacadeAccessor(){return g1}static debug(K,Q){this.getFacadeRoot().log("debug",K,Q)}static info(K,Q){this.getFacadeRoot().log("info",K,Q)}static notice(K,Q){this.getFacadeRoot().log("notice",K,Q)}static warning(K,Q){this.getFacadeRoot().log("warning",K,Q)}static error(K,Q){this.getFacadeRoot().log("error",K,Q)}static critical(K,Q){this.getFacadeRoot().log("critical",K,Q)}static alert(K,Q){this.getFacadeRoot().log("alert",K,Q)}static emergency(K,Q){this.getFacadeRoot().log("emergency",K,Q)}}class y4{config;static token="redis";instance=null;connectingSince=null;downSince=null;replaceDelay=500;constructor(K={}){this.config=K}get client(){if(this.instance===null)return this.build();let K=this.instance;if(this.isDown(K,Date.now())){this.instance=null;try{K.close()}catch{}return this.build()}return K}set client(K){this.instance=K,this.connectingSince=null,this.downSince=null,this.replaceDelay=500}close(){let K=this.instance;this.instance=null,this.connectingSince=null,this.downSince=null,this.replaceDelay=500,K?.close()}build(){let K=new(g4())(this.config.url,this.config.options);if(this.instance=K,this.downSince=null,this.connectingSince=null,typeof K.connect==="function"){this.connectingSince=Date.now();let Q;try{Q=Promise.resolve(K.connect())}catch(Z){Q=Promise.reject(Z)}Q.then(()=>{if(this.instance!==K)return;this.connectingSince=null,this.replaceDelay=500},()=>{if(this.instance!==K)return;this.connectingSince=null})}return K}isDown(K,Q){if(K.connected!==!1||typeof K.connect!=="function")return this.downSince=null,!1;if(this.connectingSince!==null){let Z=(this.config.options?.connectionTimeout??1e4)+5000;if(Q-this.connectingSince<Z)return!1;this.connectingSince=null}if(this.downSince??=Q,Q-this.downSince<this.replaceDelay)return!1;return this.replaceDelay=Math.min(this.replaceDelay*2,1e4),!0}}function g4(){let K=globalThis.Bun?.RedisClient;if(typeof K!=="function")throw Error("Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.");return K}
6
- export{h1 as li,k0 as mi,m4 as ni,a1 as oi,WK as pi,e1 as qi,HK as ri,m1 as si,c1 as ti,p4 as ui,u4 as vi,d4 as wi,p1 as xi,R1 as yi,o4 as zi,s4 as Ai,OK as Bi,Z0 as Ci,jK as Di,zK as Ei,o as Fi,x as Gi,L1 as Hi,QK as Ii,ZK as Ji,JK as Ki,$K as Li,XK as Mi,g0 as Ni,Y0 as Oi,h0 as Pi,F1 as Qi,w1 as Ri,m0 as Si,v as Ti,c0 as Ui,a as Vi,I0 as Wi,W1 as Xi,t as Yi,G0 as Zi,S1 as _i,tK as $i,V0 as aj,k1 as bj,O0 as cj,A as dj,g as ej,O1 as fj,d as gj,j1 as hj,z1 as ij,P1 as jj,e as kj,E1 as lj,l as mj,x1 as nj,K1 as oj,U1 as pj,q1 as qj,M0 as rj,L0 as sj,N0 as tj,k4 as uj,IQ as vj,AQ as wj,g1 as xj,f4 as yj,y4 as zj};
7
-
8
- //# debugId=0E63C515BDD42A4764756E2164756E21