gemi 0.194.0 → 0.195.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.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/{chunk-svtjfmkc.js → chunk-0y7jqe6m.js} +2 -2
- package/dist/{chunk-svtjfmkc.js.map → chunk-0y7jqe6m.js.map} +1 -1
- package/dist/{chunk-mc8fdh65.js → chunk-39w89wss.js} +2 -2
- package/dist/{chunk-mc8fdh65.js.map → chunk-39w89wss.js.map} +1 -1
- package/dist/{chunk-1yhvqthv.js → chunk-3qmvtfw2.js} +2 -2
- package/dist/{chunk-1yhvqthv.js.map → chunk-3qmvtfw2.js.map} +1 -1
- package/dist/{chunk-1m7kqf2t.js → chunk-5qcqwcp7.js} +3 -3
- package/dist/{chunk-1m7kqf2t.js.map → chunk-5qcqwcp7.js.map} +1 -1
- package/dist/{chunk-3svm89z4.js → chunk-652a9mr0.js} +2 -2
- package/dist/{chunk-3svm89z4.js.map → chunk-652a9mr0.js.map} +1 -1
- package/dist/{chunk-63dh2zt4.js → chunk-6efjnt6r.js} +2 -2
- package/dist/{chunk-63dh2zt4.js.map → chunk-6efjnt6r.js.map} +1 -1
- package/dist/{chunk-h9taahxv.js → chunk-7zf8rnsb.js} +3 -3
- package/dist/{chunk-h9taahxv.js.map → chunk-7zf8rnsb.js.map} +1 -1
- package/dist/chunk-afs0geyy.js +10 -0
- package/dist/{chunk-c6khfprk.js.map → chunk-afs0geyy.js.map} +3 -4
- package/dist/{chunk-jq1vwj5g.js → chunk-ahx3g8tq.js} +1 -1
- package/dist/chunk-ggbf1web.js +5 -0
- package/dist/{chunk-gn90agsv.js.map → chunk-ggbf1web.js.map} +1 -1
- package/dist/{chunk-scmjmsps.js → chunk-j56zk5a0.js} +3 -3
- package/dist/{chunk-scmjmsps.js.map → chunk-j56zk5a0.js.map} +1 -1
- package/dist/{chunk-495k9h6p.js → chunk-mndcq5z1.js} +2 -2
- package/dist/{chunk-495k9h6p.js.map → chunk-mndcq5z1.js.map} +1 -1
- package/dist/{chunk-v20fe53s.js → chunk-nphb176s.js} +9 -9
- package/dist/{chunk-v20fe53s.js.map → chunk-nphb176s.js.map} +5 -4
- package/dist/{chunk-geqdq8hp.js → chunk-p4eger3g.js} +2 -2
- package/dist/{chunk-geqdq8hp.js.map → chunk-p4eger3g.js.map} +1 -1
- package/dist/{chunk-xpkpz4g6.js → chunk-vqq0z746.js} +2 -2
- package/dist/{chunk-xpkpz4g6.js.map → chunk-vqq0z746.js.map} +1 -1
- package/dist/{chunk-5nkg3rmw.js → chunk-xjb8frdx.js} +3 -3
- package/dist/{chunk-5nkg3rmw.js.map → chunk-xjb8frdx.js.map} +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/database/index.js +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +1 -1
- package/dist/services/logging/LogManager.d.ts +10 -1
- package/dist/services/logging/LogManager.d.ts.map +1 -1
- package/dist/services/logging/config.d.ts +29 -0
- package/dist/services/logging/config.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-c6khfprk.js +0 -10
- package/dist/chunk-gn90agsv.js +0 -5
- /package/dist/{chunk-jq1vwj5g.js.map → chunk-ahx3g8tq.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{wh as XV}from"./chunk-scmjmsps.js";import{Qh as zV}from"./chunk-geqdq8hp.js";import{Ei as M6,Ki as H6,Rh as O3,Si as R1,Vh as XB,Wh as X9,Wi as nG,Xh as G9,Xi as jZ,Yh as S8,Yi as zZ,Zh as N8,_i as mB,ai as _8,aj as hB,bi as I8,ci as J3,di as W8,ei as oW,fi as R2,gi as d,mi as C,ni as xW,oi as o8,pi as MZ,qi as E8,ri as L6,ti as R$,ui as m,vi as a4}from"./chunk-v20fe53s.js";import{dj as Z$,ej as K0,fj as W$,gj as B9}from"./chunk-228w21t6.js";import{hj as ZZ,ij as tW,mj as t9,nj as Y8,oj as P}from"./chunk-dfmxvp8p.js";import{rj as gG,uj as a3}from"./chunk-n914rs58.js";import{Bj as kB,yj as BY}from"./chunk-g02gqhq0.js";import{Tj as b$,Yj as J$}from"./chunk-1705yamg.js";import{kk as HG}from"./chunk-1ghbn9jg.js";import{lk as XZ,ok as bB}from"./chunk-gmcttf0f.js";import{pk as N1}from"./chunk-beckfwe9.js";import{Gk as H2,qk as F6,rk as s0,sk as w1,tk as M2,uk as jV,wk as sZ,xk as gB}from"./chunk-wvq3c25z.js";import{Vk as f1}from"./chunk-ftvc1a0k.js";import{_k as pW,dl as cW}from"./chunk-m08p5mre.js";import{kl as hW,pl as c}from"./chunk-8e17k7ht.js";import{ql as Z3,tl as H}from"./chunk-ermvtpy9.js";import{Bl as qW}from"./chunk-j49vh5bs.js";import{Cl as pB}from"./chunk-5bfrr8x5.js";import{Ml as bW}from"./chunk-aycfrzh1.js";import{Nl as F8,Pl as GB}from"./chunk-2g2fsr71.js";import{Ul as j8}from"./chunk-vgxkt9vd.js";function z6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),OV=new Set([301,302,303,307,308]);class F1{kind;body;status;headers;[N2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return P2(J,"json"),new F1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return F1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!OV.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new F1("empty",void 0,J,Y)}static noContent($={}){return new F1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new F1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function P2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function r1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function DV($,Z,J={}){return F1.error($,Z,J)}function e0($){return typeof $==="string"?[$]:$}function X6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function LV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Q3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":I8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function MV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(LV($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function x8($,Z){if($ instanceof Response)return $;if(!$)return _2();let J=await MV($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return _2()}let{range:G}=Z;if(G){if(z<=0)return Q3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=N8(G,z);if(!B)return Q3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",_8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",X6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:V,headers:F})}return new Response(W,{status:V,headers:F})}class FZ extends K0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var I2={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function V3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in I2)))return Math.floor(Number(J[1])*(I2[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var B3=new WeakMap;function C2($){return B3.has($)}function A2($){return B3.get($)?.limit??null}function S2($){let Z=B3.get($);return Z?Z.read>Z.limit:!1}function HV($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function A8($,Z){let J=HV($);if(J!==null&&J>Z)throw new FZ(Z)}function G6($,Z,J={}){let W=B3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};B3.set($,Y),TV($,Y)}if(J.checkDeclared!==!1)A8($,Z)}function KV($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function C8($,Z){if(Z.stream!==void 0)return Z.stream;let J=KV($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new FZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function VZ($,Z){if(A8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=C8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;Y.push(Q),j+=Q.byteLength}let z=new Uint8Array(j),X=0;for(let G of Y)z.set(G,X),X+=G.byteLength;return z}function x2($){return $.headers.get("Content-Type")??""}function TV($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>C8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>VZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await VZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await VZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await VZ($,Z)))}),J("blob",{value:async()=>new Blob([await VZ($,Z)],{type:x2($)})}),J("formData",{value:async()=>new Response(await VZ($,Z),{headers:{"Content-Type":x2($)}}).formData()}),J("clone",{value:()=>{A8($,Z.limit);let W=C8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function PV($){return z6($)}function E2($,Z){if($.length===0)return $();return $(Z??new C)}class s{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!PV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return E2(Z[this.methodName].bind(Z),$)}return E2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class k2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of R2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new FZ(A2($.rawRequest));throw J}}}class w2{constructor(...$){return new s(...$)}}class f2 extends s{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=S8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(r1(Y))return Y;return await x8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return Q3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class q2{constructor(...$){return new f2(...$)}}class v2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new s("GET",$,"list"),post:new s("POST",$,"store")},this.second={get:new s("GET",$,"show"),put:new s("PUT",$,"update"),delete:new s("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class C0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new s("GET",$,Z)}post($,Z){return new s("POST",$,Z)}put($,Z){return new s("PUT",$,Z)}patch($,Z){return new s("PATCH",$,Z)}delete($,Z){return new s("DELETE",$,Z)}resource($){return new v2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${b2($)}.`);return NV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${b2($)}.`);return _V($)}file($,Z){return new w2("GET",$,Z)}stream($,Z){return new q2("GET",$,Z)}proxy($,Z={}){return new k2($,Z)}}function b2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function NV($){let Z={stream:new s("POST",$,"stream"),attach:new s("POST",$,"attach"),watch:new s("POST",$,"watch"),stop:new s("POST",$,"stop"),upload:new s("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function _V($){let Z={start:new s("POST",$,"voiceStart"),update:new s("PATCH",$,"voiceUpdate"),end:new s("DELETE",$,"voiceEnd")};return class extends C0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var e1="access_token";function E$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Q6($,Z){let J=E$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var IV=/^[A-Za-z0-9_-]+$/,xV=/^:[A-Za-z_][A-Za-z0-9_]*$/,g2=/^[A-Za-z0-9_-]{1,128}$/,CV=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function y2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new u("A channel pattern must be a non-empty string.");if($.length>255)throw new u(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(xV.test(W)){let Y=W.slice(1);if(J.has(Y))throw new u(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new u(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!IV.test(W))throw new u(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function F3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new u(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!g2.test(G))throw new u(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new u(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new u(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function m2($){if(typeof $!=="string"||$.length===0||$.length>64||!CV.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function h2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&g2.test(W[j]))}var U0="user";function OZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return F3(`${U0}.:id`,{id:Z})}class J0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class B6 extends J0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return G6(this.req.rawRequest,V3(Z)),{}}}function AV($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var SV={"body-limit":B6};class $${config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:V3($.bodyLimit)}get aliases(){return{...SV,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!C2($))G6($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of AV($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:p2(z)})}}else if(z6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:p2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await EV(W.slice(j+1)),z}return Y})()}}function p2($){return $?.runsOnRefusal===!0}async function EV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class V6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...e0($)],this}events(...$){return this}}class l2{static __brand="ChannelRouter";channels={};public(){return new V6("public")}private($){return new V6("private",$)}async authorize($,Z,J={},W={}){try{wV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!i2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=F3(Z,J??{})}catch(G){if(G instanceof u)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return P.exit(()=>F6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H($$).runMiddleware(Y.middlewares);if(Z===U0){let Q=await c2(X);if(!Q)return{ok:!1,code:"denied"};if(j=OZ(Q),Y.visibility==="private"&&Y.authorizer){if(await d2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await d2(Y.authorizer,X,z):await c2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(kV(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function bV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;s2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function i2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function c2($){if(!P.getStore().user&&E$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function d2($,Z,J){if(RV($))return new $().authorize(Z,J);return $(Z,J)}function RV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function kV($){return $?.kind===Z$||J$($)||b$($)}var u2=new WeakSet;function wV($){if(u2.has($))return;s2($),u2.add($)}function s2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!i2(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new u(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new u(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new u(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(fV(J[W].segments,J[Y].segments))throw new u(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function fV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class U6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function qV($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function vV($,Z){let J=qV($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class n2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new U6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:M,files:T,...K}=Y[U],I=D??(O?vV(W,O):W);if(B.has(I))throw Error(`${Q}: the audiences "${B.get(I)}" and "${U}" are both named "${I}". Give one its own name or casing.`);B.set(I,U);let b=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof b!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let S={...G,...K,description:b};if(z||M)S.params={...z,...M};if(X||T)S.files={...X,...T};F[I]=new U6($,Z,S)}return F}}function O0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class w8 extends K0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class E1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class o2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return E1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",X6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class a2{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function t2($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class r2{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=t2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class e2{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=t2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new r2($,Z)}file($){return new a2($)}redirect($){return new o2($)}layout($,Z,J){return new e2($,Z,J)}}function gV($){return $}function yV(){return{aliases:{},global:[],bodyLimit:null}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function DZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function mV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function hV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function O6($,Z){let J=Z||H(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=mV($,!W);if(W||!hV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class $9 extends J0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await Q6(H(E),J);if(!W)throw new R$({redirectTo:O6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class D6 extends J0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(g8))return{};if(E$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new Z9(`${W.pathname}${W.search}`)}}class Z9 extends K0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=pV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function pV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class J9 extends J0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var W9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class Y9 extends J0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...W9,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...W9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var cV="Rate limit exceeded";class Y$ extends K0{result;retryAfter;constructor($,Z=cV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...W$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class O1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(j9("window",W),j9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new Y$(W,typeof J==="function"?J(W):J);return W}}function j9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function k$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class Q9 extends J0{async run($,Z){let J=dV();if(!J)return{};let W=await J.consume(this.key(),{limit:z9($)??this.config.limit,window:z9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new Y$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=X9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${LZ(this.req)}:${this.req.routePath??"*"}`}}function dV(){try{let $=H();return $.bound(O1)?$.make(O1):null}catch{return null}}function LZ($){let Z=G9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function z9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class V9 extends J0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends K0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:B9("csrf","Invalid CSRF token",403)}},view:{}}}class F9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class U9{all($,Z){return!0}}class p8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new MZ:new L6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends J0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof MZ:$ instanceof L6}}function uV($){return new p8($)}async function K6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await WF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return JF(z,Z,J,$.url)}async function JF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new H6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function WF($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function T6($){return new TextDecoder("utf-8").decode($)}var YF={"&":"&","<":"<",">":">",'"':""","'":"'"};function w$($){return $.replace(/[&<>"']/g,(Z)=>YF[Z])}var jF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function c8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return jF[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function d8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function O9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(c8($.slice(W)));return}if(Y>W)Z.text(c8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(d8($.slice(Y+2,j).trim())),W=j+1}else{let j=zF($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=d8(z.slice(0,G));if(Q){if(Z.open(Q,XF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function zF($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function XF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[d8(W[1])]=c8(W[2]??W[3]??"");return Z}class z0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var K9="http://www.sitemaps.org/schemas/sitemap/0.9",GF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
import{uh as XV}from"./chunk-j56zk5a0.js";import{Oh as zV}from"./chunk-p4eger3g.js";import{$h as I8,Ci as M6,Ii as H6,Ph as O3,Qi as R1,Th as XB,Uh as X9,Vh as G9,Wh as S8,Wi as nG,Xh as N8,Xi as jZ,Yi as zZ,_h as _8,_i as mB,ai as J3,aj as hB,bi as W8,ci as oW,di as R2,ei as d,ki as C,li as xW,mi as o8,ni as MZ,oi as E8,pi as L6,ri as R$,si as m,ti as a4}from"./chunk-nphb176s.js";import{dj as Z$,ej as K0,fj as W$,gj as B9}from"./chunk-228w21t6.js";import{hj as ZZ,ij as tW,mj as t9,nj as Y8,oj as P}from"./chunk-dfmxvp8p.js";import{rj as gG,uj as a3}from"./chunk-n914rs58.js";import{Bj as kB,yj as BY}from"./chunk-g02gqhq0.js";import{Tj as b$,Yj as J$}from"./chunk-1705yamg.js";import{kk as HG}from"./chunk-1ghbn9jg.js";import{lk as XZ,ok as bB}from"./chunk-gmcttf0f.js";import{pk as N1}from"./chunk-beckfwe9.js";import{Gk as H2,qk as F6,rk as s0,sk as w1,tk as M2,uk as jV,wk as sZ,xk as gB}from"./chunk-wvq3c25z.js";import{Vk as f1}from"./chunk-ftvc1a0k.js";import{_k as pW,dl as cW}from"./chunk-m08p5mre.js";import{kl as hW,pl as c}from"./chunk-8e17k7ht.js";import{ql as Z3,tl as H}from"./chunk-ermvtpy9.js";import{Bl as qW}from"./chunk-j49vh5bs.js";import{Cl as pB}from"./chunk-5bfrr8x5.js";import{Ml as bW}from"./chunk-aycfrzh1.js";import{Nl as F8,Pl as GB}from"./chunk-2g2fsr71.js";import{Ul as j8}from"./chunk-vgxkt9vd.js";function z6($){return typeof $==="function"&&$.prototype!==void 0}var N2=Symbol.for("gemi.HttpResponse"),OV=new Set([301,302,303,307,308]);class F1{kind;body;status;headers;[N2]=!0;constructor($,Z,J,W){this.kind=$;this.body=Z;this.status=J;this.headers=W}static json($,Z={}){let J=Z.status??200;return P2(J,"json"),new F1("json",$,J,new Headers(Z.headers))}static error($,Z,J={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return F1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!OV.has(J))throw RangeError(`HttpResponse.redirect: status must be 301, 302, 303, 307 or 308, got ${J}.`);let W=String($);if(W==="")throw TypeError("HttpResponse.redirect: url is empty.");let Y=new Headers(Z.headers);return Y.set("Location",W),new F1("empty",void 0,J,Y)}static noContent($={}){return new F1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return P2(J,"text"),new F1("text",$,J,new Headers(Z.headers))}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let J=$,W=this.serialize(J);for(let Y of Z)J.append("Set-Cookie",Y);this.headers.forEach((Y,j)=>{if(j.toLowerCase()!=="set-cookie")J.set(j,Y)});for(let Y of this.headers.getSetCookie())J.append("Set-Cookie",Y);if(this.status>=400&&!this.headers.has("Cache-Control"))J.set("Cache-Control","no-store");return new Response(W,{status:this.status,headers:J})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null;case"text":return $.set("Content-Type","text/plain; charset=utf-8"),this.body;case"empty":return $.delete("Content-Type"),null}}}function P2($,Z){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse.${Z}: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.${Z}: a ${$} response has no body.${$===204?" Use HttpResponse.noContent().":""}`)}function r1($){return typeof $==="object"&&$!==null&&$[N2]===!0}function DV($,Z,J={}){return F1.error($,Z,J)}function e0($){return typeof $==="string"?[$]:$}function X6($,Z){let J=$.split(/[\\/]/).pop()??"",W=Z?"attachment":"inline",Y=J.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${W}; filename="${Y}"; filename*=UTF-8''${encodeURIComponent(J)}`}function LV($){return"total"in $&&"partial"in $&&"body"in $}function _2(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Q3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":I8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function MV($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(LV($))return{body:$.body,start:$.start,end:$.end,total:$.total,partial:$.partial,type:$.type,name:$.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}};let Z=$.file,J=Z instanceof Blob?Z:null,W=$.total??J?.size??-1;return{body:Z,start:$.start??0,end:$.end??W-1,total:W,partial:$.partial??!1,type:$.type??J?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function x8($,Z){if($ instanceof Response)return $;if(!$)return _2();let J=await MV($),{body:W,start:Y,end:j,total:z,partial:X}=J;if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return _2()}let{range:G}=Z;if(G){if(z<=0)return Q3(Math.max(z,0));if(!X){if(W instanceof Blob){let B=N8(G,z);if(!B)return Q3(z);W=W.slice(B.start,B.end+1),Y=B.start,j=B.end,X=!0}}}let Q=Boolean(G)&&X,V=Q?206:J.status,F=new Headers;if(F.set("Accept-Ranges","bytes"),F.set("Content-Type",J.type||"application/octet-stream"),F.set("X-Content-Type-Options","nosniff"),Q)F.set("Content-Range",_8(Y,j,z)),F.set("Content-Length",String(j-Y+1));else if(z>=0)F.set("Content-Length",String(z));if(J.name)F.set("Content-Disposition",X6(J.name,J.download));if(J.etag)F.set("ETag",J.etag);if(J.lastModified)F.set("Last-Modified",J.lastModified.toUTCString());for(let[B,U]of Object.entries(J.extraHeaders))F.set(B,U);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:V,headers:F})}return new Response(W,{status:V,headers:F})}class FZ extends K0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var I2={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function V3($){if(typeof $==="number"){if(Number.isFinite($)&&$>=0)return Math.floor($);if($===1/0)return 1/0}else{let Z=$.trim().toLowerCase();if(Z==="none"||Z==="off")return 1/0;let J=/^(\d+(?:\.\d+)?)\s*([a-z]*)$/.exec(Z);if(J&&(J[2]===""||(J[2]in I2)))return Math.floor(Number(J[1])*(I2[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var B3=new WeakMap;function C2($){return B3.has($)}function A2($){return B3.get($)?.limit??null}function S2($){let Z=B3.get($);return Z?Z.read>Z.limit:!1}function HV($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function A8($,Z){let J=HV($);if(J!==null&&J>Z)throw new FZ(Z)}function G6($,Z,J={}){let W=B3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};B3.set($,Y),TV($,Y)}if(J.checkDeclared!==!1)A8($,Z)}function KV($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function C8($,Z){if(Z.stream!==void 0)return Z.stream;let J=KV($);if(!J)return Z.stream=null;let W;return Z.stream=new ReadableStream({async pull(Y){W??=J.getReader();let{done:j,value:z}=await W.read();if(j){Y.close();return}if(Z.read+=z.byteLength,Z.read>Z.limit){let X=new FZ(Z.limit);Y.error(X),W.cancel(X).catch(()=>{});return}Y.enqueue(z)},cancel(Y){return W?W.cancel(Y):J.cancel(Y)}},{highWaterMark:0}),Z.stream}async function VZ($,Z){if(A8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=C8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:G,value:Q}=await W.read();if(G)break;Y.push(Q),j+=Q.byteLength}let z=new Uint8Array(j),X=0;for(let G of Y)z.set(G,X),X+=G.byteLength;return z}function x2($){return $.headers.get("Content-Type")??""}function TV($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>C8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>VZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await VZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await VZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await VZ($,Z)))}),J("blob",{value:async()=>new Blob([await VZ($,Z)],{type:x2($)})}),J("formData",{value:async()=>new Response(await VZ($,Z),{headers:{"Content-Type":x2($)}}).formData()}),J("clone",{value:()=>{A8($,Z.limit);let W=C8($,Z),Y=null;if(W){let[j,z]=W.tee();Z.stream=j,Y=z}return new Request($.url,{method:$.method,headers:$.headers,body:Y,signal:$.signal,duplex:"half"})}})}function PV($){return z6($)}function E2($,Z){if($.length===0)return $();return $(Z??new C)}class s{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,J){this.method=$;this.handler=Z;this.methodName=J;this.handler=Z,this.methodName=J,this.method=$}get source(){if(!PV(this.handler)||typeof this.methodName!=="string")return;return{controller:this.handler,methodName:this.methodName}}__internal_use(){return{run:this.run.bind(this),middlewares:this.middlewares}}run($){if(this.source){let Z=new this.source.controller;return E2(Z[this.methodName].bind(Z),$)}return E2(this.handler,$)}middleware($){return this.middlewares=e0($),this}}class k2{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=e0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of R2($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(S2($.rawRequest))throw new FZ(A2($.rawRequest));throw J}}}class w2{constructor(...$){return new s(...$)}}class f2 extends s{__internal_brand="StreamHandler";async run($){let Z=P.getStore(),J=Z?.req?.rawRequest,W=S8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(r1(Y))return Y;return await x8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof E8)return Q3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class q2{constructor(...$){return new f2(...$)}}class v2{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new s("GET",$,"list"),post:new s("POST",$,"store")},this.second={get:new s("GET",$,"show"),put:new s("PUT",$,"update"),delete:new s("DELETE",$,"delete")}}middleware($){if($.list)this.first.get.middleware($.list);if($.store)this.first.post.middleware($.store);if($.show)this.second.get.middleware($.show);if($.update)this.second.put.middleware($.update);if($.delete)this.second.delete.middleware($.delete);return this}}class C0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new s("GET",$,Z)}post($,Z){return new s("POST",$,Z)}put($,Z){return new s("PUT",$,Z)}patch($,Z){return new s("PATCH",$,Z)}delete($,Z){return new s("DELETE",$,Z)}resource($){return new v2($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${b2($)}.`);return NV($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${b2($)}.`);return _V($)}file($,Z){return new w2("GET",$,Z)}stream($,Z){return new q2("GET",$,Z)}proxy($,Z={}){return new k2($,Z)}}function b2($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function NV($){let Z={stream:new s("POST",$,"stream"),attach:new s("POST",$,"attach"),watch:new s("POST",$,"watch"),stop:new s("POST",$,"stop"),upload:new s("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/watch":Z.watch,"/stop":Z.stop,"/files":Z.upload};static middleware(W){if(W.stream)Z.stream.middleware(W.stream);if(W.attach)Z.attach.middleware(W.attach),Z.watch.middleware(W.attach);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function _V($){let Z={start:new s("POST",$,"voiceStart"),update:new s("PATCH",$,"voiceUpdate"),end:new s("DELETE",$,"voiceEnd")};return class extends C0{static __internal_brand="VoiceRoute";static controller=$;static handlers=Z;routes={"/":Z.start,"/:sessionId":{patch:Z.update,delete:Z.end}};static middleware(W){if(W.start)Z.start.middleware(W.start);if(W.update)Z.update.middleware(W.update);if(W.end)Z.end.middleware(W.end);return this}}}var e1="access_token";function E$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Q6($,Z){let J=E$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var IV=/^[A-Za-z0-9_-]+$/,xV=/^:[A-Za-z_][A-Za-z0-9_]*$/,g2=/^[A-Za-z0-9_-]{1,128}$/,CV=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function y2($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function UZ($){if(typeof $!=="string"||$.length===0)throw new u("A channel pattern must be a non-empty string.");if($.length>255)throw new u(`The channel pattern "${$.slice(0,40)}\u2026" is longer than ${"255"} characters.`);let Z=$.split("."),J=new Set;for(let W of Z){if(xV.test(W)){let Y=W.slice(1);if(J.has(Y))throw new u(`The channel pattern "${$}" names the param "${Y}" twice.`);J.add(Y);continue}if(W.startsWith("__"))throw new u(`The channel "${$}" has the segment "${W}". Segments starting with "__" are reserved for gemi (driver control messages).`);if(!IV.test(W))throw new u(`The channel pattern "${$}" has an invalid segment "${W}". Segments are separated by dots and are either letters, digits, "_" and "-", or a param such as ":siteId".`)}return Z}function F3($,Z={}){let J=UZ($),W=new Set,Y=J.map((j)=>{if(!j.startsWith(":"))return j;let z=j.slice(1);W.add(z);let X=Z[z];if(X===void 0||X===null)throw new u(`The channel "${$}" needs the param "${z}".`);let G=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof G!=="string"||!g2.test(G))throw new u(`The param "${z}" of the channel "${$}" must be 1 to 128 letters, digits, "_" or "-". Use a public id in a channel name.`);return G}).join(".");for(let j of Object.keys(Z))if(!W.has(j))throw new u(`The channel "${$}" has no param "${j}".`);if(Y.length>255)throw new u(`The topic built from "${$}" is longer than 255 characters.`);return Y}function b8($){if(UZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function m2($){if(typeof $!=="string"||$.length===0||$.length>64||!CV.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function h2($,Z){if($===Z)return!0;if($===U0)return Z.startsWith(`${U0}.`)&&Z.split(".").length===2;let J=$.split("."),W=Z.split(".");if(J.length!==W.length)return!1;return J.every((Y,j)=>Y===W[j]||Y.startsWith(":")&&g2.test(W[j]))}var U0="user";function OZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return F3(`${U0}.:id`,{id:Z})}class J0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class B6 extends J0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return G6(this.req.rawRequest,V3(Z)),{}}}function AV($){let Z=new Map;for(let J of $)if(typeof J==="string"){let[W,Y=""]=J.split(":");if(W.startsWith("-")){if(Z.has(W.replace("-","")))Z.delete(W.replace("-",""))}else Z.set(W,Y.split(",").filter(Boolean))}else Z.set(J,[]);return Z}var SV={"body-limit":B6};class $${config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:V3($.bodyLimit)}get aliases(){return{...SV,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!C2($))G6($,this.defaultBodyLimit,{checkDeclared:!1})}assertGlobalMiddleware(){for(let $ of this.config.global){if(typeof $!=="string")continue;let[Z]=$.split(":");if(Z.startsWith("-"))throw Error(`Global middleware "${$}" cancels an alias, but nothing is inherited into the global list. Remove it.`);if(!this.aliases[Z])throw Error(`Global middleware "${Z}" is not a registered alias. Add it to \`aliases\` in the middleware config, or list the class itself.`)}}runGlobalMiddleware(){return this.runMiddleware(this.config.global)}runMiddleware($){let Z=new C,J=this.aliases,W=[];for(let[Y,j]of AV($).entries())if(typeof Y==="string"){let z=J[Y];if(z){let X=new z(Z);W.push({run:()=>X.run.call(X,...j),runsOnRefusal:p2(z)})}}else if(z6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:p2(Y)})}else W.push({run:Y,runsOnRefusal:!1});return(async()=>{let Y={};for(let j=0;j<W.length;j++)try{Y={...Y,...await W[j].run()}}catch(z){throw await EV(W.slice(j+1)),z}return Y})()}}function p2($){return $?.runsOnRefusal===!0}async function EV($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class V6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...e0($)],this}events(...$){return this}}class l2{static __brand="ChannelRouter";channels={};public(){return new V6("public")}private($){return new V6("private",$)}async authorize($,Z,J={},W={}){try{wV(this)}catch(G){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",G),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!i2(Y))return{ok:!1,code:"unknown_channel"};let j=null;try{if(Z===U0){if(Object.keys(J??{}).length>0)return{ok:!1,code:"invalid_params"}}else j=F3(Z,J??{})}catch(G){if(G instanceof u)return{ok:!1,code:"invalid_params"};throw G}let z=Object.fromEntries(Object.entries(J??{}).map(([G,Q])=>[G,String(Q)])),X=new C($,z,"api",Z);return P.exit(()=>F6.exit(()=>P.run(X,async()=>{let G=P.getStore();try{if(Y.middlewares.length>0)await H($$).runMiddleware(Y.middlewares);if(Z===U0){let Q=await c2(X);if(!Q)return{ok:!1,code:"denied"};if(j=OZ(Q),Y.visibility==="private"&&Y.authorizer){if(await d2(Y.authorizer,X,z)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}if(Y.visibility==="private"){if((Y.authorizer?await d2(Y.authorizer,X,z):await c2(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(Q){if(kV(Q))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,Q),{ok:!1,code:"error"}}finally{G.destroy()}},W.carried)))}}async function bV($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;s2(Y);let j=W.as,z,X=null;if(j instanceof Request)z=j;else if(j&&typeof j==="object"&&j.rawRequest instanceof Request)z=j.rawRequest;else z=new Request("http://localhost/__gemi/socket"),X=j?{user:j}:null;return(await Y.authorize(z,Z,J,{carried:X})).ok}function i2($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function c2($){if(!P.getStore().user&&E$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function d2($,Z,J){if(RV($))return new $().authorize(Z,J);return $(Z,J)}function RV($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function kV($){return $?.kind===Z$||J$($)||b$($)}var u2=new WeakSet;function wV($){if(u2.has($))return;s2($),u2.add($)}function s2($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!i2(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=UZ(W);if(j[0].startsWith(":"))throw new u(`The channel pattern "${W}" starts with a param. Start it with a literal segment, such as "site.:siteId", so it cannot overlap another channel.`);if(W!==U0&&j.length===2&&j[0]===U0)throw new u(`The channel pattern "${W}" can build user.<id>, which belongs to the "user" channel (the signed-in user's own). Declare "user" and emit with Broadcast.toUser(user), or name this channel differently.`);if(W!==U0&&Y.visibility==="private"&&!Y.authorizer&&j.some((z)=>z.startsWith(":")))throw new u(`The private channel "${W}" has params but no authorization, so every signed-in user could join every one of them. Pass a callback or a policy that checks the params: this.private((req, params) => ...).`);J.push({pattern:W,segments:W===U0?[U0,":id"]:j})}for(let W=0;W<J.length;W++)for(let Y=W+1;Y<J.length;Y++)if(fV(J[W].segments,J[Y].segments))throw new u(`The channel patterns "${J[W].pattern}" and "${J[Y].pattern}" can build the same topic, so a subscriber could join one's topics through the other's authorization. Make them differ in a literal segment.`)}function fV($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class R8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class U6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class k8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function qV($){let Z=[],J="";for(let W of $)if(W==="_"||W==="-"||W===" "){if(J)Z.push(J);J=""}else if(W===W.toLowerCase())J+=W;else{if(J)Z.push(J);J=W.toLowerCase()}if(J)Z.push(J);return Z}function vV($,Z){let J=qV($);if(Z==="snake")return J.join("_");if(Z==="kebab")return J.join("-");return J.map((W,Y)=>Y===0?W:W[0].toUpperCase()+W.slice(1)).join("")}class n2{static __brand="McpRouter";routes={};scopes;param($){return new R8($.as,$.input,$.bind)}fromTool($,Z={}){return new k8($,Z)}fromApiRoute($,Z,J){return new U6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...G}=J,Q=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,V=Object.keys(Y??{});if(V.length===0)throw Error(`${Q}: declare at least one audience.`);let F={},B=new Map;for(let U of V){let{name:D,casing:O,description:L,params:M,files:T,...K}=Y[U],I=D??(O?vV(W,O):W);if(B.has(I))throw Error(`${Q}: the audiences "${B.get(I)}" and "${U}" are both named "${I}". Give one its own name or casing.`);B.set(I,U);let b=typeof L==="function"?j===void 0?void 0:L(j):L??j;if(typeof b!=="string")throw Error(`${Q}: the audience "${U}" has no description, and there is no shared one.`);let S={...G,...K,description:b};if(z||M)S.params={...z,...M};if(X||T)S.files={...X,...T};F[I]=new U6($,Z,S)}return F}}function O0($,Z){return $.replace(/:([^/]+[*?]?)/g,(J,W)=>{let Y=W.endsWith("?")||W.endsWith("*"),j=Y?W.slice(0,-1):W,z=Z[j];if(z===void 0){if(Y)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${j}`);console.error(`Missing parameter: ${j} in URL: ${$}`)}return String(z)}).replace(/\/\//g,"/").replace(/\/$/,"")}class w8 extends K0{constructor($,Z=307){super("Redirect error");this.name="RedirectError",this.payload={api:{status:200,data:{},directive:{kind:"Redirect",path:$}},view:{status:Z,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:$}}}}}class E1{static to($,...Z){let[J={}]=Z,{search:W={},params:Y={},permanent:j,status:z}={params:{},status:307,permanent:!1,...J},X=new URLSearchParams(W).toString();throw new w8([O0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new w8($,Z)}}class o2{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let{destination:J,permanent:W=!1,status:Y=307}=await this.handler($);if(!J)throw Error(`Redirect destination is required see ${Z}`);return E1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function f8($,Z){if($ instanceof Response)return $;let J=$ instanceof Blob,W=J?$:$.file,Y=J?$.name:$.name??$.file?.name,j=(J?$.type:$.type??$.file?.type)||"",z=J?!1:$.download??!1,X=J?200:$.status??200;if(!J)for(let[G,Q]of Object.entries($.headers??{}))Z.set(G,Q);if(W instanceof Blob&&"exists"in W&&typeof W.exists==="function"){if(!await W.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",j||"application/octet-stream"),W instanceof Blob)Z.set("Content-Length",String(W.size));if(Y)Z.set("Content-Disposition",X6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class a2{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,J]=$;this.handler=(W)=>{return new Z()[J](W)}}}async run($,Z){let J=await this.handler($);if(!J)throw Error(`File route handler must return a file see ${Z}`);return{FILE:J}}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function t2($,Z){if(r1($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class r2{viewPath;middlewares=[];featureGates=[];staticOptions=null;handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[J,W]=Z;this.handler=(Y)=>{return new J()[W](Y)}}}async run($,Z){let J=t2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=e0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class e2{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends b1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends b1{routes=J??{}}}else this.children=class extends b1{routes=Z},this.handler=()=>({})}async run($,Z){let J=t2(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=e0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class b1{middlewares=[];featureGates=[];routes={};view($,Z){return new r2($,Z)}file($){return new a2($)}redirect($){return new o2($)}layout($,Z,J){return new e2($,Z,J)}}function gV($){return $}function yV(){return{aliases:{},global:[],bodyLimit:null}}var l0="redirect";function U1($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let J=new URL($,"http://gemi.invalid");if(J.origin!=="http://gemi.invalid")return Z;let W=`${J.search}${J.hash}`.replaceAll("/","%2F"),Y=`${J.pathname}${W}`.replaceAll(":","%3A");return Y.startsWith("//")?Z:Y}catch{return Z}}function DZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function q8($){return/^(https?:\/\/|\/\/)/i.test($??"")}function mV($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(H(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function hV($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function O6($,Z){let J=Z||H(E).config.signInPath,W=/^[a-z][a-z\d+.-]*:/i.test(J);if(W?!/^https?:\/\//i.test(J):!J.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${J}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let Y=new URL(J,"http://gemi.invalid");if($?.kind==="view"){let j=mV($,!W);if(W||!hV(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(l0,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class $9 extends J0{async run($){let Z=P.getStore(),J=Z.req;if(Z.user)return{};let W=await Q6(H(E),J);if(!W)throw new R$({redirectTo:O6(J,$)});return Z.setUser(W),{}}}var g8="gemi_same_site",v8="private, no-cache, no-store, max-age=0, must-revalidate";class D6 extends J0{run(){let $=P.getStore(),Z=$?.req;if(!Z||$.user)return{};let J=Z.rawRequest;if(Z.kind!=="view"||J.method!=="GET"&&J.method!=="HEAD")return{};let W=new URL(J.url);if(/\.(json|og)$/.test(W.pathname))return{};if(W.searchParams.has(g8))return{};if(E$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(g8,"1"),new Z9(`${W.pathname}${W.search}`)}}class Z9 extends K0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=pV($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":v8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":v8}},viewData:{status:200,data:{},headers:{"Cache-Control":v8},directive:{kind:"Redirect",path:$}},view:{status:200,headers:J,body:`<!doctype html><html><head><meta charset="utf-8"><meta name="robots" content="noindex"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=${Z}"><title>Redirecting</title></head><body><p><a href="${Z}">Continue</a></p></body></html>`}}}}function pV($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class J9 extends J0{async run(...$){let[Z="public",J="864000",...W]=$,Y=`${Z}, max-age=${J}${W.length>0?", ":""}${W.join(", ")}`;if($.length===0)Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")Y="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")Y="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",Y);return{}}}var W9={"Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"};class Y9 extends J0{static runsOnRefusal=!0;config={origins:{"":{"Access-Control-Allow-Methods":"GET, HEAD, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Allow-Credentials":"true"}}};run(){let $=this.req,Z=$.rawRequest.headers.get("Origin");if(Z&&this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let J={...W9,...this.config.origins[Z]};for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}else if(Z&&this.config.origins["*"]){$.ctx().setHeaders("Access-Control-Allow-Origin","*");let J={...W9,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var cV="Rate limit exceeded";class Y$ extends K0{result;retryAfter;constructor($,Z=cV){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?y8($):{}};this.payload={api:{status:429,data:{error:{...W$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function y8($){let Z={"X-RateLimit-Limit":String($.limit),"X-RateLimit-Remaining":String($.remaining),"X-RateLimit-Reset":String(Math.ceil($.resetAt/1000))};if(!$.allowed)Z["Retry-After"]=String(Math.max(1,Math.ceil($.retryAfter/1000)));return Z}class O1{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let J=Z.limit??this.config.limit,W=Z.window??this.config.window,Y=Z.cost??1;if(j9("window",W),j9("limit",J),!Number.isFinite(Y)||Y<0)throw Error(`Rate limiter cost must be zero or greater, got ${Y}`);return await this.config.driver.consume({key:$,limit:J,window:W*1000,cost:Y})}async enforce($,Z={},J){let W=await this.consume($,Z);if(!W.allowed)throw new Y$(W,typeof J==="function"?J(W):J);return W}}function j9($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as m8}from"net";function k$($){let Z=$.trim();if(Z==="")return null;if(Z.startsWith("[")){let W=Z.indexOf("]");if(W<0)return null;let Y=Z.slice(W+1);if(Y!==""&&!/^:\d{1,5}$/.test(Y))return null;let j=Z.slice(1,W);return m8(j)===6?j:null}if(m8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&m8(J[1])===4?J[1]:null}class Q9 extends J0{async run($,Z){let J=dV();if(!J)return{};let W=await J.consume(this.key(),{limit:z9($)??this.config.limit,window:z9(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(y8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new Y$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=X9(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${LZ(this.req)}:${this.req.routePath??"*"}`}}function dV(){try{let $=H();return $.bound(O1)?$.make(O1):null}catch{return null}}function LZ($){let Z=G9($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return k$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function z9($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class V9 extends J0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new h8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new h8;return{}}}class h8 extends K0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:B9("csrf","Invalid CSRF token",403)}},view:{}}}class F9{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class U9{all($,Z){return!0}}class p8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new MZ:new L6}authorize($,Z){if(typeof Z==="number"&&Number.isFinite(Z))Z=String(Z);if(typeof Z!=="string"||Z==="")return Promise.reject(this.refusal());let J=this.answers.get($.rawRequest);if(!J)J=new Map,this.answers.set($.rawRequest,J);let W=J.get(Z);if(!W)W=this.decide($,Z),J.set(Z,W);return W}async allows($,Z){try{return await this.authorize($,Z),!0}catch(J){if(this.isRefusal(J))return!1;throw J}}fromRoute($=new C,Z=this.param){if(Z===void 0)throw Error('This resource policy has no `param`. Give `defineResourcePolicy` one, or name it: `fromRoute(req, "pageId")`, or `alias:pageId` on the middleware.');return this.authorize($,$.params?.[Z])}get middleware(){if(!this.middlewareClass){let $=(Z,J)=>this.fromRoute(Z,J||void 0);this.middlewareClass=class extends J0{async run(J){await $(this.req,J)}}}return this.middlewareClass}middlewareClass;forAgent($){return{authorize:async(Z,{threadId:J,body:W})=>{let Y;if(J!==void 0){if(Y=$.thread?await $.thread(J,Z):null,Y===null||Y===void 0)throw this.refusal()}if(W!==void 0){let j=await $.body(W,Z);if(await this.authorize(Z,j),J!==void 0&&String(Y)!==String(j))throw this.refusal();return}if(J!==void 0)await this.authorize(Z,Y)}}}async decide($,Z){let J=await this.options.load(Z,$);if(J===null||J===void 0||!await this.options.allow(J,$))throw this.refusal();return J}isRefusal($){return this.refuse==="forbidden"?$ instanceof MZ:$ instanceof L6}}function uV($){return new p8($)}async function K6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await WF($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return JF(z,Z,J,$.url)}async function JF($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:Q,value:V}=await Y.read();if(Q)break;if(z+V.byteLength>Z){if(!J)throw new H6(W,Z);j.push(V.subarray(0,Z-z)),z=Z;break}j.push(V),z+=V.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),G=0;for(let Q of j)X.set(Q,G),G+=Q.byteLength;return X}async function WF($){let Z=$.getReader(),J=await Z.read(),W=J.done?new Uint8Array:J.value,Y=new ReadableStream({start(j){if(J.done)j.close();else j.enqueue(W)},async pull(j){let z=await Z.read();if(z.done)j.close();else j.enqueue(z.value)},cancel(j){return Z.cancel(j)}});return[W,Y]}function T6($){return new TextDecoder("utf-8").decode($)}var YF={"&":"&","<":"<",">":">",'"':""","'":"'"};function w$($){return $.replace(/[&<>"']/g,(Z)=>YF[Z])}var jF={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function c8($){if(!$.includes("&"))return $;return $.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,4});/g,(Z,J)=>{if(J[0]!=="#")return jF[J]??Z;let W=J[1]==="x"?parseInt(J.slice(2),16):parseInt(J.slice(1),10);return W>0&&W<=1114111?String.fromCodePoint(W):Z})}function d8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function O9($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(c8($.slice(W)));return}if(Y>W)Z.text(c8($.slice(W,Y)));if($.startsWith("<!--",Y)){let j=$.indexOf("-->",Y+4);if(j===-1)return;W=j+3}else if($.startsWith("<![CDATA[",Y)){let j=$.indexOf("]]>",Y+9);if(j===-1)return;Z.text($.slice(Y+9,j)),W=j+3}else if($.startsWith("<?",Y)){let j=$.indexOf("?>",Y+2);if(j===-1)return;W=j+2}else if($.startsWith("<!",Y)){let j=$.indexOf(">",Y+2);if(j===-1)return;let z=$.indexOf("[",Y+2);if(z!==-1&&z<j){let X=$.indexOf("]",z+1);if(X===-1)return;let G=$.indexOf(">",X+1);if(G===-1)return;W=G+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(d8($.slice(Y+2,j).trim())),W=j+1}else{let j=zF($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let G=z.search(/[\s]|$/),Q=d8(z.slice(0,G));if(Q){if(Z.open(Q,XF(z.slice(G)),X),X)Z.close(Q)}W=j+1}}}function zF($,Z){let J=null;for(let W=Z;W<$.length;W++){let Y=$[W];if(J){if(Y===J)J=null}else if(Y==='"'||Y==="'")J=Y;else if(Y===">")return W}return-1}function XF($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[d8(W[1])]=c8(W[2]??W[3]??"");return Z}class z0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var K9="http://www.sitemaps.org/schemas/sitemap/0.9",GF="http://www.w3.org/1999/xhtml",i8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
`,D9=`<urlset xmlns="${K9}" xmlns:xhtml="${GF}">
|
|
4
4
|
`,L9=`</urlset>
|
|
5
5
|
`,f$=50000,U3=52428800,M9=2048,QF=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),BF=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,VF="application/xml; charset=utf-8",H9=new TextEncoder;function s8($,Z){let J;try{J=new URL($)}catch{throw new z0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new z0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>M9)throw new z0(`Sitemap: ${Z} is over ${M9} characters: "${W.slice(0,80)}\u2026".`);return W}function T9($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new z0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!BF.test($))throw new z0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function FF($){let Z=s8($.loc,"loc"),J=`<url><loc>${w$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${w$(T9($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!QF.has($.changefreq))throw new z0(`Sitemap: changefreq "${$.changefreq}" of ${Z} is not one the protocol knows.`);J+=`<changefreq>${$.changefreq}</changefreq>`}if($.priority!=null){let W=$.priority;if(!Number.isFinite(W)||W<0||W>1)throw new z0(`Sitemap: priority ${W} of ${Z} is not between 0 and 1.`);J+=`<priority>${Number(W.toFixed(4))}</priority>`}for(let W of $.alternates??[]){let Y=W.hrefLang?.trim();if(!Y)throw new z0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=s8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${w$(Y)}" href="${w$(j)}"/>`}return`${J}</url>
|
|
@@ -112,6 +112,6 @@ data: ${JSON.stringify(Z)}
|
|
|
112
112
|
"updated_at" BIGINT NOT NULL,
|
|
113
113
|
"finished_at" BIGINT,
|
|
114
114
|
"deadline_at" BIGINT${W}
|
|
115
|
-
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var rB=191,eB=30000;class H8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class K8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class L2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N1(oB(),$),this.store=YH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(j3);return this.ownFeed??=new j3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){JV("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;JV("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:XZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return WH(Z),this.change($,x1,{status:"running",progress:Z})}complete($,Z){return this.change($,x1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,x1,{status:"failed",error:ZV(Z)})}cancel($,Z){return this.change($,x1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new H8($);if(C1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof K8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,x1,{status:"failed",error:G instanceof K8?ZV(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+XZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new H8($);let z=null;for(;;){if(C1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await $V(z,Math.min(G,X??1/0,eB),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new H8($);if(yield W,C1(W.status))return;for await(let Y of J){let j=JH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,C1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=XZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||C1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,x1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(C1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,$V(j,Math.min(z??1/0,eB))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function $V($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function JH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function ZV($){if(typeof $==="string")return{message:$};if($ instanceof K8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function JV($,Z){if(typeof Z!=="string"||Z===""||Z.length>rB)throw TypeError(`A run's ${$} is a string of 1 to ${rB} characters; got ${JSON.stringify(Z)}.`)}function WH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function YH($,Z){if($==="memory")return new V2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(f1).connection();return new D2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class WV extends m{static getFacadeAccessor(){return L2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class YV extends m{static getFacadeAccessor(){return j$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class K2{value;constructor($){this.value=$}}var jH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function zH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!jH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class T8{bound;constructor($){this.bound=$}get name(){return this.bound??w1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return H2(J.sql,(W)=>M2(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=zH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(s0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await H2(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);let G=await M2(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-sqqby94y.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=XV($,zV(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return w1()===this.name?$:void 0}connection($=this.name){return jV($),H(f1).connection($)}}var GZ=new T8;class GV extends m{static getFacadeAccessor(){return f1}static connection($){return new T8($)}static get sql(){return GZ.sql}static get dialect(){return GZ.dialect}static query($){return GZ.query($)}static execute($){return GZ.execute($)}static transaction($){return GZ.transaction($)}static readOnly($,Z){return GZ.readOnly($,Z)}static schema(){return GZ.schema()}static close(){return this.getFacadeRoot().close()}}export{F1 as oe,DV as pe,e0 as qe,Q3 as re,x8 as se,FZ as te,V3 as ue,C0 as ve,Q6 as we,a8 as xe,t8 as ye,R9 as ze,Y$ as Ae,O1 as Be,k$ as Ce,J0 as De,Q9 as Ee,LZ as Fe,k9 as Ge,w9 as He,e8 as Ie,$7 as Je,_6 as Ke,TZ as Le,d9 as Me,kF as Ne,u9 as Oe,wF as Pe,SP as Qe,s9 as Re,$Y as Se,G7 as Te,ZY as Ue,JY as Ve,pF as We,WY as Xe,Q7 as Ye,uF as Ze,lF as _e,B7 as $e,YY as af,jY as bf,j$ as cf,zY as df,oF as ef,F7 as ff,g8 as gf,D6 as hf,E1 as if,f8 as jf,b1 as kf,x$ as lf,V8 as mf,PB as nf,NB as of,hM as pf,i1 as qf,NS as rf,_B as sf,rW as tf,eW as uf,Z2 as vf,CB as wf,SB as xf,EB as yf,RB as zf,wB as Af,fB as Bf,aS as Cf,qB as Df,U8 as Ef,J2 as Ff,W2 as Gf,Y2 as Hf,O8 as If,j3 as Jf,iB as Kf,sB as Lf,u as Mf,F3 as Nf,h4 as Of,UN as Pf,ON as Qf,DN as Rf,KN as Sf,UG as Tf,y5 as Uf,LG as Vf,IN as Wf,KG as Xf,c0 as Yf,i3 as Zf,TG as _f,nB as $f,EE as ag,B2 as bg,x1 as cg,C1 as dg,V2 as eg,D2 as fg,ZH as gg,H8 as hg,K8 as ig,L2 as jg,WV as kg,YV as lg,T8 as mg,GV as ng,h5 as og,iD as pg,n5 as qg,o5 as rg,g_ as sg,dG as tg,sG as ug,B6 as vg,$$ as wg,r_ as xg,oG as yg,aG as zg,KW as Ag,$3 as Bg,TW as Cg,ux as Dg,rx as Eg,ex as Fg,UM as Gg,gW as Hg,dW as Ig,HM as Jg,mW as Kg,PM as Lg,Z6 as Mg,uW as Ng,zB as Og,z8 as Pg,X8 as Qg,_A as Rg,IA as Sg,xA as Tg,B1 as Ug,E as Vg,q0 as Wg,V6 as Xg,l2 as Yg,bV as Zg,c2 as _g,s2 as $g,R8 as ah,U6 as bh,k8 as ch,n2 as dh,gV as eh,yV as fh,$9 as gh,J9 as hh,Y9 as ih,V9 as jh,F9 as kh,U9 as lh,p8 as mh,uV as nh,z0 as oh,I9 as ph,HZ as qh,E9 as rh};
|
|
115
|
+
)`,`CREATE INDEX IF NOT EXISTS "${Z}_subject_created_at_idx" ON "${Z}"("subject", "created_at")`,`CREATE INDEX IF NOT EXISTS "${Z}_status_deadline_at_idx" ON "${Z}"("status", "deadline_at")`]}var rB=191,eB=30000;class H8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class K8 extends Error{code;data;constructor($,Z={}){super($,Z.cause===void 0?void 0:{cause:Z.cause});this.name="RunFailure",this.code=Z.code,this.data=Z.data}}class L2{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=N1(oB(),$),this.store=YH(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make(j3);return this.ownFeed??=new j3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){JV("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;JV("id",Z);let J=await this.store.create({id:Z,kind:$.kind,subject:$.subject??null,owner:$.owner??null,meta:$.meta??null,status:$.start?"running":"pending",deadlineMs:$.deadline===void 0||$.deadline===null?null:XZ($.deadline)});return await this.publish(J),J}async get($){return await this.store.get($)}list($={}){return this.store.list($)}start($){return this.change($,["pending"],{status:"running"})}async progress($,Z){return WH(Z),this.change($,x1,{status:"running",progress:Z})}complete($,Z){return this.change($,x1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,x1,{status:"failed",error:ZV(Z)})}cancel($,Z){return this.change($,x1,{status:"cancelled",error:{message:Z??"The run was cancelled.",code:"cancelled"}})}async execute($,Z){let J=this.feed.subscribe(this.channel($));try{await J.ready();let W=await this.start($)??await this.store.get($);if(!W)throw new H8($);if(C1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(G)=>{if(Y.signal.aborted)return;await this.progress($,G)}},X;try{let G=await Z(z);X=await this.complete($,G)}catch(G){if(!(G instanceof K8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,G);X=await this.change($,x1,{status:"failed",error:G instanceof K8?ZV(G):{message:"The run failed.",code:"error"}})}finally{Y.abort(),J.close(),await j}return X??await this.store.get($)??W}finally{J.close()}}async wait($,Z={}){let{signal:J}=Z;J?.throwIfAborted();let W=Z.timeout===void 0?1/0:Date.now()+XZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new H8($);let z=null;for(;;){if(C1(j.status))return j;J?.throwIfAborted();let X=await this.untilDeadline(j);if(X!==null&&X<=0){j=await this.expire($)??await this.store.get($)??j;continue}let G=W-Date.now();if(G<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await $V(z,Math.min(G,X??1/0,eB),J))z=null;j=await this.store.get($)??j}}finally{Y.close()}}async*subscribe($,Z={}){let J=this.feed.subscribe(this.channel($),{signal:Z.signal});try{await J.ready();let W=await this.store.get($);if(!W)throw new H8($);if(yield W,C1(W.status))return;for await(let Y of J){let j=JH(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,C1(W.status))return}}finally{J.close()}}stream($,Z,J={}){return this.feed.stream($,this.channel(Z),J)}cursor($){return this.feed.cursor(this.channel($))}async sweep(){let $=await this.now(),Z=0;for(let J of await this.store.overdue($,this.config.sweepLimit))if(await this.expire(J.id))Z++;return Z}async prune($){let Z=XZ($);return await this.store.prune?.(Z)??0}async close(){await this.ownFeed?.close(),this.ownFeed=null}now(){return this.store.now?this.store.now():Promise.resolve(Date.now())}async untilDeadline($){if($.deadlineAt===null)return null;return $.deadlineAt-await this.now()}async expire($){let Z=await this.store.get($);if(!Z||C1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,x1,{status:"timed_out",error:{message:"The run passed its deadline.",code:"deadline"}})}async watch($,Z,J,W){let Y=new Promise((z)=>{if(W.signal.aborted)z("ended");W.signal.addEventListener("abort",()=>z("ended"),{once:!0})}),j=null;try{for(;;){if(W.signal.aborted)return;if(C1(Z.status)){W.abort();return}let z=await this.untilDeadline(Z);if(z!==null&&z<=0){Z=await this.expire($)??await this.store.get($)??Z;continue}j??=J.next();let X=await Promise.race([Y,$V(j,Math.min(z??1/0,eB))]);if(X==="ended")return;if(X)j=null;Z=await this.store.get($)??Z}}catch(z){console.error(`[gemi] Run ${$}: could not follow the run for a cancel.`,z)}}async change($,Z,J){let W=await this.store.transition($,Z,J);if(W)await this.publish(W);return W}async publish($){try{await this.feed.publish(this.channel($.id),$)}catch(Z){console.error(`[gemi] Run ${$.id}: could not publish its change.`,Z)}}}function $V($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>G(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},G=(Q)=>{X(),W(Q)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>G(!0),()=>G(!0))})}function JH($,Z){if($.type!=="change")return null;let J=$.data;if(!J||typeof J!=="object"||J.id!==Z||typeof J.version!=="number")return null;return J}function ZV($){if(typeof $==="string")return{message:$};if($ instanceof K8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function JV($,Z){if(typeof Z!=="string"||Z===""||Z.length>rB)throw TypeError(`A run's ${$} is a string of 1 to ${rB} characters; got ${JSON.stringify(Z)}.`)}function WH($){let{fraction:Z}=$;if(Z!==void 0&&!(Number.isFinite(Z)&&Z>=0&&Z<=1))throw RangeError(`A run's progress fraction is between 0 and 1; got ${Z}.`)}function YH($,Z){if($==="memory")return new V2;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The runs store needs the application it belongs to, and this RunManager was built without one. Pass { application }.");if($==="database"){let J=Z.make(f1).connection();return new D2(J)}return $(Z)}if(typeof $==="string")throw Error(`Unknown runs store "${$}". The runs slice's store is "memory", "database", a RunStore, or a function returning one.`);return $}class WV extends m{static getFacadeAccessor(){return L2}static create($){return this.getFacadeRoot().create($)}static get($){return this.getFacadeRoot().get($)}static list($){return this.getFacadeRoot().list($)}static start($){return this.getFacadeRoot().start($)}static progress($,Z){return this.getFacadeRoot().progress($,Z)}static complete($,Z){return this.getFacadeRoot().complete($,Z)}static fail($,Z){return this.getFacadeRoot().fail($,Z)}static cancel($,Z){return this.getFacadeRoot().cancel($,Z)}static execute($,Z){return this.getFacadeRoot().execute($,Z)}static wait($,Z){return this.getFacadeRoot().wait($,Z)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}static cursor($){return this.getFacadeRoot().cursor($)}static channel($){return this.getFacadeRoot().channel($)}static sweep(){return this.getFacadeRoot().sweep()}static prune($){return this.getFacadeRoot().prune($)}}class YV extends m{static getFacadeAccessor(){return j$}static enabled($){return this.getFacadeRoot().enabled($)}static all(){return this.getFacadeRoot().forClient()}static explain($){return this.getFacadeRoot().explain($)}static for($){return this.getFacadeRoot().for($)}static list(){return this.getFacadeRoot().list()}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class K2{value;constructor($){this.value=$}}var jH=/^[A-Za-z_][A-Za-z0-9_$]*$/;function zH($){let Z=["SET TRANSACTION READ ONLY"],J=[["statementTimeoutMs","statement_timeout"],["lockTimeoutMs","lock_timeout"],["idleInTransactionTimeoutMs","idle_in_transaction_session_timeout"]];for(let[W,Y]of J){let j=$[W];if(j===void 0)continue;if(typeof j!=="number"||!Number.isInteger(j)||j<=0)throw TypeError(`DB.readOnly: ${W} must be a positive whole number of milliseconds, got ${String(j)}.`);Z.push(`SET LOCAL ${Y} = ${j}`)}if($.role!==void 0){if(typeof $.role!=="string"||!jH.test($.role))throw TypeError(`DB.readOnly: the role "${String($.role)}" is not a plain identifier. Use letters, digits, _ and $.`);Z.push(`SET LOCAL ROLE "${$.role}"`)}return Z}class T8{bound;constructor($){this.bound=$}get name(){return this.bound??w1()}get sql(){return this.connection().sql}get dialect(){return this.connection().dialect}async query($){return await this.run($,"query")}async execute($){let Z=await this.run($,"execute");return Number(Z?.count??0)}async transaction($){let Z=this.name,J=this.connection(Z);return H2(J.sql,(W)=>M2(Z,()=>$(W)),{slowTransactionThreshold:J.config.slowTransactionThreshold,connection:Z})}async readOnly($,Z){let J=typeof $==="function"?{}:$,W=typeof $==="function"?$:Z;if(typeof W!=="function")throw TypeError("DB.readOnly needs a callback: readOnly(options, async (tx) => ...).");let Y=zH(J??{}),j=this.name,z=this.connection(j);if(z.dialect!=="postgres")throw Error(`DB.readOnly is supported on Postgres only, and the "${j}" connection is ${z.dialect}.`);if(s0()!==void 0)throw Error("DB.readOnly cannot run inside a transaction: SET TRANSACTION READ ONLY has to be the first statement of its own transaction. Call it outside the transaction.");try{await H2(z.sql,async(X)=>{for(let Q of Y)await X.unsafe(Q);let G=await M2(j,()=>W(X));throw new K2(G)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof K2)return X.value;throw X}throw Error("DB.readOnly: the transaction committed, which it never should.")}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-sqqby94y.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=XV($,zV(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=s0();if($===void 0)return;return w1()===this.name?$:void 0}connection($=this.name){return jV($),H(f1).connection($)}}var GZ=new T8;class GV extends m{static getFacadeAccessor(){return f1}static connection($){return new T8($)}static get sql(){return GZ.sql}static get dialect(){return GZ.dialect}static query($){return GZ.query($)}static execute($){return GZ.execute($)}static transaction($){return GZ.transaction($)}static readOnly($,Z){return GZ.readOnly($,Z)}static schema(){return GZ.schema()}static close(){return this.getFacadeRoot().close()}}export{F1 as me,DV as ne,e0 as oe,Q3 as pe,x8 as qe,FZ as re,V3 as se,C0 as te,Q6 as ue,a8 as ve,t8 as we,R9 as xe,Y$ as ye,O1 as ze,k$ as Ae,J0 as Be,Q9 as Ce,LZ as De,k9 as Ee,w9 as Fe,e8 as Ge,$7 as He,_6 as Ie,TZ as Je,d9 as Ke,kF as Le,u9 as Me,wF as Ne,SP as Oe,s9 as Pe,$Y as Qe,G7 as Re,ZY as Se,JY as Te,pF as Ue,WY as Ve,Q7 as We,uF as Xe,lF as Ye,B7 as Ze,YY as _e,jY as $e,j$ as af,zY as bf,oF as cf,F7 as df,g8 as ef,D6 as ff,E1 as gf,f8 as hf,b1 as if,x$ as jf,V8 as kf,PB as lf,NB as mf,hM as nf,i1 as of,NS as pf,_B as qf,rW as rf,eW as sf,Z2 as tf,CB as uf,SB as vf,EB as wf,RB as xf,wB as yf,fB as zf,aS as Af,qB as Bf,U8 as Cf,J2 as Df,W2 as Ef,Y2 as Ff,O8 as Gf,j3 as Hf,iB as If,sB as Jf,u as Kf,F3 as Lf,h4 as Mf,UN as Nf,ON as Of,DN as Pf,KN as Qf,UG as Rf,y5 as Sf,LG as Tf,IN as Uf,KG as Vf,c0 as Wf,i3 as Xf,TG as Yf,nB as Zf,EE as _f,B2 as $f,x1 as ag,C1 as bg,V2 as cg,D2 as dg,ZH as eg,H8 as fg,K8 as gg,L2 as hg,WV as ig,YV as jg,T8 as kg,GV as lg,h5 as mg,iD as ng,n5 as og,o5 as pg,g_ as qg,dG as rg,sG as sg,B6 as tg,$$ as ug,r_ as vg,oG as wg,aG as xg,KW as yg,$3 as zg,TW as Ag,ux as Bg,rx as Cg,ex as Dg,UM as Eg,gW as Fg,dW as Gg,HM as Hg,mW as Ig,PM as Jg,Z6 as Kg,uW as Lg,zB as Mg,z8 as Ng,X8 as Og,_A as Pg,IA as Qg,xA as Rg,B1 as Sg,E as Tg,q0 as Ug,V6 as Vg,l2 as Wg,bV as Xg,c2 as Yg,s2 as Zg,R8 as _g,U6 as $g,k8 as ah,n2 as bh,gV as ch,yV as dh,$9 as eh,J9 as fh,Y9 as gh,V9 as hh,F9 as ih,U9 as jh,p8 as kh,uV as lh,z0 as mh,I9 as nh,HZ as oh,E9 as ph};
|
|
116
116
|
|
|
117
|
-
//# debugId=
|
|
117
|
+
//# debugId=5335683D24FDA44C64756E2164756E21
|