gemi 0.218.0 → 0.219.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +2 -2
  3. package/dist/ai/testing/index.js +2 -2
  4. package/dist/ai/testing/index.js.map +1 -1
  5. package/dist/{chunk-ww62b10k.js → chunk-0egjv6cj.js} +2 -2
  6. package/dist/{chunk-ww62b10k.js.map → chunk-0egjv6cj.js.map} +1 -1
  7. package/dist/{chunk-9g5qh1ya.js → chunk-2vktfp1f.js} +2 -2
  8. package/dist/{chunk-9g5qh1ya.js.map → chunk-2vktfp1f.js.map} +1 -1
  9. package/dist/chunk-4g24ffv8.js +5 -0
  10. package/dist/{chunk-d6bgh2nr.js.map → chunk-4g24ffv8.js.map} +1 -1
  11. package/dist/chunk-4kkb85z8.js +8 -0
  12. package/dist/{chunk-xese0rng.js.map → chunk-4kkb85z8.js.map} +4 -5
  13. package/dist/{chunk-b1pps9bj.js → chunk-59p034g3.js} +2 -2
  14. package/dist/{chunk-b1pps9bj.js.map → chunk-59p034g3.js.map} +1 -1
  15. package/dist/{chunk-c95ds04p.js → chunk-66re5qsr.js} +2 -2
  16. package/dist/{chunk-c95ds04p.js.map → chunk-66re5qsr.js.map} +1 -1
  17. package/dist/{chunk-sqqh78tf.js → chunk-6my6c6b1.js} +2 -2
  18. package/dist/{chunk-sqqh78tf.js.map → chunk-6my6c6b1.js.map} +1 -1
  19. package/dist/chunk-71r1x773.js +19 -0
  20. package/dist/{chunk-4sbrvmz9.js.map → chunk-71r1x773.js.map} +3 -3
  21. package/dist/chunk-ak85ee4e.js +39 -0
  22. package/dist/chunk-ak85ee4e.js.map +20 -0
  23. package/dist/{chunk-gxd1388t.js → chunk-c250kpcm.js} +2 -2
  24. package/dist/{chunk-gxd1388t.js.map → chunk-c250kpcm.js.map} +1 -1
  25. package/dist/{chunk-4s72m6zx.js → chunk-cmyt2txd.js} +3 -3
  26. package/dist/{chunk-4s72m6zx.js.map → chunk-cmyt2txd.js.map} +1 -1
  27. package/dist/{chunk-fq7wkefg.js → chunk-cw50n89n.js} +2 -2
  28. package/dist/{chunk-fq7wkefg.js.map → chunk-cw50n89n.js.map} +1 -1
  29. package/dist/{chunk-7rmb1v9c.js → chunk-g5drp5xx.js} +2 -2
  30. package/dist/{chunk-7rmb1v9c.js.map → chunk-g5drp5xx.js.map} +1 -1
  31. package/dist/{chunk-snt0523y.js → chunk-gf3m0866.js} +2 -2
  32. package/dist/{chunk-snt0523y.js.map → chunk-gf3m0866.js.map} +1 -1
  33. package/dist/{chunk-tw338bbv.js → chunk-jfpwjqvq.js} +2 -2
  34. package/dist/{chunk-tw338bbv.js.map → chunk-jfpwjqvq.js.map} +1 -1
  35. package/dist/{chunk-gxfyd8wr.js → chunk-kt174y9e.js} +3 -3
  36. package/dist/{chunk-gxfyd8wr.js.map → chunk-kt174y9e.js.map} +1 -1
  37. package/dist/{chunk-s7jwsbfd.js → chunk-nrv7hdeh.js} +3 -3
  38. package/dist/{chunk-s7jwsbfd.js.map → chunk-nrv7hdeh.js.map} +1 -1
  39. package/dist/{chunk-7t13vyzg.js → chunk-p4b5hmr8.js} +2 -2
  40. package/dist/{chunk-7t13vyzg.js.map → chunk-p4b5hmr8.js.map} +1 -1
  41. package/dist/chunk-pnt0c59g.js +484 -0
  42. package/dist/{chunk-ktee4gy4.js.map → chunk-pnt0c59g.js.map} +8 -7
  43. package/dist/{chunk-m0pfdc1n.js → chunk-s4sx97fn.js} +3 -3
  44. package/dist/{chunk-m0pfdc1n.js.map → chunk-s4sx97fn.js.map} +1 -1
  45. package/dist/{chunk-ncw3zjxm.js → chunk-w4aw44zg.js} +2 -2
  46. package/dist/{chunk-ncw3zjxm.js.map → chunk-w4aw44zg.js.map} +1 -1
  47. package/dist/{chunk-7081awrd.js → chunk-w9a3b4vs.js} +2 -2
  48. package/dist/{chunk-7081awrd.js.map → chunk-w9a3b4vs.js.map} +1 -1
  49. package/dist/{chunk-bcfwa370.js → chunk-xm6hfksv.js} +2 -2
  50. package/dist/{chunk-bcfwa370.js.map → chunk-xm6hfksv.js.map} +1 -1
  51. package/dist/{chunk-k8nsefzb.js → chunk-xrkr2yzz.js} +2 -2
  52. package/dist/{chunk-k8nsefzb.js.map → chunk-xrkr2yzz.js.map} +1 -1
  53. package/dist/{chunk-evgs2tr8.js → chunk-xvf1hcxg.js} +2 -2
  54. package/dist/{chunk-evgs2tr8.js.map → chunk-xvf1hcxg.js.map} +2 -2
  55. package/dist/{chunk-eh3ktv8k.js → chunk-y12m6w7b.js} +2 -2
  56. package/dist/{chunk-eh3ktv8k.js.map → chunk-y12m6w7b.js.map} +1 -1
  57. package/dist/chunk-yv3y3r9q.js +88 -0
  58. package/dist/{chunk-sxxkkx75.js.map → chunk-yv3y3r9q.js.map} +3 -10
  59. package/dist/client/index.d.ts +2 -0
  60. package/dist/client/index.d.ts.map +1 -1
  61. package/dist/client/index.js +54 -1
  62. package/dist/client/index.js.map +1 -1
  63. package/dist/client/useWorkflow.d.ts +51 -0
  64. package/dist/client/useWorkflow.d.ts.map +1 -0
  65. package/dist/console/run.js +2 -2
  66. package/dist/console/run.js.map +1 -1
  67. package/dist/database/index.js +1 -1
  68. package/dist/facades/index.js +2 -2
  69. package/dist/facades/index.js.map +1 -1
  70. package/dist/http/index.js +2 -2
  71. package/dist/http/index.js.map +1 -1
  72. package/dist/i18n/index.js +2 -2
  73. package/dist/i18n/index.js.map +1 -1
  74. package/dist/kernel/index.js +2 -2
  75. package/dist/kernel/index.js.map +1 -1
  76. package/dist/orm/index.js +2 -2
  77. package/dist/orm/index.js.map +1 -1
  78. package/dist/server/index.js +1 -1
  79. package/dist/services/index.d.ts +2 -1
  80. package/dist/services/index.d.ts.map +1 -1
  81. package/dist/services/index.js +3 -3
  82. package/dist/services/index.js.map +2 -2
  83. package/dist/services/queue/QueueManager.d.ts +2 -0
  84. package/dist/services/queue/QueueManager.d.ts.map +1 -1
  85. package/dist/services/queue/work.js +2 -2
  86. package/dist/services/queue/work.js.map +1 -1
  87. package/dist/services/queue/workflow/Step.d.ts +2 -9
  88. package/dist/services/queue/workflow/Step.d.ts.map +1 -1
  89. package/dist/services/queue/workflow/Workflow.d.ts +26 -38
  90. package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
  91. package/dist/services/queue/workflow/WorkflowRuntime.d.ts +45 -0
  92. package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
  93. package/dist/services/queue/workflow/WorkflowStore.d.ts +2 -16
  94. package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -1
  95. package/dist/services/queue/workflow/wire.d.ts +71 -0
  96. package/dist/services/queue/workflow/wire.d.ts.map +1 -0
  97. package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -1
  98. package/dist/support/index.js +2 -2
  99. package/dist/support/index.js.map +1 -1
  100. package/package.json +1 -1
  101. package/dist/chunk-4sbrvmz9.js +0 -19
  102. package/dist/chunk-d6bgh2nr.js +0 -5
  103. package/dist/chunk-ktee4gy4.js +0 -484
  104. package/dist/chunk-sxxkkx75.js +0 -117
  105. package/dist/chunk-xb0evp2m.js +0 -5
  106. package/dist/chunk-xb0evp2m.js.map +0 -12
  107. package/dist/chunk-xese0rng.js +0 -13
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$ as RJ,_ as p,aa as TJ,ba as SJ}from"./chunk-7rmb1v9c.js";import{Da as b,Ha as R,Ia as BJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Te as YJ,ih as LJ,jh as k,rh as DJ,sh as PJ,th as AJ}from"./chunk-sxxkkx75.js";import"./chunk-s7jwsbfd.js";import"./chunk-4s72m6zx.js";import{Ci as jJ,yi as XJ,zi as HJ}from"./chunk-xese0rng.js";import{Pj as NJ}from"./chunk-eh3ktv8k.js";import"./chunk-snt0523y.js";import"./chunk-ww62b10k.js";import"./chunk-gxfyd8wr.js";import"./chunk-m0pfdc1n.js";import"./chunk-ncw3zjxm.js";import"./chunk-k8nsefzb.js";import"./chunk-xb0evp2m.js";import"./chunk-yxtfg4wy.js";import"./chunk-xyv3y476.js";import"./chunk-qa528feb.js";import"./chunk-jzqywxpj.js";import"./chunk-qstjm3cb.js";import"./chunk-aes0ecnp.js";import"./chunk-sba3s380.js";import{om as zJ}from"./chunk-cwm5x7rf.js";import"./chunk-q0d45r2j.js";import{Gm as FJ}from"./chunk-hmtn7996.js";import{Im as y}from"./chunk-rp2f9mq1.js";import"./chunk-yedb5vvg.js";import{createHash as L2}from"crypto";import{join as d,resolve as qJ,sep as bJ}from"path";import{Duplex as hJ}from"stream";import{constants as v,createBrotliCompress as cJ,createGzip as pJ}from"zlib";var dJ=["br","gzip"],lJ=1024,oJ=5,nJ=19,iJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function aJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let G=W.indexOf("=");if(G===-1)continue;if(W.slice(0,G).trim().toLowerCase()==="q"){Y=rJ(W.slice(G+1));break}}$.set(j,Y)}return $}function u(J,$=dJ){let Z=aJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function tJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<lJ)return!1;return!0}function eJ(J){let $=J==="br"?cJ({params:{[v.BROTLI_PARAM_QUALITY]:oJ,[v.BROTLI_PARAM_LGWIN]:nJ},flush:v.BROTLI_OPERATION_FLUSH}):pJ({level:iJ,flush:v.Z_SYNC_FLUSH});return hJ.toWeb($)}function J2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function JJ(J,$){if(!tJ(J.method,$))return $;let Z=new Headers($.headers);J2(Z);let Q=u(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=eJ(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as Y2,stat as WJ}from"fs/promises";import{join as W2}from"path";import{mkdir as B2,readFile as $2,stat as R2,writeFile as T2}from"fs/promises";import{dirname as q2,join as Z2}from"path";import{promisify as $J}from"util";import{brotliCompress as Q2,constants as v2,gzip as X2}from"zlib";var H2=".vite/static-assets.json";var ZJ={br:".br",gzip:".gz"},j2=["br","gzip"],w2=$J(Q2),k2=$J(X2);async function QJ(J){let $;try{$=await $2(Z2(J,H2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=j2.filter((Y)=>j.includes(Y))}return Q}function m(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function GJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await Y2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=W2(Q,Y.name),G=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await WJ(W);G=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(G&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var G2="public, max-age=31536000, must-revalidate",V2="public, max-age=31536000, immutable";async function z2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=u(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+ZJ[Q];try{let j=await WJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function VJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?V2:G2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await z2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${m(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=m(Q.lastModified);let G=XJ(J.headers.get("Range"));if(G){let z=HJ(G,W);if(!z)return YJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":jJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as _2}from"fs/promises";var w="app/client.tsx";function UJ(J,$=b){let Z=J[w]?.file;if(!Z)return;return{module:R(Z,$),preload:B(J,w,$)}}function B(J,$,Z=b){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(R(W.file,Z));for(let G of W.imports??[])j(G)};return j($),Q}function U2(J,$,Z=b){let Q=new Set(B(J,$,Z)),H=[],j=new Set,Y=(G)=>{if(j.has(G))return;j.add(G);let z=J[G];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let G of H)for(let z of B(J,G,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function KJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let G of W.imports??[])j(G);for(let G of W.css??[])if(!Q.has(G))Q.add(G),Z.push(G)};return j($),Z}function OJ(J,$=b){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${zJ}`,j=J[H]?.file;Z.set(Q,j?{src:R(j,$),preload:B(J,H,$),dynamicPreload:U2(J,H,$)}:void 0)}return Z.get(Q)}}var xJ="x-gemi-build";var K2="__gemiReload";function O2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},G=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=G(new URL(window.location.href).origin),I=G(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function CJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${O2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${K2}}`}var x2=new RegExp(`^${LJ}/.+\\.m?js$`);function h(J){return x2.test(J)}function _J(J){if(h(J))return new Response(CJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(k(J))return new Response("Not found",{status:404});return}function IJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function MJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,G)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(G);if(z!==void 0){if(z>H())return;j.delete(G)}let C;try{C=new URL(G.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(G);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(G);return}let L=Bun.file(G).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var C2=`<!DOCTYPE html>
2
+ import{$ as RJ,_ as p,aa as TJ,ba as SJ}from"./chunk-g5drp5xx.js";import{Da as b,Ha as R,Ia as BJ}from"./chunk-v2fd69at.js";import"./chunk-ba1h9pm6.js";import{Ue as YJ,ah as LJ,bh as k,jh as DJ,kh as PJ,lh as AJ}from"./chunk-yv3y3r9q.js";import"./chunk-nrv7hdeh.js";import"./chunk-cmyt2txd.js";import{qi as XJ,ri as HJ,ui as jJ}from"./chunk-4kkb85z8.js";import{Cj as NJ}from"./chunk-y12m6w7b.js";import"./chunk-gf3m0866.js";import"./chunk-0egjv6cj.js";import"./chunk-kt174y9e.js";import"./chunk-s4sx97fn.js";import"./chunk-w4aw44zg.js";import"./chunk-xrkr2yzz.js";import"./chunk-ak85ee4e.js";import"./chunk-yxtfg4wy.js";import"./chunk-xyv3y476.js";import"./chunk-qa528feb.js";import"./chunk-jzqywxpj.js";import"./chunk-qstjm3cb.js";import"./chunk-aes0ecnp.js";import"./chunk-sba3s380.js";import{om as zJ}from"./chunk-cwm5x7rf.js";import"./chunk-q0d45r2j.js";import{Gm as FJ}from"./chunk-hmtn7996.js";import{Im as y}from"./chunk-rp2f9mq1.js";import"./chunk-yedb5vvg.js";import{createHash as L2}from"crypto";import{join as d,resolve as qJ,sep as bJ}from"path";import{Duplex as hJ}from"stream";import{constants as v,createBrotliCompress as cJ,createGzip as pJ}from"zlib";var dJ=["br","gzip"],lJ=1024,oJ=5,nJ=19,iJ=6;function rJ(J){if(J===void 0)return 1;if(!/^\d+(\.\d{0,3})?$/.test(J.trim()))return 1;let $=Number(J.trim());return Number.isFinite($)?Math.min($,1):1}function aJ(J){if(J===null||J===void 0)return null;let $=new Map;for(let Z of J.split(",")){let[Q,...H]=Z.split(";"),j=Q.trim().toLowerCase();if(j==="")continue;let Y=1;for(let W of H){let G=W.indexOf("=");if(G===-1)continue;if(W.slice(0,G).trim().toLowerCase()==="q"){Y=rJ(W.slice(G+1));break}}$.set(j,Y)}return $}function u(J,$=dJ){let Z=aJ(J);if(!Z)return null;let Q=Z.get("*"),H=null,j=0;for(let Y of $){let W=Z.get(Y)??Q??0;if(W>j)H=Y,j=W}return H}function sJ(J,$){if(!J)return!1;return J.split(",").some((Z)=>Z.trim().toLowerCase().split("=")[0].trim()===$)}function tJ(J,$){if(J==="HEAD")return!1;if($.status<200||$.status===204||$.status===206||$.status===304)return!1;if($.headers.has("Content-Range"))return!1;let Z=$.headers.get("Content-Type");if(!Z||!/^\s*text\/html\s*(;|$)/i.test(Z))return!1;if(!$.body)return!1;let Q=$.headers.get("Content-Encoding");if(Q&&Q.trim().toLowerCase()!=="identity")return!1;if(sJ($.headers.get("Cache-Control"),"no-transform"))return!1;let H=$.headers.get("Content-Length");if(H!==null&&Number(H)<lJ)return!1;return!0}function eJ(J){let $=J==="br"?cJ({params:{[v.BROTLI_PARAM_QUALITY]:oJ,[v.BROTLI_PARAM_LGWIN]:nJ},flush:v.BROTLI_OPERATION_FLUSH}):pJ({level:iJ,flush:v.Z_SYNC_FLUSH});return hJ.toWeb($)}function J2(J){let $=J.get("Vary");if(!$){J.set("Vary","Accept-Encoding");return}let Z=$.split(",").map((Q)=>Q.trim().toLowerCase());if(Z.includes("*")||Z.includes("accept-encoding"))return;J.append("Vary","Accept-Encoding")}function JJ(J,$){if(!tJ(J.method,$))return $;let Z=new Headers($.headers);J2(Z);let Q=u(J.headers.get("Accept-Encoding"));if(!Q)return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z});let H;try{H=eJ(Q)}catch{return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}return Z.set("Content-Encoding",Q),Z.delete("Content-Length"),new Response($.body.pipeThrough(H),{status:$.status,statusText:$.statusText,headers:Z})}import{readdir as Y2,stat as WJ}from"fs/promises";import{join as W2}from"path";import{mkdir as B2,readFile as $2,stat as R2,writeFile as T2}from"fs/promises";import{dirname as q2,join as Z2}from"path";import{promisify as $J}from"util";import{brotliCompress as Q2,constants as v2,gzip as X2}from"zlib";var H2=".vite/static-assets.json";var ZJ={br:".br",gzip:".gz"},j2=["br","gzip"],w2=$J(Q2),k2=$J(X2);async function QJ(J){let $;try{$=await $2(Z2(J,H2),"utf8")}catch{return null}let Z;try{Z=JSON.parse($)?.files}catch{return null}if(!Z||typeof Z!=="object")return null;let Q={files:{}};for(let[H,j]of Object.entries(Z)){if(!Array.isArray(j))continue;Q.files[H]=j2.filter((Y)=>j.includes(Y))}return Q}function m(J){let $=J.toString(),Z=new Bun.CryptoHasher("sha1");return Z.update($),Z.digest("hex")}async function GJ(J){let $=new Set;async function Z(Q,H){let j;try{j=await Y2(Q,{withFileTypes:!0})}catch{return}for(let Y of j){if(Y.name.startsWith("."))continue;if(H&&Y.name==="assets")continue;let W=W2(Q,Y.name),G=Y.isDirectory(),z=Y.isFile();if(Y.isSymbolicLink())try{let C=await WJ(W);G=C.isDirectory(),z=C.isFile()}catch{continue}if(z)$.add(W);else if(G&&!Y.isSymbolicLink())await Z(W,!1)}}return await Z(J,!0),$}var G2="public, max-age=31536000, must-revalidate",V2="public, max-age=31536000, immutable";async function z2(J,$,Z){if(Z.length===0||J.headers.has("Range"))return null;let Q=u(J.headers.get("Accept-Encoding"),Z);if(!Q)return null;let H=$+ZJ[Q];try{let j=await WJ(H);return j.isFile()?{encoding:Q,path:H,size:j.size}:null}catch{return null}}async function VJ(J,$,Z={}){let Q=Bun.file($),H=Z.encodings??[],j={"Content-Type":Q.type||"application/octet-stream","Cache-Control":Z.immutable?V2:G2,"Accept-Ranges":"bytes"};if(H.length>0)j.Vary="Accept-Encoding";let Y=await z2(J,$,H);if(Y){let z=Bun.file(Y.path);return new Response(z.stream(),{headers:{...j,"Content-Encoding":Y.encoding,"Content-Length":String(Y.size),ETag:`${m(z.lastModified)}-${Y.encoding}`}})}let W=Q.size;j.ETag=m(Q.lastModified);let G=XJ(J.headers.get("Range"));if(G){let z=HJ(G,W);if(!z)return YJ(W);return new Response(Q.slice(z.start,z.end+1).stream(),{status:206,headers:{...j,"Content-Range":jJ(z.start,z.end,W),"Content-Length":String(z.length)}})}return new Response(Q.stream(),{headers:{...j,"Content-Length":String(W)}})}import{stat as _2}from"fs/promises";var w="app/client.tsx";function UJ(J,$=b){let Z=J[w]?.file;if(!Z)return;return{module:R(Z,$),preload:B(J,w,$)}}function B(J,$,Z=b){let Q=[],H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W?.file)return;Q.push(R(W.file,Z));for(let G of W.imports??[])j(G)};return j($),Q}function U2(J,$,Z=b){let Q=new Set(B(J,$,Z)),H=[],j=new Set,Y=(G)=>{if(j.has(G))return;j.add(G);let z=J[G];if(!z)return;for(let C of z.dynamicImports??[])if(!/(^|\/)node_modules\//.test(C)&&!H.includes(C))H.push(C);for(let C of z.imports??[])Y(C)};Y($);let W=[];for(let G of H)for(let z of B(J,G,Z))if(!Q.has(z))Q.add(z),W.push(z);return W}function KJ(J,$){let Z=[],Q=new Set,H=new Set,j=(Y)=>{if(H.has(Y))return;H.add(Y);let W=J[Y];if(!W)return;for(let G of W.imports??[])j(G);for(let G of W.css??[])if(!Q.has(G))Q.add(G),Z.push(G)};return j($),Z}function OJ(J,$=b){let Z=new Map;return(Q)=>{if(!Z.has(Q)){let H=`${Q}${zJ}`,j=J[H]?.file;Z.set(Q,j?{src:R(j,$),preload:B(J,H,$),dynamicPreload:U2(J,H,$)}:void 0)}return Z.get(Q)}}var xJ="x-gemi-build";var K2="__gemiReload";function O2(J,$,Z,Q){let H=Date.now(),j=function(U){return typeof U==="number"&&H-U>=0&&H-U<Z},Y=function(U){try{let K=U?JSON.parse(U):null;return K&&typeof K==="object"&&!Array.isArray(K)?K:{}}catch{return{}}},W=function(U){let K={};for(let M in U)if(j(U[M]))K[M]=U[M];return K},G=function(U){let K=2166136261;for(let M=0;M<U.length;M++)K=Math.imul(K^U.charCodeAt(M),16777619);return(K>>>0).toString(36)},z=null,C={};try{z=window.sessionStorage,C=Y(z.getItem(J))}catch{z=null}let N=J+":",F="",I="";try{let U=new URL($,window.location.href);F=G(new URL(window.location.href).origin),I=G(U.origin+U.pathname)}catch{}let L=null;try{let U=window.name;if(!I)L=null;else if(U==="")L={};else if(U.indexOf(N)===0){let K=Y(U.slice(N.length)),M=K.m;L=K.o===F&&M&&typeof M==="object"&&!Array.isArray(M)?M:{}}}catch{L=null}if(Q==="tidy"){try{let U=window.name;if(L===null||U.indexOf(N)!==0)return"ok";for(let K in L)if(j(L[K]))return"cooldown";window.name=""}catch{}return"ok"}if(j(C[$])||L&&j(L[I]))return"cooldown";if(!z&&!L)return"storage";if(!Q)return"ok";if(z)try{let U=W(C);U[$]=H;let K=JSON.stringify(U);if(z.setItem(J,K),z.getItem(J)===K)return"ok"}catch{}if(L)try{let U=W(L);U[I]=H;let K=N+JSON.stringify({o:F,m:U});if(window.name=K,window.name===K)return"ok"}catch{}return"storage"}function CJ(J,$=30000){let Z=JSON.stringify("gemi:chunk-reload"),Q=JSON.stringify(`Failed to fetch dynamically imported module: ${J}`);return`var g=${O2.toString()};var r=!1;try{r=navigator.onLine!==!1&&g(${Z},window.location.href,${Number($)},!0)==="ok"}catch(e){}if(r)window.location.reload();else throw new Error(${Q});export {r as ${K2}}`}var x2=new RegExp(`^${LJ}/.+\\.m?js$`);function h(J){return x2.test(J)}function _J(J){if(h(J))return new Response(CJ(J),{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store"}});if(k(J))return new Response("Not found",{status:404});return}function IJ(J){let $=J?.trim();if(!$)return;try{let Z=new URL($);if(Z.protocol!=="https:"&&Z.protocol!=="http:")throw Error("not http(s)");return Z.search="",Z.hash="",Z.href.endsWith("/")?Z.href:`${Z.href}/`}catch{console.error(`GEMI_ASSET_FALLBACK_URL is not an absolute http(s) URL (${JSON.stringify($)}); missing assets are not looked up anywhere else.`);return}}function MJ({base:J,timeoutMs:$=3000,missTtlMs:Z=30000,fetch:Q=fetch,now:H=Date.now}){let j=new Map,Y=(W)=>{if(j.delete(W),j.set(W,H()+Z),j.size>1000)j.delete(j.keys().next().value)};return async(W,G)=>{if(W.method!=="GET"&&W.method!=="HEAD")return;let z=j.get(G);if(z!==void 0){if(z>H())return;j.delete(G)}let C;try{C=new URL(G.replace(/^\/+/,""),J)}catch{return}if(!C.href.startsWith(J))return;let N=new AbortController,F=setTimeout(()=>N.abort(),$),I;try{I=await Q(C.href,{method:W.method,signal:N.signal,redirect:"error"})}catch{Y(G);return}finally{clearTimeout(F)}if(I.status!==200){I.body?.cancel().catch(()=>{}),Y(G);return}let L=Bun.file(G).type,U=new Headers({"Content-Type":L!=="application/octet-stream"&&L||I.headers.get("content-type")||"application/octet-stream","Cache-Control":"public, max-age=31536000, immutable",["x-gemi-asset-fallback"]:"1"}),K=I.headers.get("content-length");if(K&&!I.headers.get("content-encoding"))U.set("Content-Length",K);return new Response(W.method==="HEAD"?null:I.body,{status:200,headers:U})}}var C2=`<!DOCTYPE html>
3
3
  <html lang="en">
4
4
  <head>
5
5
  <meta charset="UTF-8" />
@@ -21,4 +21,4 @@ import{$ as RJ,_ as p,aa as TJ,ba as SJ}from"./chunk-7rmb1v9c.js";import{Da as b
21
21
  </html>`;function c(J,$,Z){if(!Z)console.error(J);else try{Z(J instanceof Error?J:Error(String(J),{cause:J}))}catch(Q){console.error(J),console.error(Q)}if(y($))return new Response(JSON.stringify({error:NJ("server_error","Internal Server Error",500)}),{status:500,headers:{"Content-Type":"application/json"}});return new Response(C2,{status:500,headers:{"Content-Type":"text/html; charset=utf-8"}})}var g=FJ(),I2=d(g,"app"),D=d(g,"dist"),T=d(D,"client");function M2(J){let $;try{$=decodeURIComponent(J)}catch{return null}let Z=qJ(T,"."+$.replace("/assets/assets","/assets"));return Z.startsWith(T+bJ)?Z:null}async function N2(J){try{return(await _2(J)).isFile()}catch{return!1}}async function F3(J,$){let Z=await import(`${D}/client/.vite/manifest.json`),Q=await import(`${D}/server/.vite/manifest.json`),H=await BJ(`${D}/client`);process.env.ROOT_DIR=g,process.env.APP_DIR=I2,process.env.DIST_DIR=D;let j={},Y={},W={},G={},z={},C=(X,V)=>`"${X}": () => import("${V}")`,N=[],F=J.getRequiredViews.call(J);for(let X of["404",...J.getFlatComponentTree.call(J)]){let V=Q[`app/views/${X}.tsx`];if(!V?.file&&F[X])throw TJ(X,F[X]);if(!V?.file){console.log(`Server file not found for ${X}`),console.log(V);let _=Object.keys(Q),A=`app/views/${X}.tsx`;console.log(`${A} not found in server manifest`),console.log(_)}let x=await import(`${process.env.DIST_DIR}/server/${V?.file}`);j[X]=x.default,Y[X]=x.OpenGraph,W[X]=x;let O=Z[`app/views/${X}.tsx`];if(O?.css&&O?.css.length>0)G[X]=O?.css;if(O)N.push(C(X,R(O?.file,H))),z[X]=B(Z,`app/views/${X}.tsx`,H)}let I=`{${N.join(",")}}`,L=UJ(Z,H);if(!L)console.error(`Client manifest has no "${w}" entry \u2014 dist/client is incomplete, so documents will render but never hydrate.`);let U=Z["app/client.tsx"]?.css??[],K=(await Promise.all(U.map((X)=>Bun.file(`${D}/client/${X}`).text()))).join(`
22
22
  `),M=OJ(Z,H),l=L2("sha256").update(await Bun.file(`${D}/client/.vite/manifest.json`).text()).digest("base64url").slice(0,12),o=new Map,EJ=(X)=>{let V=o.get(X);if(!V)V=Bun.file(`${D}/client/${X}`).text(),o.set(X,V);return V},vJ=async(X,V)=>{let x=new Set;for(let _ of V?[V,...X]:X)for(let A of KJ(Z,`app/views/${_}.tsx`))x.add(A);let O=await Promise.all([...x].map(async(_)=>({id:_,content:await EJ(_)})));return p(V?O:[{content:K},...O])},wJ=await GJ(T),n=new Map;for(let[X,V]of Object.entries((await QJ(T))?.files??{})){let x=qJ(T,X);if(x.startsWith(T+bJ))n.set(x,{immutable:!0,encodings:V})}let i=IJ(process.env.GEMI_ASSET_FALLBACK_URL),r=i?MJ({base:i}):void 0;async function kJ(X){let{pathname:V}=new URL(X.url);if(y(V))return await S(X,V);let x=M2(V),O=k(V),_=!O&&x!==null&&wJ.has(x),A=O||V.startsWith("/.well-known")||_;if(_&&!(await a(X)).publicFiles)return await S(X,V);if(A){if(!x||!await N2(x)){if(O&&r){let P=await r(X,V);if(P)return P}if(O&&!h(V)&&(await a(X)).assetRoutes)return await S(X,V);return _J(V)??await S(X,V)}try{return await VJ(X,x,n.get(x))}catch(P){return J.onException?.(P),new Response("Not found",{status:404})}}let E=await S(X,V);if(V.endsWith(".json"))try{E.headers.set(xJ,l)}catch{}return E}async function a(X){try{return await J.staticFiles?.(X)??{publicFiles:!0,assetRoutes:!1}}catch{return{publicFiles:!1,assetRoutes:!0}}}async function S(X,V){let x=J.fetch.bind(J);try{let O=await x(X);if(O instanceof Response)return O;else{let _=[];return _.push({content:K}),await O({getStyles:async(E,P)=>{let t=E??["404"];if(P?.static)return vJ(t,P.layout);for(let fJ of t){let uJ=Z[`app/views/${fJ}.tsx`];for(let e of uJ?.css??[]){let mJ=Bun.file(`${process.env.DIST_DIR}/client/${e}`);_.push({id:e,content:await mJ.text()})}}return p(_)},clientEntry:L,modulePreloadManifest:z,loaders:I,viewImportMap:j,viewModules:W,ogMap:Y,cssManifest:G,assetBase:H,resolveIsland:M,buildId:l})}}catch(O){return c(O,V,J.onException)}}let yJ=(process.env.GEMI_COMPRESSION??"auto").toLowerCase()!=="off",s=DJ(process.env.GEMI_TRUST_PROXY),gJ=AJ(process.env),q=J.sockets();if(q&&s.kind==="none"&&!gJ)console.warn("[gemi] Broadcast sockets: GEMI_TRUST_PROXY is not set, so a socket's address is its TCP peer. Behind a proxy or load balancer every client shares the proxy's address, and broadcast.maxConnectionsPerIp caps the whole app per process. Set GEMI_TRUST_PROXY (see forwardedFor) or raise that limit.");let f=Bun.serve({maxRequestBodySize:10737418240,fetch:async(X,V)=>{if(PJ(X.headers,V.requestIP(X)?.address??null,s),J.applyTrustedClientIp(X),q?.matches(X))return q.upgrade(X,V);let x=await $(X,(O)=>J.withGlobalMiddleware(O,kJ,(_)=>c(_,new URL(O.url).pathname,J.onException)));return yJ?JJ(X,x):x},idleTimeout:SJ(),port:process.env.PORT||5173,websocket:q?.websocket});return await q?.start(f),RJ({port:f.port,rootDir:g}),f}export{F3 as httpProd};
23
23
 
24
- //# debugId=E90A7CC68CA086FB64756E2164756E21
24
+ //# debugId=F58B82450D28F90164756E2164756E21
@@ -14,6 +14,6 @@
14
14
  "import { stringEraRefusal } from \"../http/Error\";\nimport { isApiPath } from \"../services/router/apiPath\";\n\n// The production server's last resort: an error nothing on the way here turned\n// into a response. Request breakers (auth, 404s, 416s) are answered by the\n// dispatchers before this, so what arrives is a genuine failure — and its\n// message and stack are for the developer, not for whoever triggered it. They\n// can carry absolute paths, dependency versions, SQL fragments and column\n// names. The dev server renders them on purpose (`httpDev.ts`); this does not.\n\nconst GENERIC_500_HTML = `<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Internal Server Error</title>\n <style>\n body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: grid; place-items: center; }\n main { text-align: center; padding: 16px; }\n h1 { font-size: 1.5rem; margin: 0 0 0.5rem; }\n p { margin: 0; opacity: 0.7; }\n </style>\n </head>\n <body>\n <main>\n <h1>Something went wrong</h1>\n <p>Please try again later.</p>\n </main>\n </body>\n</html>`;\n\nexport function unhandledErrorResponse(\n err: unknown,\n pathname: string,\n onException?: (error: Error) => void,\n): Response {\n // `onException` is the report, and the default one `App` installs is a\n // `console.error`, so logging here as well printed every failure twice\n // (three times for `/api`, whose dispatcher logs before rethrowing). Only\n // without a reporter does this log itself.\n //\n // Reported for `/api` too: an app's error tracking should see an API failure\n // that got this far, not only a page one. `onRequestFail` is a different\n // hook (route config, called by the dispatchers), so this is not a second\n // report through the same channel.\n if (!onException) {\n console.error(err);\n } else {\n try {\n // The hook is typed to receive an `Error`; a thrown string or object is\n // wrapped so a reporter reading `.stack` or `.name` gets one.\n onException(err instanceof Error ? err : new Error(String(err), { cause: err }));\n } catch (reportError) {\n // A broken reporter must not turn a 500 into a leaked stack either.\n console.error(err);\n console.error(reportError);\n }\n }\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({ error: stringEraRefusal(\"server_error\", \"Internal Server Error\", 500) }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(GENERIC_500_HTML, {\n status: 500,\n headers: { \"Content-Type\": \"text/html; charset=utf-8\" },\n });\n}\n"
15
15
  ],
16
16
  "mappings": ";qmCAAA,eAAS,UAET,SAAS,OAAM,IAAS,QCgBxB,WAAS,UACT,cAAS,oBAAW,WAAsB,QAW1C,FAAM,HAAuC,LAAC,DAAM,AAAM,JAQpD,HAAyB,DAYzB,HAAiB,JACjB,HAAqB,HAGrB,HAAa,JAEnB,SAAS,EAAW,CAAC,EAAiC,CACpD,GAAI,IAAQ,OACV,MAAO,GAKT,GAAI,CAAC,oBAAoB,KAAK,EAAI,KAAK,CAAC,EACtC,MAAO,GAET,IAAM,EAAQ,OAAO,EAAI,KAAK,CAAC,EAC/B,OAAO,OAAO,SAAS,CAAK,EAAI,KAAK,IAAI,EAAO,CAAC,EAAI,EAahD,SAAS,EAAmB,CAAC,EAA+D,CACjG,GAAI,IAAW,MAAQ,IAAW,OAChC,OAAO,KAGT,IAAM,EAAW,IAAI,IACrB,QAAW,KAAQ,EAAO,MAAM,GAAG,EAAG,CACpC,IAAO,KAAc,GAAU,EAAK,MAAM,GAAG,EACvC,EAAS,EAAU,KAAK,EAAE,YAAY,EAC5C,GAAI,IAAW,GACb,SAGF,IAAI,EAAI,EACR,QAAW,KAAS,EAAQ,CAC1B,IAAM,EAAY,EAAM,QAAQ,GAAG,EACnC,GAAI,IAAc,GAChB,SAEF,GAAI,EAAM,MAAM,EAAG,CAAS,EAAE,KAAK,EAAE,YAAY,IAAM,IAAK,CAC1D,EAAI,GAAY,EAAM,MAAM,EAAY,CAAC,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C7C,EAAuB,EAAK,IAAI,IAAI,EAAI,GAAG,EAAE,SAAU,EAAI,WAAW,CACxE,CACF,EAKA,OAAO,GAAqB,GAAiB,EAAK,CAAG,EAAI,GAE3D,YAAa,GAAkB,EAC/B,KAAM,QAAQ,IAAI,MAAQ,KAC1B,UAAW,GAAS,SACtB,CAAC,EAKD,OAJA,MAAM,GAAS,MAAM,CAAM,EAE3B,GAAmB,CAAE,KAAM,EAAO,KAAM,SAAQ,CAAC,EAE1C",
17
- "debugId": "E90A7CC68CA086FB64756E2164756E21",
17
+ "debugId": "F58B82450D28F90164756E2164756E21",
18
18
  "names": []
19
19
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  class B{app;constructor(z){this.app=z}register(){}boot(){}shutdown(z){}}
3
- export{B as Pe};
3
+ export{B as Qe};
4
4
 
5
- //# debugId=81BDDB875237ADD464756E2164756E21
5
+ //# debugId=4FA2CA8D375E286C64756E2164756E21
@@ -5,6 +5,6 @@
5
5
  "import type { Application } from \"../foundation/Application\";\n\n/**\n * What a provider's `shutdown()` may resolve: nothing, or whether it\n * abandoned work at the deadline. See `ServiceProvider` below.\n */\nexport type ProviderShutdownResult = void | { abandoned: boolean };\n\n/**\n * Every hook defaults to a no-op. `register()` binds services into the\n * container and must not resolve any of them; `boot()` runs after every\n * provider has registered, so it may resolve freely.\n *\n * `shutdown()` runs once when a production server is told to stop (`SIGTERM`\n * or `SIGINT`), after it has stopped accepting requests and the in-flight ones\n * have finished or run out of grace — so nothing a request needs is torn down\n * under it. Providers shut down in reverse registration order, so one\n * registered after another may still use it. Each is awaited, but under a\n * shared deadline (`GEMI_SHUTDOWN_PROVIDER_TIMEOUT`): one that overruns is\n * abandoned and the next begins, and one that throws is logged and does not\n * stop the rest. See `Application.shutdown`.\n *\n * Under `gemi dev` it also runs on every `bun --hot` reload, for the\n * application the reload replaced, once the new one is serving and the old\n * one's requests have finished (see `server/devReload.ts`). A hook that closes\n * something kept on `globalThis` across reloads would close it for the new\n * application too.\n *\n * `timeoutMs` is what is left of that shared deadline when this provider is\n * reached. A provider that waits for something — jobs finishing, a queue\n * draining — should bound its own wait by a little less than this, so that it\n * is still the one to report what it gave up on. Ignoring it is fine; the\n * provider is then simply abandoned at the deadline, with only a generic line\n * from `Application` to say so.\n *\n * A provider that bounds its own wait and gives up on work it was waiting for\n * resolves `{ abandoned: true }`. `Application` then reports it in `timedOut`\n * as if it had overrun, and the process exits `1` — the work was cut off just\n * the same, and an orchestrator or a log alert has to be able to see that from\n * the exit code. The provider names what it abandoned in its own log line.\n */\nexport abstract class ServiceProvider {\n constructor(protected app: Application) {}\n\n register(): void {}\n\n boot(): void | Promise<void> {}\n\n shutdown(options?: {\n timeoutMs: number;\n }): ProviderShutdownResult | Promise<ProviderShutdownResult> {}\n}\n"
6
6
  ],
7
7
  "mappings": ";AAyCO,MAAe,CAAgB,CACd,IAAtB,WAAW,CAAW,EAAkB,CAAlB,WAEtB,QAAQ,EAAS,EAEjB,IAAI,EAAyB,EAE7B,QAAQ,CAAC,EAEoD,EAC/D",
8
- "debugId": "81BDDB875237ADD464756E2164756E21",
8
+ "debugId": "4FA2CA8D375E286C64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -0,0 +1,19 @@
1
+ // @bun
2
+ import{re as M}from"./chunk-7xe5vd4w.js";import{Ie as V,Ne as Q,ye as C}from"./chunk-pnt0c59g.js";import{jm as P}from"./chunk-aes0ecnp.js";import{Em as A,Fm as S,Gm as R}from"./chunk-hmtn7996.js";class j extends Error{code;constructor(z,F=1){super(z);this.code=F;this.name="CommandFailed"}}class Z{static commandName="unset";static description="";static args=[];static options=[];run(z){}}function p(z){return z}function L(){return{commands:[],commandsDir:"app/commands"}}var I=Symbol.for("gemi.console.builder");function k(z){if(z.trim()==="")throw Error("A command name cannot be empty.");if(/[{}]/.test(z)||/\s/.test(z))throw Error(`Invalid command name ${JSON.stringify(z)}. gemi does not parse a signature string; the name is the whole of it. Declare arguments with .arg() and flags with .option():
3
+
4
+ defineCommand("mail:send")
5
+ .arg("user", { required: true })
6
+ .option("queue", { type: "boolean" })
7
+ .handle(async ({ args, options }) => { ... })`)}function c(z){k(z);let F=[],G=[],Y="",J={[I]:z,describe(H){return Y=H,J},arg(H,O={}){if(O.required&&O.default!==void 0)throw Error(`Argument "${H}" of command "${z}" is both required and has a default. An argument that is supplied when absent cannot also be `+"absent \u2014 drop one.");if(O.variadic&&O.default!==void 0)throw Error(`Argument "${H}" of command "${z}" is variadic and has a default. A variadic argument collects the remaining values and is an empty list when there are none, so the default could never `+"apply \u2014 drop it, or drop `variadic`.");let $=F.find((X)=>X.variadic);if($)throw Error(`Argument "${H}" of command "${z}" is declared after the variadic argument "${$.name}", which collects everything that follows, so "${H}" could never receive a value. A variadic argument must be declared last.`);if(F.some((X)=>X.name===H))throw Error(`Command "${z}" declares the argument "${H}" twice.`);return F.push({...O,name:H}),J},option(H,O){if(G.some((K)=>K.name===H))throw Error(`Command "${z}" declares the option "${H}" twice.`);let $="alias"in O?O.alias:void 0,X=$===void 0?void 0:G.find((K)=>("alias"in K)&&K.alias===$);if(X)throw Error(`Options "${X.name}" and "${H}" of command "${z}" both use the alias "-${$}".`);return G.push({...O,name:H}),J},handle(H){let O=z,$=Y,X=class extends Z{static commandName=O;static description=$;static args=[...F];static options=[...G];run(K){return H(K)}};return delete J[I],Object.defineProperty(X,"name",{value:O,configurable:!0}),X}};return J}function T(z){return typeof z==="object"&&z!==null&&typeof z[I]==="string"}function o(z){return z}function B(){return{jobs:[],jobsDir:"app/cron"}}function n(z){return z}function D(){return{listeners:[],listenersDir:"app/listeners"}}class U{static name="unset";static event;queued=!1;maxAttempts=3;backoff=0;worker=!1}class W{static name="unset";run(z,...F){throw Error(`The workflow ${this.constructor.name} has no run method.`)}onCancel(z,...F){return}static start(...z){return P(V).workflows.start(this,z)}static signal(z,F,G){return P(V).workflows.signal(z,F,G)}static items(z,F,G={}){return P(V).workflows.items(z,F,G)}static channel(z){return P(V).workflows.channel(z)}static stream(z,F,G={}){return P(V).workflows.stream(z,F,G)}static cursor(z){return P(V).workflows.cursor(z)}static subscribe(z,F={}){return P(V).workflows.subscribe(z,F)}static find(z){return P(V).workflows.find(z)}static cancel(z){return P(V).workflows.cancel(z)}}import{existsSync as E}from"fs";import{dirname as x,isAbsolute as N,join as y}from"path";function q(z){return N(z)?z:y(R(),z)}function _(z,F,G){if(E(z)||E(x(z)))return;console.warn(`No ${F} were discovered: neither ${z} nor the directory above it exists, so this process cannot see the application's source. If this is a deploy that ships only the build output, list the classes explicitly in app/config/${G}.ts so they travel with it.`)}async function Zz(z=C().jobsDir){let F=q(z);_(F,"queue jobs","queue");let G=await S(F,Q);return w(G),G}async function qz(z=C().workflowsDir){let F=q(z);_(F,"workflows","queue");let G=await S(F,W);for(let Y of G){if(Object.getOwnPropertyDescriptor(Y,"name")?.writable)continue;console.warn(`Workflow ${Y.name} does not declare \`static name\`. A workflow is stored under its name, and a production build renames the class. Add: static name = "${Y.name}";`)}return G}function w(z){for(let F of z){if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;console.warn(`Queued job ${F.name} does not declare \`static name\`, so it is registered under its class name. A production build minifies the class that dispatches it and renames it, while discovery reads this `+"file from source and does not \u2014 so the dispatch would be dropped in "+`production and nowhere else. Add: static name = "${F.name}";`)}}async function _z(z=B().jobsDir){let F=q(z);return _(F,"cron jobs","schedule"),await S(F,M)}async function Iz(z=L().commandsDir){let F=q(z);_(F,"commands","command");let G=[],Y=await S(F,Z,[],(J,H)=>{if(T(J))G.push(H)});return b(G),Y}function b(z){if(z.length===0)return;let F=z.length===1?`${z[0]} exports a command builder that never called \`.handle()\``:`${z.length} files export a command builder that never called \`.handle()\`:
8
+ ${z.join(`
9
+ `)}`;throw new A(`${F}, so there is no command to run. \`.handle()\` is what turns `+`the chain into a command \u2014 finish it:
10
+
11
+ `+` export default defineCommand("my-command")
12
+ .handle(async ({ line }) => { line("hello") })`)}async function Uz(z=D().listenersDir){let F=q(z);_(F,"event listeners","events");let G=await S(F,U);return f(G),v(G),g(G),G}function f(z){let F=z.filter((G)=>!G.event);if(F.length===0)return;throw new A(`${F.map((G)=>G.name).join(", ")} declare no \`static event\`, so there is no event name to register them under and their \`handle\` would never run. Every listener binds to exactly one event:
13
+
14
+ static event = UserRegistered;
15
+
16
+ If this is an abstract base its subclasses extend, move it out of the `+"listeners directory \u2014 the walk excludes gemi's `Listener` and "+"nothing else, so a base sitting beside its subclasses is registered and run like one of them.")}function v(z){for(let F of z){if(Object.getOwnPropertyDescriptor(F,"name")?.writable)continue;console.warn(`Event listener ${F.name} does not declare \`static name\`, so it is registered under its class name, which a production build renames. Nothing reads that name across a build boundary while the `+"listener is sync, which is why this is a warning \u2014 but adding "+`\`queued = true\` to it is refused at boot for the same reason, because the queue's key is that string. Add: static name = "${F.name}";`)}}function g(z){let F=new Set;for(let{event:G}of z){if(F.has(G))continue;if(Object.getOwnPropertyDescriptor(G,"name")?.writable)continue;F.add(G),console.warn(`Event ${G.name} does not declare \`static name\`, so it is dispatched under its class name. A production build minifies the code that dispatches it and renames the class, while discovery reads `+"the listener's copy from source and does not \u2014 so the dispatch would "+`reach no listener in production and nowhere else. Add: static name = "${G.name}";`)}}
17
+ export{j as be,Z as ce,p as de,L as ee,c as fe,o as ge,B as he,n as ie,D as je,U as ke,W as le,Zz as me,qz as ne,_z as oe,Iz as pe,Uz as qe};
18
+
19
+ //# debugId=7B7916FCDCE2B58664756E2164756E21
@@ -8,10 +8,10 @@
8
8
  "import type { CronJob } from \"./CronJob\";\n\n// Config key: `schedule`. Consumed by `ScheduleServiceProvider`.\nexport interface ScheduleConfig {\n /**\n * The `CronJob` subclasses this application runs on a schedule, or nothing.\n *\n * ### Why \"or nothing\" is the point\n *\n * A cron job that is written and not listed here never fires, and unlike a\n * dropped dispatch there is no caller left waiting to notice: nothing is\n * downstream of a tick that did not happen. The report is simply not sent,\n * for as long as it takes somebody to ask why they stopped seeing it. That is\n * the whole failure — the file exists, the expression is right, and the class\n * was never in the module graph.\n *\n * Leaving this out spells the schedule once: the jobs are the classes under\n * `jobsDir`.\n *\n * ### The rule, exactly\n *\n * **Declared wins, and `[]` is declared.** A `jobs` that is present is used\n * verbatim and no directory is read — the escape hatch for an app whose jobs\n * live somewhere this cannot walk, for one that runs a deliberate subset, and\n * for a deploy that ships no source. An empty array means an app with nothing\n * scheduled and says so; it does not mean \"find some\".\n *\n * **Absent or `undefined` discovers.** `undefined` counts as absent for the\n * same reason `withDefaults` treats it that way everywhere else: a key spread\n * in from an optional value is an omission, not an instruction.\n *\n * Either way the set the scheduler ended up with is readable afterwards, as\n * `app(Scheduler).jobs` — an app that used to import this array to assert\n * something about its own schedule asks the scheduler instead.\n */\n jobs?: Array<new () => CronJob>;\n\n /**\n * Where to look when `jobs` was not declared. Relative to the project root,\n * or absolute.\n *\n * Every `.ts`/`.tsx` file underneath it is imported at boot and every exported\n * class extending `CronJob` is scheduled, so this wants to be a directory of\n * cron declarations rather than a directory that merely contains some. Moving\n * the jobs is what this field is for; pointing it at `app/` is not.\n */\n jobsDir?: string;\n}\n\nexport function defineScheduleConfig(config: ScheduleConfig): ScheduleConfig {\n return config;\n}\n\nexport function scheduleConfigDefaults(): Required<ScheduleConfig> {\n return {\n jobs: [],\n jobsDir: \"app/cron\",\n };\n}\n",
9
9
  "import type { ListenerClass } from \"./Listener\";\n\n// Config key: `events`. Derived from `EventServiceProvider`.\nexport interface EventConfig {\n /**\n * The `Listener` subclasses this application registers, or nothing.\n *\n * ### Why \"or nothing\" is the point\n *\n * A dispatch fans out to whatever the `EventManager` holds for the event's\n * name, and an event nothing is registered for is not an error — it is the\n * ordinary state of an application that has not written that listener yet.\n * So this list is a second spelling of `app/listeners`, kept in step by hand,\n * and what the two disagreeing costs is a side effect that stops happening,\n * with a development-only warning as the only trace. Nothing fails, nothing\n * is dropped from a log: the welcome email simply is not sent.\n *\n * Leaving this out spells it once: the listeners are the classes under\n * `listenersDir`.\n *\n * ### The rule, exactly\n *\n * **Declared wins, and `[]` is declared.** A `listeners` that is present is\n * used verbatim and no directory is read — that is the escape hatch for an\n * app whose listeners live somewhere this cannot walk, for one that\n * deliberately registers a subset, and for a deploy that ships no source. An\n * empty array means an app with no listeners and says so; it does not mean\n * \"find some\".\n *\n * **Absent or `undefined` discovers.** `undefined` counts as absent for the\n * same reason `withDefaults` treats it that way everywhere else: a key spread\n * in from an optional value is an omission, not an instruction.\n */\n listeners?: ListenerClass[];\n\n /**\n * Where to look when `listeners` was not declared. Relative to the project\n * root, or absolute.\n *\n * Every `.ts`/`.tsx` file underneath it is imported at boot and every\n * exported class extending `Listener` is registered, so this wants to be a\n * directory of listener declarations rather than a directory that merely\n * contains some. That includes an abstract base a few listeners share: the\n * walk excludes the framework's `Listener` and nothing else, so a base\n * sitting here is registered alongside its subclasses and its `handle` runs\n * on every dispatch of whatever event it declares. Keep shared bases outside\n * this directory.\n *\n * There is no `eventsDir` to go with it. Event classes are never discovered\n * — each is imported by the listener that binds to it and by the code that\n * dispatches it, so nothing needs to walk them and a walk that imported them\n * anyway would only be a boot cost.\n */\n listenersDir?: string;\n}\n\nexport function defineEventConfig(config: EventConfig): EventConfig {\n return config;\n}\n\nexport function eventConfigDefaults(): Required<EventConfig> {\n return {\n listeners: [],\n listenersDir: \"app/listeners\",\n };\n}\n",
10
10
  "import type { Event, EventClass } from \"./Event\";\n\n/**\n * One side effect of one event, in its own file.\n *\n * ```typescript\n * // app/listeners/SendWelcomeEmail.ts\n * export class SendWelcomeEmail extends Listener {\n * static name = \"SendWelcomeEmail\";\n * static event = UserRegistered;\n *\n * async handle(event: UserRegistered) {\n * await Mail.send(event.email, ...);\n * }\n * }\n * ```\n *\n * That is the whole of what the subsystem buys: adding a fourth side effect to\n * a registration is adding a file, rather than editing the controller that\n * already has three.\n *\n * ### Why the binding lives here and not on the event\n *\n * The listener is the thing with an opinion about what it cares about; an event\n * has no business knowing who is watching. An event listing its listeners would\n * also put the property back the way it was — adding a side effect would edit\n * an existing file.\n *\n * ### Why the binding is a value at all\n *\n * Laravel binds a listener to an event by reflecting on the type-hint of\n * `handle(UserRegistered $event)`. TypeScript erases types at runtime, so that\n * mechanism cannot exist here and the binding has to be carried as a value.\n * That constraint turns out to be a favourable one: it is also what makes the\n * payload types flow without a generated registry.\n *\n * ### The seam, written down rather than hidden\n *\n * **Nothing checks that `static event` and the annotation on `handle` agree.**\n * A static and an instance member cannot reference each other's types, so the\n * compiler sees `static event = UserRegistered` and `handle(event: OrderPaid)`\n * as two unrelated declarations. Copy a listener, change the static, forget the\n * annotation, and TypeScript is satisfied while the listener receives something\n * else.\n *\n * It is accepted because the failure is local and immediate — that one listener\n * reads a field that is not there, in its own stack — rather than the\n * misroute-shaped failures the rest of this subsystem is arranged against. The\n * `Listener.test-d.ts` beside this file pins the two halves the compiler *does*\n * enforce, so a later refactor reaching for convenience cannot widen them to\n * `any` unnoticed.\n */\nexport abstract class Listener {\n /**\n * The name this listener is reported and de-duplicated under. Required.\n *\n * Two listener classes claiming one name is refused at registration, and a\n * discovery walk makes that ordinary: `auth/NotifyAdmins.ts` beside\n * `billing/NotifyAdmins.ts` is a natural thing to write, and nothing forces\n * the import alias a hand-written list would have demanded.\n *\n * As on `Event`, the `\"unset\"` default is a floor and not the check — a class\n * declaration always shadows it with its own implicit binding, which is the\n * one a minifier renames. `discoverListeners` reads the property descriptor\n * to tell a declared name from an implicit one.\n *\n * For a **queued** listener it is more than a label: the queue is keyed by\n * name, the listener is registered under `listener:<name>`, and that string\n * is what a queued dispatch carries. So a queued listener whose name is the\n * implicit class binding is refused at registration rather than warned about\n * — the two ends of the queue can be two different module graphs, and a name\n * only one of them minified is a side effect that stops happening in\n * production and reports success.\n */\n static name = \"unset\";\n\n /**\n * The event class this listener handles. Exactly one, required.\n *\n * It holds the **class**, not its name. The name is read off it once, at\n * registration, inside `EventManager.useListeners` — and that read happens in\n * the module graph that declared the class, so the name it yields is the\n * source one. Nothing downstream keeps the class object, because a registry\n * keyed by class identity is wrong in production only.\n *\n * There is no `static events = [A, B]`, deliberately. A listener bound to two\n * events has to discriminate inside `handle`, and the natural way to write\n * that is `if (event instanceof UserRegistered)` — which is `true` in every\n * test and `false` in a production build, for the reason `Event`'s own doc\n * comment gives. Two events wanting the same side effect are two small\n * listeners calling one shared function.\n *\n * Declared as required, and still checked at runtime: every subclass inherits\n * this declaration whether or not it assigns to it, so the compiler cannot\n * see a listener that left it out. `EventManager` refuses one out loud.\n */\n static event: EventClass;\n\n /**\n * Where this listener runs. **A context boundary, not a performance dial.**\n *\n * Left `false`, the listener runs inline, inside the dispatcher's\n * `kernelContext` and `ormContext`: it has the request's `app()`, the\n * authenticated user through `currentActor()`, and it joins the ambient\n * transaction.\n *\n * **Unless the event declares `static afterCommit`.** That flag releases its\n * listeners after the commit and outside the transaction's scope, so a sync\n * listener bound to one runs with `currentTransaction()` undefined and\n * commits on its own. The listener kept sync *because* it writes a row that\n * has to roll back with the write it describes — an audit trail, a ledger\n * entry — starts committing separately the day someone sets that flag in the\n * event's file, and nothing on this side says so: no error, no warning, and\n * a `queued = false` that still reads as \"inside the transaction\".\n *\n * Set `true`, it is handed to the `QueueManager` instead and run from a\n * drain, on the queue's terms. What crosses is the event's name and its\n * constructor arguments as JSON, and nothing else — not the instance the sync\n * listeners share, and not a line of the request. With `worker = true` it is\n * a different thread with a cloned application.\n *\n * The part that catches people is that the context is not reliably *gone*\n * either: the queue is in-process, so a drain that happens to start from\n * `push` is still standing in the dispatcher's context and `app()` there\n * resolves the request's application. Nothing about that is promised. A\n * queued listener that reads the current actor, or writes expecting to join\n * the ambient transaction, works until the day the queue was already busy —\n * and then reads different rows, or commits separately, with no error either\n * way. So: a listener that needs the request's context has to stay sync, and\n * a listener that only needs the payload is free to queue.\n *\n * What it buys, in exchange, is the queue's whole retry path: `maxAttempts`,\n * `onFail`-style re-queueing and dead-lettering, none of which a sync\n * listener has. `dispatchAndWait` does **not** wait for it.\n */\n queued = false;\n\n /**\n * Attempts before the queue gives up, counting the first. `Job`'s field and\n * `Job`'s meaning, because it is forwarded to one.\n *\n * **Ignored unless `queued` is true.** A sync listener has no retry path at\n * all — its throw is logged and the next listener runs — so a `maxAttempts`\n * beside `queued = false` is a line that does nothing, which is why it is\n * said here rather than in a note somewhere else.\n */\n maxAttempts = 3;\n\n /**\n * Milliseconds to wait before each retry: a number for every retry, or an\n * array with one entry per retry, its last repeating. `Job`'s field and\n * `Job`'s meaning, because it is forwarded to one.\n *\n * **Ignored unless `queued` is true**, for the reason `maxAttempts` is.\n */\n backoff: number | number[] = 0;\n\n /**\n * Runs `handle` in a Worker thread with its own cloned application, for a\n * queued listener whose work is CPU-bound. `Job`'s field and `Job`'s\n * meaning, because it is forwarded to one.\n *\n * **Ignored unless `queued` is true.** A sync listener runs on the\n * dispatcher's stack by definition; there is no thread to move it to.\n */\n worker = false;\n\n /**\n * The side effect. Runs inside the dispatcher's context when `queued` is\n * false: a sync listener has the request's `app()`, its authenticated user,\n * and — unless the event declares `static afterCommit` — its ambient\n * transaction. A queued one can rely on none of them — see `queued`.\n *\n * Annotate the parameter with the event named in `static event` — narrowing\n * the base's `Event` here is legal because method parameters are bivariant,\n * which is what lets this class avoid a generic parameter. Nothing checks\n * that the two agree; see the note on the class.\n *\n * Abstract, so a listener that forgets it fails to compile rather than\n * silently handling nothing.\n *\n * A throw is caught, logged with both names, and the next listener still\n * runs. Listeners are independent side effects by construction, and their\n * order is a filesystem walk's — letting one cancel the rest would make that\n * order load-bearing, which is the exact coupling this subsystem exists to\n * remove.\n */\n abstract handle(event: Event): void | Promise<void>;\n}\n\n/**\n * A `Listener` subclass, as the registry and the `events` config slice hold\n * one.\n *\n * Zero-argument, because the manager constructs one per dispatch and has\n * nothing to pass it. The `event` member is typed as present even though\n * `EventManager` checks for it at runtime: an inherited declaration is\n * indistinguishable from an assignment to the type system, so this is the\n * shape, and the runtime check is what covers the difference.\n */\nexport type ListenerClass = (new () => Listener) & {\n name: string;\n event: EventClass;\n};\n",
11
- "import { app } from \"../../../foundation/app\";\nimport { QueueManager } from \"../QueueManager\";\nimport type { EachProblem, EachProgress, Step } from \"./Step\";\nimport type { StepRunStatus, WorkflowRunStatus } from \"./WorkflowStore\";\n\n/** The arguments `start` takes: `run`'s, after `step`. */\nexport type WorkflowArgs<T extends Workflow> = Parameters<T[\"run\"]> extends [\n any,\n ...infer Rest,\n]\n ? Rest\n : never;\n\n/** What `Workflow.find` resolves to. Times are epoch milliseconds. */\nexport type WorkflowStatus = {\n id: string;\n /** The workflow class's `static name`. */\n name: string;\n status: WorkflowRunStatus;\n /** The `run` arguments after `step`. */\n args: unknown[];\n /** The key of the step it is on, or `null`. */\n currentStep: string | null;\n /** 0 to 1, as `step.progress` last set it; 1 once completed. */\n progress: number;\n /** What `run` returned, once completed. */\n result: unknown;\n /** Why it failed; for a cancelled one, why `onCancel` failed. */\n error: string | null;\n /** Every step recorded so far, in the order they were first reached. */\n steps: WorkflowStepStatus[];\n createdAt: number;\n updatedAt: number;\n};\n\nexport type WorkflowStepStatus = {\n key: string;\n status: StepRunStatus;\n /** Attempts started; `step.run` only. */\n attempt: number;\n error: string | null;\n /** The batch a `step.batch` dispatched. */\n batchId: string | null;\n /**\n * 0 to 1: the batch's progress for a `step.batch`, or the share of items\n * that have ended for a `step.each`.\n */\n progress?: number;\n /** How far a `step.each` is. */\n items?: EachProgress;\n /** When a sleep ends, a wait times out, or a retry is due. */\n wakeAt: number | null;\n startedAt: number | null;\n finishedAt: number | null;\n};\n\n/**\n * A durable workflow (#846): a `run` method made of steps, which survives\n * restarts and deploys, sleeps and waits without holding a process, and can\n * be cancelled.\n *\n * ```ts\n * export class ImportSiteWorkflow extends Workflow {\n * static name = \"ImportSiteWorkflow\";\n *\n * async run(step: Step, importId: string) {\n * const pages = await step.run(\"discover\", () => crawl(importId));\n * const chosen = await step.waitFor<string[]>(\"pages-chosen\", { timeout: \"7d\" });\n * await step.run(\"charge\", (ctx) => charge(importId, ctx.idempotencyKey), { attempts: 1 });\n * const builds = await step.batch(\"build\", BuildPageJob,\n * chosen.map((id) => [id, importId] as const), { allowFailures: true });\n * await step.sleep(\"settle\", \"30s\");\n * return step.run(\"report\", () => report(importId, builds.failedJobIds));\n * }\n *\n * async onCancel(step: Step, importId: string) {\n * await step.run(\"refund\", () => refundUnbuilt(importId));\n * }\n * }\n * ```\n *\n * ### How it runs\n *\n * Each pass calls `run` from the top, inside an internal queue job (a\n * *tick*), so leases, heartbeats and crash recovery are the queue's. A step\n * whose result is stored returns it without running; the first one without\n * one runs and its result is stored before the code goes on. A step that\n * cannot finish now (a sleep, a wait, a batch, a retry with a delay) ends the\n * pass, and a later tick picks it up. **Code outside the steps runs again on\n * every pass**, so it must be cheap and give the same answer each time: put\n * anything with a side effect, anything slow and anything random or\n * time-dependent inside `step.run`.\n *\n * Step keys are the identity of a step: unique within the workflow, and the\n * same on every pass. Adding or removing a step between deploys is safe; a\n * renamed step runs again.\n */\nexport class Workflow {\n static name = \"unset\";\n\n /**\n * The workflow's body. Its return value, as JSON, is the workflow's\n * `result`. A throw that escapes it fails the workflow.\n */\n run(_step: Step, ..._args: any[]): unknown {\n throw new Error(`The workflow ${(this.constructor as typeof Workflow).name} has no run method.`);\n }\n\n /**\n * Runs once after `Workflow.cancel`, in place of `run`, with the same\n * arguments: the place to undo what the steps did. Its steps are memoized\n * like `run`'s (use keys of their own), so it may sleep or retry too.\n */\n onCancel(_step: Step, ..._args: any[]): unknown {\n return undefined;\n }\n\n /**\n * Starts a workflow and resolves to its id. The workflow and its first tick\n * are recorded in one atomic write. Inside an ORM transaction it belongs to\n * the transaction, as a dispatch does: recorded with it, or held until it\n * commits and dropped if it rolls back.\n */\n static start<T extends Workflow>(\n this: new () => T,\n ...args: WorkflowArgs<T>\n ): Promise<string> {\n return app(QueueManager).workflows.start(this as unknown as WorkflowClass, args);\n }\n\n /**\n * Delivers `payload` to the workflow's `step.waitFor(key)`, and resolves to\n * whether it was taken: `false` for an unknown or ended workflow, and for a\n * key that was already signalled. A signal that arrives before the workflow\n * reaches its `waitFor` is kept until it does.\n */\n static signal(id: string, key: string, payload?: unknown): Promise<boolean> {\n return app(QueueManager).workflows.signal(id, key, payload);\n }\n\n /**\n * The items of the `step.each` under `key` that failed or were skipped\n * (or only those of `status`), by index, from just after the index\n * `after`, at most `limit` (default 100, at most 1000). Page through them\n * by passing the last index as `after`.\n */\n static items(\n id: string,\n key: string,\n options: { status?: \"failed\" | \"skipped\"; after?: number; limit?: number } = {},\n ): Promise<EachProblem[]> {\n return app(QueueManager).workflows.items(id, key, options);\n }\n\n /** The workflow's status, or `null` for an unknown id. */\n static find(id: string): Promise<WorkflowStatus | null> {\n return app(QueueManager).workflows.find(id);\n }\n\n /**\n * Cancels a workflow that has not ended, and resolves to whether it did.\n * A running `step.batch` is cancelled with it, a running `step.run` is told\n * through `ctx.signal`, and `onCancel` then runs once.\n */\n static cancel(id: string): Promise<boolean> {\n return app(QueueManager).workflows.cancel(id);\n }\n}\n\nexport type WorkflowClass = (new () => Workflow) & { name: string };\n",
11
+ "import { app } from \"../../../foundation/app\";\nimport { QueueManager } from \"../QueueManager\";\nimport type { EachProblem, Step } from \"./Step\";\nimport type { ChangeFeedResponse, StreamOptions } from \"../../change-feed/stream\";\nimport type { WorkflowUpdate } from \"./wire\";\n\n/** The arguments `start` takes: `run`'s, after `step`. */\nexport type WorkflowArgs<T extends Workflow> = Parameters<T[\"run\"]> extends [\n any,\n ...infer Rest,\n]\n ? Rest\n : never;\n\n/** What `Workflow.find` resolves to: the workflow's update, with its arguments and result. */\nexport type WorkflowStatus = WorkflowUpdate & {\n /** The `run` arguments after `step`. */\n args: unknown[];\n /** What `run` returned, once completed. */\n result: unknown;\n};\n\nexport type { WorkflowStepStatus, WorkflowUpdate } from \"./wire\";\n\n/**\n * A durable workflow (#846): a `run` method made of steps, which survives\n * restarts and deploys, sleeps and waits without holding a process, and can\n * be cancelled.\n *\n * ```ts\n * export class ImportSiteWorkflow extends Workflow {\n * static name = \"ImportSiteWorkflow\";\n *\n * async run(step: Step, importId: string) {\n * const pages = await step.run(\"discover\", () => crawl(importId));\n * const chosen = await step.waitFor<string[]>(\"pages-chosen\", { timeout: \"7d\" });\n * await step.run(\"charge\", (ctx) => charge(importId, ctx.idempotencyKey), { attempts: 1 });\n * const builds = await step.batch(\"build\", BuildPageJob,\n * chosen.map((id) => [id, importId] as const), { allowFailures: true });\n * await step.sleep(\"settle\", \"30s\");\n * return step.run(\"report\", () => report(importId, builds.failedJobIds));\n * }\n *\n * async onCancel(step: Step, importId: string) {\n * await step.run(\"refund\", () => refundUnbuilt(importId));\n * }\n * }\n * ```\n *\n * ### How it runs\n *\n * Each pass calls `run` from the top, inside an internal queue job (a\n * *tick*), so leases, heartbeats and crash recovery are the queue's. A step\n * whose result is stored returns it without running; the first one without\n * one runs and its result is stored before the code goes on. A step that\n * cannot finish now (a sleep, a wait, a batch, a retry with a delay) ends the\n * pass, and a later tick picks it up. **Code outside the steps runs again on\n * every pass**, so it must be cheap and give the same answer each time: put\n * anything with a side effect, anything slow and anything random or\n * time-dependent inside `step.run`.\n *\n * Step keys are the identity of a step: unique within the workflow, and the\n * same on every pass. Adding or removing a step between deploys is safe; a\n * renamed step runs again.\n */\nexport class Workflow {\n static name = \"unset\";\n\n /**\n * The workflow's body. Its return value, as JSON, is the workflow's\n * `result`. A throw that escapes it fails the workflow.\n */\n run(_step: Step, ..._args: any[]): unknown {\n throw new Error(`The workflow ${(this.constructor as typeof Workflow).name} has no run method.`);\n }\n\n /**\n * Runs once after `Workflow.cancel`, in place of `run`, with the same\n * arguments: the place to undo what the steps did. Its steps are memoized\n * like `run`'s (use keys of their own), so it may sleep or retry too.\n */\n onCancel(_step: Step, ..._args: any[]): unknown {\n return undefined;\n }\n\n /**\n * Starts a workflow and resolves to its id. The workflow and its first tick\n * are recorded in one atomic write. Inside an ORM transaction it belongs to\n * the transaction, as a dispatch does: recorded with it, or held until it\n * commits and dropped if it rolls back.\n */\n static start<T extends Workflow>(\n this: new () => T,\n ...args: WorkflowArgs<T>\n ): Promise<string> {\n return app(QueueManager).workflows.start(this as unknown as WorkflowClass, args);\n }\n\n /**\n * Delivers `payload` to the workflow's `step.waitFor(key)`, and resolves to\n * whether it was taken: `false` for an unknown or ended workflow, and for a\n * key that was already signalled. A signal that arrives before the workflow\n * reaches its `waitFor` is kept until it does.\n */\n static signal(id: string, key: string, payload?: unknown): Promise<boolean> {\n return app(QueueManager).workflows.signal(id, key, payload);\n }\n\n /**\n * The items of the `step.each` under `key` that failed or were skipped\n * (or only those of `status`), by index, from just after the index\n * `after`, at most `limit` (default 100, at most 1000). Page through them\n * by passing the last index as `after`.\n */\n static items(\n id: string,\n key: string,\n options: { status?: \"failed\" | \"skipped\"; after?: number; limit?: number } = {},\n ): Promise<EachProblem[]> {\n return app(QueueManager).workflows.items(id, key, options);\n }\n\n /** The ChangeFeed channel a workflow's changes are published to: `gemi:workflow:<id>`. */\n static channel(id: string): string {\n return app(QueueManager).workflows.channel(id);\n }\n\n /**\n * An SSE response following workflow `id`, for `useWorkflow`. Each event's\n * `data` is a `WorkflowUpdate`: the status without `args` and `result`.\n * Authorise the read first, as for any route. Resumes from\n * `Last-Event-ID`, or `options.cursor` (`Workflow.cursor(id)`).\n */\n static stream(\n request: { rawRequest: Request } | Request,\n id: string,\n options: StreamOptions = {},\n ): ChangeFeedResponse<WorkflowUpdate> {\n return app(QueueManager).workflows.stream(request, id, options);\n }\n\n /** A cursor at the workflow's channel head, for a view that read it to hand its client. */\n static cursor(id: string): Promise<string> {\n return app(QueueManager).workflows.cursor(id);\n }\n\n /**\n * Follows workflow `id` on the server: yields it as it is now, then each\n * newer update, and ends after the one that ended it.\n */\n static subscribe(\n id: string,\n options: { signal?: AbortSignal } = {},\n ): AsyncGenerator<WorkflowUpdate, void, undefined> {\n return app(QueueManager).workflows.subscribe(id, options);\n }\n\n /** The workflow's status, or `null` for an unknown id. */\n static find(id: string): Promise<WorkflowStatus | null> {\n return app(QueueManager).workflows.find(id);\n }\n\n /**\n * Cancels a workflow that has not ended, and resolves to whether it did.\n * A running `step.batch` is cancelled with it, a running `step.run` is told\n * through `ctx.signal`, and `onCancel` then runs once.\n */\n static cancel(id: string): Promise<boolean> {\n return app(QueueManager).workflows.cancel(id);\n }\n}\n\nexport type WorkflowClass = (new () => Workflow) & { name: string };\n",
12
12
  "import { existsSync } from \"node:fs\";\nimport { dirname, isAbsolute, join } from \"node:path\";\n\nimport {\n discoverClasses,\n DiscoveryError,\n projectRoot,\n} from \"../support/discover\";\nimport { Command, type CommandClass } from \"../console/Command\";\nimport { commandConfigDefaults } from \"../console/config\";\nimport { isUnfinishedBuilder } from \"../console/builder\";\nimport { CronJob } from \"./cron/CronJob\";\nimport { scheduleConfigDefaults } from \"./cron/config\";\nimport { eventConfigDefaults } from \"./events/config\";\nimport type { EventClass } from \"./events/Event\";\nimport { Listener, type ListenerClass } from \"./events/Listener\";\nimport { Job } from \"./queue/Job\";\nimport { queueConfigDefaults } from \"./queue/config\";\nimport { Workflow, type WorkflowClass } from \"./queue/workflow/Workflow\";\n\n/**\n * Reading an application's jobs off the filesystem, for the two subsystems that\n * were asking every app to write its job list twice.\n *\n * Both functions here are the same call to `discoverClasses` with a different\n * base class, which is deliberate: one walk, one set of skip rules, one answer\n * to \"what does this app have\". They are exported from `gemi/services` rather\n * than kept private to the providers because the list stopped being something\n * an app could import — a test that used to walk the exported `jobs` array\n * needs somewhere to ask the same question, and so does a script.\n *\n * What the providers add on top of these is the decision of *whether* to ask,\n * which is the config's to make and not this file's.\n */\n\n/**\n * A directory the app named, resolved the way the app meant it.\n *\n * Relative paths hang off the project root rather than `process.cwd()` at the\n * moment of the call, because a config slice saying `app/jobs` means the app's\n * `app/jobs` and not whatever directory somebody happened to launch a script\n * from. Absolute paths are taken as given, which is what makes these callable\n * from a test that has no project around it.\n */\nfunction resolveDir(dir: string): string {\n return isAbsolute(dir) ? dir : join(projectRoot(), dir);\n}\n\n/**\n * Says something when the directory is missing *and so is the tree it lives in*.\n *\n * A missing directory has two readings and they want opposite responses. An app\n * that has never written a cron job has no `app/cron`, and warning about that on\n * every boot for the rest of its life is noise — the answer \"you have no cron\n * jobs\" is correct and uninteresting. But a deploy that ships `dist/` and\n * `node_modules/` without the source has no `app/cron` *and no `app/`*, and\n * there discovery quietly returns nothing while the app very much does have\n * jobs: the exact silence #322 and #323 exist to remove, reintroduced one layer\n * down and in production only.\n *\n * The parent directory is what tells them apart. If neither the directory nor\n * the one above it is there, the tree this was pointed into is not there\n * either, and that is worth a sentence.\n */\nfunction warnIfSourceIsMissing(\n resolved: string,\n subject: string,\n slice: string,\n) {\n if (existsSync(resolved) || existsSync(dirname(resolved))) return;\n\n console.warn(\n `No ${subject} were discovered: neither ${resolved} nor the directory ` +\n `above it exists, so this process cannot see the application's source. ` +\n `If this is a deploy that ships only the build output, list the classes ` +\n `explicitly in app/config/${slice}.ts so they travel with it.`,\n );\n}\n\n/**\n * The `Job` subclasses under `dir`, defaulting to the config slice's `app/jobs`.\n *\n * This is what a `queue` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array:\n * every job this application would register, in the order it would register\n * them.\n *\n * Every file underneath is imported, so calling this runs the app's job modules\n * — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverJobs(\n dir: string = queueConfigDefaults().jobsDir,\n): Promise<Array<new () => Job>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"queue jobs\", \"queue\");\n const jobs = await discoverClasses(resolved, Job);\n warnIfNameWillNotSurviveTheBuild(jobs);\n return jobs;\n}\n\n/**\n * The `Workflow` subclasses under `dir`, defaulting to the queue slice's\n * `app/workflows`: what a `queue` slice with no `workflows` key resolves to.\n * A missing directory is no workflows, said nothing about unless the tree\n * above it is missing too.\n */\nexport async function discoverWorkflows(\n dir: string = queueConfigDefaults().workflowsDir,\n): Promise<WorkflowClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"workflows\", \"queue\");\n const workflows = (await discoverClasses(resolved, Workflow)) as WorkflowClass[];\n for (const workflow of workflows) {\n if (Object.getOwnPropertyDescriptor(workflow, \"name\")?.writable) continue;\n console.warn(\n `Workflow ${workflow.name} does not declare \\`static name\\`. A workflow ` +\n `is stored under its name, and a production build renames the class. ` +\n `Add: static name = \"${workflow.name}\";`,\n );\n }\n return workflows;\n}\n\n/**\n * Says something about a discovered job that never declared `static name`.\n *\n * This is the one hazard discovery introduces rather than removes, and it is\n * production-only. `gemi build` minifies the server entry, and app code\n * reachable from it — a controller, and every job class that controller\n * imports to dispatch — is bundled and minified with it. Minification renames\n * the class binding, and a class's implicit `.name` is that binding: a\n * `TestJob` in the bundle reports `\"D\"`. Discovery, meanwhile, imports\n * `app/jobs/TestJob.ts` from source at runtime, where it is still `\"TestJob\"`.\n * The queue is keyed by that name, so the two halves stop agreeing and the\n * dispatch is dropped — in production, and only there.\n *\n * A declared `static name = \"TestJob\"` is a string literal, which survives\n * minification intact, and the two halves agree again. `docs/jobs-and-queues.md`\n * has always called it required; before discovery an app could get away without\n * it, because the explicit `jobs` array was bundled too and both sides were\n * wrong in the same way.\n *\n * The check is exact rather than a guess: a `static name = \"...\"` class field\n * defines a *writable* own property, while the implicit class name is\n * non-writable. Cron is unaffected — `CronJob.name` is an instance field\n * holding a string literal, not the class binding.\n */\nfunction warnIfNameWillNotSurviveTheBuild(jobs: Array<new () => Job>) {\n for (const job of jobs) {\n if (Object.getOwnPropertyDescriptor(job, \"name\")?.writable) continue;\n\n console.warn(\n `Queued job ${job.name} does not declare \\`static name\\`, so it is ` +\n `registered under its class name. A production build minifies the ` +\n `class that dispatches it and renames it, while discovery reads this ` +\n `file from source and does not — so the dispatch would be dropped in ` +\n `production and nowhere else. Add: static name = \"${job.name}\";`,\n );\n }\n}\n\n/**\n * The `CronJob` subclasses under `dir`, defaulting to the config slice's\n * `app/cron`.\n *\n * This is what a `schedule` config slice with no `jobs` key resolves to. Call it\n * directly to ask the question a test used to answer by importing the array —\n * though after boot `app(Scheduler).jobs` is the better one, because it is what\n * the scheduler actually took rather than what this would find if asked again.\n *\n * Every file underneath is imported, so calling this runs the app's cron\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCronJobs(\n dir: string = scheduleConfigDefaults().jobsDir,\n): Promise<Array<new () => CronJob>> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"cron jobs\", \"schedule\");\n return await discoverClasses(resolved, CronJob);\n}\n\n/**\n * The `Command` subclasses under `dir`, defaulting to the config slice's\n * `app/commands`.\n *\n * This is what a `commands`-less `command` slice resolves to, and what\n * `gemi run` lists. Unlike the two above it is not called during boot — a\n * command registry has one consumer, and importing every file under\n * `app/commands` into every server process would be a cost paid on every start\n * for code no request reaches.\n *\n * Every file underneath is imported, so calling this runs the app's command\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n */\nexport async function discoverCommands(\n dir: string = commandConfigDefaults().commandsDir,\n): Promise<CommandClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"commands\", \"command\");\n\n const unfinished: string[] = [];\n\n const commands = await discoverClasses(\n resolved,\n Command,\n [],\n (value, file) => {\n if (isUnfinishedBuilder(value)) unfinished.push(file);\n },\n );\n\n refuseUnfinishedBuilders(unfinished);\n\n return commands as CommandClass[];\n}\n\n/**\n * Stops the walk for a builder chain that was never finished.\n *\n * This is the one silence the builder introduces, and it is the exact shape\n * #322 and #323 exist to remove. `defineCommand(...).arg(...)` without a\n * trailing `.handle(...)` is a plain object rather than a class, so\n * `discoverClasses` discards it along with every constant and helper a command\n * file happens to export — and the command disappears from `gemi run` with\n * nothing raised. The author sees a listing containing every command except the\n * one they just wrote.\n *\n * A throw rather than a warning, because there is no reading of an unfinished\n * builder under which the author meant it: the chain builds a description of a\n * command and then discards it.\n *\n * \"Unfinished\" is decided by `.handle()` clearing the brand, not by the export\n * still being a builder object. Those differ for the natural way to share\n * declarations —\n *\n * export const base = defineCommand(\"reindex\").option(\"verbose\", …);\n * export default base.handle(async () => {});\n *\n * — where `base` is a builder that *did* produce a command. Keying off the shape\n * alone made that file abort the whole of `gemi run`, taking every other command\n * in the project down with it, under a message that was untrue for it.\n */\nfunction refuseUnfinishedBuilders(files: string[]): void {\n if (files.length === 0) return;\n\n const subject =\n files.length === 1\n ? `${files[0]} exports a command builder that never called \\`.handle()\\``\n : `${files.length} files export a command builder that never called ` +\n `\\`.handle()\\`:\\n ${files.join(\"\\n \")}`;\n\n throw new DiscoveryError(\n `${subject}, so there is no command to run. \\`.handle()\\` is what turns ` +\n `the chain into a command — finish it:\\n\\n` +\n ` export default defineCommand(\"my-command\")\\n` +\n ` .handle(async ({ line }) => { line(\"hello\") })`,\n );\n}\n\n/**\n * The `Listener` subclasses under `dir`, defaulting to the config slice's\n * `app/listeners`.\n *\n * This is what an `events` config slice with no `listeners` key resolves to.\n * Call it directly to ask what an application would register: every listener,\n * in the order it would register them.\n *\n * Only listeners are walked. Event classes are never discovered — each is\n * imported by the listener that binds to it and by the code that dispatches it,\n * so there is nothing a walk over them would find that is not already in the\n * module graph.\n *\n * **Known residual, matching jobs and cron.** `discoverClasses` excludes the\n * `base` it is handed and not intermediates, so an abstract listener base\n * written in `listenersDir` and extended by its siblings is discovered and\n * registered alongside them — constructed, with its `handle` called, on every\n * dispatch of whatever event it declares. Keep shared bases outside the\n * directory.\n *\n * Every file underneath is imported, so calling this runs the app's listener\n * modules — the cost `discoverClasses` documents at length, paid once per call.\n *\n * @throws DiscoveryError if a discovered listener declares no `static event`.\n */\nexport async function discoverListeners(\n dir: string = eventConfigDefaults().listenersDir,\n): Promise<ListenerClass[]> {\n const resolved = resolveDir(dir);\n warnIfSourceIsMissing(resolved, \"event listeners\", \"events\");\n\n const listeners = (await discoverClasses(\n resolved,\n Listener,\n )) as ListenerClass[];\n\n refuseListenersWithNoEvent(listeners);\n warnIfListenerNameWillNotSurviveTheBuild(listeners);\n warnIfEventNameWillNotSurviveTheBuild(listeners);\n\n return listeners;\n}\n\n/**\n * Stops the walk for a listener that binds to nothing.\n *\n * `static event` is declared as required on the base and the compiler still\n * cannot see it missing: every subclass inherits the declaration whether or not\n * it assigns to one, so `typeof SomeListener` type-checks either way. What the\n * author gets instead is a file that is imported, registered under no name, and\n * never called — the silence this whole module is arranged against.\n *\n * A throw rather than a warning, because there is no reading of a listener with\n * no event under which the author meant it. The usual cause is the residual\n * above: an abstract base sharing a gate between two listeners, sitting in\n * `listenersDir` where the walk finds it. Moving it out is the fix, and the\n * message says so — the alternative, excluding it by some guess about\n * abstractness, is how a discovery pass ends up quietly covering less than the\n * directory holds.\n */\nfunction refuseListenersWithNoEvent(listeners: ListenerClass[]): void {\n const orphans = listeners.filter((listener) => !listener.event);\n if (orphans.length === 0) return;\n\n throw new DiscoveryError(\n `${orphans\n .map((listener) => listener.name)\n .join(\", \")} declare no \\`static event\\`, so there is no event name to ` +\n `register them under and their \\`handle\\` would never run. Every ` +\n `listener binds to exactly one event:\\n\\n` +\n ` static event = UserRegistered;\\n\\n` +\n `If this is an abstract base its subclasses extend, move it out of the ` +\n `listeners directory — the walk excludes gemi's \\`Listener\\` and ` +\n `nothing else, so a base sitting beside its subclasses is registered ` +\n `and run like one of them.`,\n );\n}\n\n/**\n * Says something about a discovered listener that never declared `static name`.\n *\n * The hazard is `warnIfNameWillNotSurviveTheBuild`'s, one subsystem over: a\n * `static name = \"...\"` class field defines a *writable* own property while the\n * implicit class binding does not, and a minifier renames the binding while\n * leaving the string literal alone. The two spellings are indistinguishable by\n * value — both read `\"SendWelcomeEmail\"` in development — so the descriptor is\n * the only thing that tells them apart, and the difference only becomes visible\n * in a production build.\n *\n * A warning rather than a refusal, because a *sync* listener's name has no\n * second half to disagree with: every reader of it comes from this same\n * source-side walk, so a minified build and this walk cannot produce two\n * different strings for it. A **queued** listener does have one — the name is\n * the queue's key and it crosses a JSON boundary — and that case is refused\n * outright, by `jobForListener`, at the point the listener is registered with\n * the queue rather than here. This walk cannot tell the two apart without\n * constructing every listener it found; the registry constructs them anyway.\n */\nfunction warnIfListenerNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n for (const listener of listeners) {\n if (Object.getOwnPropertyDescriptor(listener, \"name\")?.writable) continue;\n\n console.warn(\n `Event listener ${listener.name} does not declare \\`static name\\`, so ` +\n `it is registered under its class name, which a production build ` +\n `renames. Nothing reads that name across a build boundary while the ` +\n `listener is sync, which is why this is a warning — but adding ` +\n `\\`queued = true\\` to it is refused at boot for the same reason, ` +\n `because the queue's key is that string. Add: static name = ` +\n `\"${listener.name}\";`,\n );\n }\n}\n\n/**\n * Says something about the *event* a discovered listener binds to, when that\n * event's name is the implicit class binding.\n *\n * This is the check that matters from the first dispatch, and it is the reason\n * `discoverListeners` reads `static event` at all. The registry is keyed by the\n * event's name; the dispatcher supplies that name from the class it constructs.\n * A production build minifies the server entry and the app code reachable from\n * it — the controller, and the event class it imports in order to dispatch —\n * while discovery imports `app/listeners/*.ts` from source, and those files\n * import `app/events/*.ts` from source too. Two module graphs, two class\n * objects, and an implicit `.name` that reads `\"UserRegistered\"` on one side\n * and `\"D\"` on the other. The dispatch then finds no listeners, which is legal,\n * normal, and completely silent.\n *\n * A declared `static name` is a string literal, which survives minification\n * intact, and the two halves agree again.\n *\n * Checked through the descriptor rather than the string, and not by comparing\n * `event.name` to anything: in development the two spellings produce the same\n * value, so a check on the string would be a tautology that passes forever.\n */\nfunction warnIfEventNameWillNotSurviveTheBuild(listeners: ListenerClass[]) {\n const warned = new Set<EventClass>();\n\n for (const { event } of listeners) {\n if (warned.has(event)) continue;\n if (Object.getOwnPropertyDescriptor(event, \"name\")?.writable) continue;\n warned.add(event);\n\n console.warn(\n `Event ${event.name} does not declare \\`static name\\`, so it is ` +\n `dispatched under its class name. A production build minifies the ` +\n `code that dispatches it and renames the class, while discovery reads ` +\n `the listener's copy from source and does not — so the dispatch would ` +\n `reach no listener in production and nowhere else. Add: ` +\n `static name = \"${event.name}\";`,\n );\n }\n}\n"
13
13
  ],
14
- "mappings": ";sNA4GO,AAAM,IAAsB,DAAM,CAG5B,KAFX,WAAW,CACT,EACS,EAAe,EACxB,CACA,MAAM,CAAO,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,QAAW,KAAY,EAAW,CAChC,GAAI,OAAO,yBAAyB,EAAU,MAAM,GAAG,SAAU,SAEjE,QAAQ,KACN,kBAAkB,EAAS,gLAGzB,sEACA,+HAEI,EAAS,QACjB,GA0BJ,SAAS,CAAqC,CAAC,EAA4B,CACzE,IAAM,EAAS,IAAI,IAEnB,QAAa,WAAW,EAAW,CACjC,GAAI,EAAO,IAAI,CAAK,EAAG,SACvB,GAAI,OAAO,yBAAyB,EAAO,MAAM,GAAG,SAAU,SAC9D,EAAO,IAAI,CAAK,EAEhB,QAAQ,KACN,SAAS,EAAM,yLAGb,6EACA,yEACkB,EAAM,QAC5B",
15
+ "debugId": "7B7916FCDCE2B58664756E2164756E21",
16
16
  "names": []
17
17
  }
@@ -0,0 +1,39 @@
1
+ // @bun
2
+ import{al as m}from"./chunk-yxtfg4wy.js";import{cl as H,dl as C,hl as A,jl as E}from"./chunk-xyv3y476.js";import{Ll as g}from"./chunk-qa528feb.js";import{sm as k}from"./chunk-q0d45r2j.js";import{Om as l}from"./chunk-yedb5vvg.js";class V extends Error{lock;token;constructor(J,Y,Z="its lease ran out or another holder took it"){super(`Lost the lock "${J}" (token ${Y}): ${Z}.`);this.lock=J;this.token=Y;this.name="LockLostError"}}var d=60000,h=100,c=(J)=>new Promise((Y)=>setTimeout(Y,J));class T{store;name;owner;token;ttl;lost;controller=new AbortController;deadline;expiryTimer;renewTimer;done=!1;constructor(J,Y,Z,$,j,W){this.store=J;this.name=Y;this.owner=Z;this.token=$;this.ttl=j;this.lost=this.controller.signal,this.deadline=W+j,this.armExpiry()}get expired(){return this.lost.aborted||performance.now()>=this.deadline}async extend(J=this.ttl){if(this.lost.aborted)return!1;let Y=performance.now();if(!await this.store.extend(this.name,this.owner,this.token,J))return this.markLost(),!1;if(this.done)return!0;return this.deadline=Math.max(this.deadline,Y+J),this.armExpiry(),!0}async isHeld(){if(this.lost.aborted)return!1;let J=await this.store.held(this.name,this.owner,this.token);if(!J)this.markLost();return J}async fence(J){if(this.lost.aborted)throw new V(this.name,this.token);try{return await this.store.fence(this.name,this.owner,this.token,J)}catch(Y){if(Y instanceof V)this.markLost();throw Y}}async release(){if(this.stop(),this.lost.aborted)return!1;return this.store.release(this.name,this.owner,this.token)}startRenewing(){if(this.renewTimer||this.done)return;this.renewTimer=setInterval(()=>{this.extend().catch((J)=>{console.error(`[gemi] Could not renew the lock "${this.name}".`,J)})},Math.max(1,Math.floor(this.ttl/3))),this.renewTimer.unref?.()}markLost(J){if(this.stop(),!this.lost.aborted)this.controller.abort(new V(this.name,this.token,J))}stop(){this.done=!0,clearInterval(this.renewTimer),clearTimeout(this.expiryTimer),this.renewTimer=void 0,this.expiryTimer=void 0}armExpiry(){clearTimeout(this.expiryTimer),this.expiryTimer=setTimeout(()=>this.markLost("its lease ran out before it was renewed"),Math.max(0,this.deadline-performance.now())),this.expiryTimer.unref?.()}}class i{store;static token="locks";constructor(J){this.store=J}async acquire(J,Y={}){let Z=Y.ttl??d;if(!(Z>0))throw Error(`A lock's ttl must be a positive number of milliseconds; got ${Z}.`);let $=Bun.randomUUIDv7(),j=performance.now()+Math.max(0,Y.wait??0);for(;;){let W=performance.now(),z=await this.store.acquire(J,$,Z);if(z!==null){let X=new T(this.store,J,$,z,Z,W);if(Y.renew)X.startRenewing();return X}let G=j-performance.now();if(G<=0)return null;await c(Math.min(h,G))}}async run(J,Y,Z){let $=await this.acquire(J,{...Y,renew:Y.renew??!0});if(!$)return{acquired:!1};let j;try{j=await Z($)}catch(W){throw await $.release().catch(()=>{}),W}if($.expired)throw $.markLost(),$.lost.reason;return await $.release(),{acquired:!0,value:j}}}function VJ(J){return J}function S(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function O(J){let Y=new URLSearchParams;for(let[Z,$]of J)Y.append(Z,String($));return Y.toString()}function R(J){let Y=new Map;if(!J)return Y;let Z;try{Z=new URLSearchParams(J)}catch{return Y}for(let[$,j]of Z){let W=Number(j);if(j!==""&&Number.isSafeInteger(W)&&W>=0)Y.set($,W)}return Y}var{SQL:s}=globalThis.Bun;function t(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var o=async(J)=>{let Y=new s(J,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(Z,$,j)=>Y.listen(Z,$,j),close:()=>Y.close({timeout:1})}},a=async(J)=>{let Y;try{Y=(await import("./chunk-h6knw9f0.js")).default}catch($){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:$})}let Z=Y(J,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:($,j,W)=>Z.listen($,j,W),close:()=>Z.end({timeout:1}).catch(()=>{})}},y=(J)=>t()?o(J):a(J);var r=/^[A-Za-z_][A-Za-z0-9_]*$/;class x{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor(J,Y={}){if(J.dialect!=="postgres"&&J.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${J.dialect}.`);let Z=Y.headsTable??"gemi_change_heads",$=Y.entriesTable??"gemi_changes",j=Y.notifyChannel??"gemi_changes";for(let z of[Z,$,j])if(!r.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let W=Y.retain??1000;if(!Number.isInteger(W)||W<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${W}.`);this.headsTable=Z,this.entriesTable=$,this.notifyChannel=j,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name,this.url=J.url,this.retain=W,this.listener=Y.listener??y}async createTable(){for(let J of n(this.headsTable,this.entriesTable))await this.sql.unsafe(J)}joinsTransaction(){return this.transaction()!==void 0}publish(J,Y){let Z=this.transaction();if(!Z){let j=()=>this.sql.begin((z)=>this.append(z,J,Y));if(this.dialect!=="sqlite")return j();let W=this.sqliteTurn.then(j);return this.sqliteTurn=W.catch(()=>{}),W}let $=this.append(Z,J,Y);return E($),$}async append(J,Y,Z){let $=J.unsafe(`"${this.headsTable}"`),j=J.unsafe(`"${this.entriesTable}"`),[W]=await J`
3
+ INSERT INTO ${$} (channel, seq) VALUES (${Y}, 1)
4
+ ON CONFLICT (channel) DO UPDATE SET seq = ${$}.seq + 1
5
+ RETURNING seq
6
+ `,z=Number(W.seq);if(await J`
7
+ INSERT INTO ${j} (channel, seq, data, created_at)
8
+ VALUES (${Y}, ${z}, ${JSON.stringify(Z??null)}, ${Date.now()})
9
+ `,z>this.retain)await J`DELETE FROM ${j} WHERE channel = ${Y} AND seq <= ${z-this.retain}`;if(this.dialect==="postgres")await J`SELECT pg_notify(${this.notifyChannel}, ${`${z} ${Y}`})`;return z}async heads(J){let Y=new Map(J.map((j)=>[j,0]));if(J.length===0)return Y;let Z=this.transaction()??this.sql,$=await Z`
10
+ SELECT channel, seq FROM ${Z.unsafe(`"${this.headsTable}"`)}
11
+ WHERE channel IN ${Z([...J])}
12
+ `;for(let j of $)Y.set(j.channel,Number(j.seq));return Y}async read(J,Y,Z){let $=this.sql,[j]=await $`
13
+ SELECT seq FROM ${$.unsafe(`"${this.headsTable}"`)} WHERE channel = ${J}
14
+ `,W=j?Number(j.seq):0;if(Y>W)return{entries:[],head:W,gap:!0};if(Y===W)return{entries:[],head:W,gap:!1};let z=await $`
15
+ SELECT seq, data FROM ${$.unsafe(`"${this.entriesTable}"`)}
16
+ WHERE channel = ${J} AND seq > ${Y}
17
+ ORDER BY seq
18
+ LIMIT ${Z}
19
+ `;if(z.length===0||Number(z[0].seq)!==Y+1)return{entries:[],head:W,gap:!0};return{entries:z.map((G)=>({seq:Number(G.seq),data:JSON.parse(G.data)})),head:W,gap:!1}}async listen(J,Y){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let Z=await this.listener(this.url);try{await Z.listen(this.notifyChannel,($)=>{let j=$.indexOf(" "),W=Number($.slice(0,j));if(j>0&&Number.isInteger(W))J($.slice(j+1),W)},Y)}catch($){throw await Z.close(),$}return{close:()=>Z.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let J=H();if(J===void 0||C()!==this.connection)return;return J}}function n(J,Y){return[`CREATE TABLE IF NOT EXISTS "${J}" (
20
+ "channel" TEXT NOT NULL PRIMARY KEY,
21
+ "seq" BIGINT NOT NULL
22
+ )`,`CREATE TABLE IF NOT EXISTS "${Y}" (
23
+ "channel" TEXT NOT NULL,
24
+ "seq" BIGINT NOT NULL,
25
+ "data" TEXT NOT NULL,
26
+ "created_at" BIGINT NOT NULL,
27
+ PRIMARY KEY ("channel", "seq")
28
+ )`]}class I{logs=new Map;retain;constructor(J={}){let Y=J.retain??1000;if(!Number.isInteger(Y)||Y<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Y}.`);this.retain=Y}async publish(J,Y){let Z=this.logs.get(J);if(!Z)Z={head:0,entries:[]},this.logs.set(J,Z);let $=++Z.head;if(Z.entries.push({seq:$,data:Y===void 0?null:structuredClone(Y)}),Z.entries.length>this.retain)Z.entries.splice(0,Z.entries.length-this.retain);return $}async heads(J){return new Map(J.map((Y)=>[Y,this.logs.get(Y)?.head??0]))}async read(J,Y,Z){let $=this.logs.get(J),j=$?.head??0;if(Y>j)return{entries:[],head:j,gap:!0};if(!$||Y===j)return{entries:[],head:j,gap:!1};let W=$.entries[0]?.seq??j+1;if(W>Y+1)return{entries:[],head:j,gap:!0};let z=Y+1-W;return{entries:$.entries.slice(z,z+Z),head:j,gap:!1}}}var M=new TextEncoder;function L(J){return`id: ${J.seq}
29
+ data: ${JSON.stringify(J.event)}
30
+
31
+ `}var e=5000,N=`: keepalive
32
+
33
+ `;function JJ(J,Y=e){let Z=null,$=!1,j=()=>{if($)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,$)return;try{J.enqueue(M.encode(N))}catch{W();return}j()},Y)},W=()=>{if($=!0,Z!==null)clearTimeout(Z);Z=null};return j(),{touch:j,stop:W}}function _(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function MJ(J,Y=200){let Z=J[Symbol.asyncIterator](),$=-1,j,W=new ReadableStream({start(z){j=JJ(z)},async pull(z){try{let G=await Z.next();if(G.done){j.stop(),z.close();return}$=G.value.seq,z.enqueue(M.encode(L(G.value))),j.touch()}catch(G){let X={type:"error",error:ZJ(G)};j.stop(),z.enqueue(M.encode(L({seq:$+1,event:X}))),z.close()}},cancel(z){j.stop(),Z.return?.(z)}});return new Response(W,{status:Y,headers:_()})}var YJ=new Set(["frame_cursor_evicted","live_run_not_found"]);function ZJ(J){let Y=J&&typeof J==="object"?J.code:void 0;if(J instanceof Error&&typeof Y==="string"&&YJ.has(Y))return{code:"unknown",message:J.message,retryable:!1};return console.error("[gemi/ai] agent stream failed",J),{code:"unknown",message:"The run's stream failed.",retryable:!1}}var w=new TextEncoder;function b(J,Y){return w.encode(`id: ${J}
34
+ data: ${JSON.stringify(Y)}
35
+
36
+ `)}function v(J,Y,Z,$){let j=Y instanceof Request?Y:Y.rawRequest,W=$.cursor??j.headers.get("Last-Event-ID")??new URL(j.url).searchParams.get("cursor"),z;try{z=J.subscribe(Z,{cursor:W,signal:j.signal})}catch(Q){if(!(Q instanceof P))throw Q;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String($.retryAfter??5)}})}let G=null,X=!1,U=!1,B=(Q)=>{if(G)clearInterval(G);if(G=null,z.close(),U)return;U=!0;try{Q.close()}catch{}},p=new ReadableStream({start(Q){G=setInterval(()=>{if(k())return B(Q);try{Q.enqueue(w.encode(N))}catch{B(Q)}},J.config.keepaliveInterval)},async pull(Q){try{if(!X){if(await z.ready(),X=!0,!U)Q.enqueue(b(z.cursor,{type:"ready"}));return}let K=await z.next();if(K.done||U)return B(Q);Q.enqueue(b(z.cursor,K.value))}catch(K){if(!U)console.error("[gemi] A change feed stream failed.",K);B(Q)}},cancel(){if(U=!0,G)clearInterval(G);G=null,z.close()}});return new Response(p,{headers:_()})}var q=255,f=500,$J=30000;class P extends Error{limit;constructor(J){super(`The change feed holds its limit of ${J} subscriptions.`);this.limit=J;this.name="ChangeFeedFullError"}}class jJ{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=f;pollTimer=null;polling=null;constructor(J={},Y={}){this.options=Y;this.config=m(S(),J),this.driver=zJ(this.config.driver,Y.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish(J,Y){F(J);let Z=Y===void 0?null:Y;if(H()!==void 0&&!this.driver.joinsTransaction?.())return A(async()=>{this.wake(J,await this.driver.publish(J,Z))}),null;let $=await this.driver.publish(J,Z);return A(()=>this.wake(J,$)),$}async head(J){return F(J),(await this.driver.heads([J])).get(J)??0}async cursor(J){let Y=D(J);return O(await this.driver.heads(Y))}subscribe(J,Y={}){let Z=D(J);if(this.all.size>=this.config.maxSubscriptions)throw new P(this.config.maxSubscriptions);let $=new u(this,Z,WJ(Y.cursor),this.config,Y.signal);this.all.add($);for(let j of Z){let W=this.followers.get(j);if(!W)this.followers.set(j,W=new Set);W.add($)}return this.startListening(),this.startPolling(),$}stream(J,Y,Z={}){return v(this,J,D(Y),Z)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Y of this.all)Y.close();let J=this.listening;this.listening=null,await J?.close(),await this.driver.close?.()}forget(J){if(!this.all.delete(J))return;for(let Y of J.channels){let Z=this.followers.get(Y);if(Z?.delete(J),Z?.size===0)this.followers.delete(Y)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let J=[...this.followers.keys()];for(let Y=0;Y<J.length;Y+=500){let Z=await this.driver.heads(J.slice(Y,Y+500));for(let[$,j]of Z)this.wake($,j)}}catch(J){console.error("[gemi] The change feed could not read its channels' heads.",J)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake(J,Y){for(let Z of this.followers.get(J)??[])Z.moved(J,Y)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let J=await this.driver.listen((Y,Z)=>this.wake(Y,Z),()=>this.resync());if(this.listenState!=="connecting"){await J.close();return}this.listening=J,this.listenState="listening",this.backoffMs=f,this.resync()}catch(J){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,J),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,$J)}}}class u{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor(J,Y,Z,$,j){this.manager=J;this.config=$;this.signal=j;this.channels=Y;for(let W of Y){let z=Z.get(W);if(z!==void 0)this.positions.set(W,z),this.readTo.set(W,z),this.dirty.add(W)}if(j?.aborted)this.close();else j?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return O(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let J=this.channels.filter((Z)=>!this.positions.has(Z));if(J.length===0)return;let Y=await this.manager.driver.heads(J);for(let Z of J){let $=Y.get(Z)??0;this.positions.set(Z,$),this.readTo.set(Z,$)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let J=this.pending.shift();if(J)return this.positions.set(J.channel,J.seq),{done:!1,value:J};let Y=this.dirty.values().next().value;if(Y!==void 0){await this.read(Y);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved(J,Y){let Z=this.readTo.get(J);if(Z!==void 0&&Y===Z)return;this.dirty.add(J),this.wake()}async read(J){let Y=this.readTo.get(J)??0;this.dirty.delete(J);let{batchSize:Z}=this.config,{entries:$,head:j,gap:W}=await this.manager.driver.read(J,Y,Z);if(this.closed)return;if(W){this.readTo.set(J,j),this.pending.push({type:"reset",channel:J,seq:j});return}for(let z of $)this.readTo.set(J,z.seq),this.pending.push({type:"change",channel:J,seq:z.seq,data:z.data});if($.length===Z)this.dirty.add(J)}idle(){return new Promise((J)=>{this.wakeUp=J})}wake(){let J=this.wakeUp;this.wakeUp=null,J?.()}}function F(J){if(typeof J!=="string"||J===""||J.length>q)throw Error(`A change feed channel is a string of 1 to ${q} characters; got ${JSON.stringify(J)}.`)}function D(J){let Y=[...new Set(typeof J==="string"?[J]:J)];if(Y.length===0)throw Error("A change feed subscription needs at least one channel.");for(let Z of Y)F(Z);return Y}function WJ(J){if(J===void 0||J===null)return new Map;if(typeof J==="string")return R(J);let Y=J instanceof Map?[...J]:Object.entries(J);return R(O(new Map(Y)))}function zJ(J,Y){if(J==="memory")return new I;if(J==="database"||typeof J==="function"){if(!Y&&(J==="database"||J.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if(J==="database")return new x(Y.make(g));return J(Y)}if(typeof J==="string")throw Error(`Unknown change feed driver "${J}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return J}var GJ={ms:1,s:1000,m:60000,h:3600000,d:86400000,w:604800000};function vJ(J){if(typeof J==="number"){if(!Number.isFinite(J)||J<0)throw TypeError(`A duration is 0 or more milliseconds; got ${J}.`);return Math.round(J)}let Y=/^\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d|w)\s*$/.exec(String(J));if(!Y)throw TypeError(`"${String(J)}" is not a duration. Use milliseconds, or a number and one of ms, s, m, h, d, w ("30s", "7d").`);return Math.round(Number(Y[1])*GJ[Y[2]])}
37
+ export{vJ as Lk,V as Mk,T as Nk,i as Ok,VJ as Pk,S as Qk,O as Rk,R as Sk,x as Tk,I as Uk,L as Vk,JJ as Wk,_ as Xk,MJ as Yk,P as Zk,jJ as _k,u as $k};
38
+
39
+ //# debugId=EF9FC6110EEA07A364756E2164756E21