gemi 0.174.0 → 0.175.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/{chunk-jy4hy8d4.js → chunk-1670g2gy.js} +1 -1
- package/dist/{chunk-d6x90qty.js → chunk-k036qfj0.js} +25 -25
- package/dist/{chunk-d6x90qty.js.map → chunk-k036qfj0.js.map} +4 -4
- package/dist/{chunk-hz37kkwy.js → chunk-wf81wenb.js} +2 -2
- package/dist/{chunk-hz37kkwy.js.map → chunk-wf81wenb.js.map} +1 -1
- package/dist/{chunk-a8c7fe9s.js → chunk-xnkx1kz8.js} +1 -1
- package/dist/{chunk-48pgk5j8.js → chunk-yc2w8x64.js} +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +6 -0
- package/dist/services/router/config.d.ts.map +1 -1
- package/package.json +1 -1
- /package/dist/{chunk-jy4hy8d4.js.map → chunk-1670g2gy.js.map} +0 -0
- /package/dist/{chunk-a8c7fe9s.js.map → chunk-xnkx1kz8.js.map} +0 -0
- /package/dist/{chunk-48pgk5j8.js.map → chunk-yc2w8x64.js.map} +0 -0
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{mh as AK}from"./chunk-hr9twa8v.js";import{Gh as CK}from"./chunk-m0nvysa5.js";import{Fi as S1,Hh as Q3,Ji as xQ,Ki as ZZ,Lh as AG,Li as JZ,Mh as d5,Mi as jK,Nh as u5,Oh as T8,Oi as zK,Ph as D8,Sh as O8,Th as L8,Uh as tZ,Vh as a4,Wh as RY,Xh as F5,Yh as d,ci as C,di as p8,ei as FZ,fi as N8,gi as B6,ii as b$,ji as m,ki as d4,si as V6,yi as F6}from"./chunk-r22svpab.js";import{Ri as $$,Si as z0,Ti as J$,Ui as i5}from"./chunk-4dnr1vg7.js";import{$i as r4,Vi as t$,Wi as kY,_i as b2,aj as T}from"./chunk-4hhvaa7a.js";import{dj as UQ,gj as u3}from"./chunk-6srzhv88.js";import{kj as c2,nj as tG}from"./chunk-0v46hne6.js";import{Fj as E$,Kj as Z$}from"./chunk-rjsd8f8q.js";import{Yj as aX}from"./chunk-vzz91xsm.js";import{Zj as WZ,ak as aG}from"./chunk-d7a79eqm.js";import{bk as P1}from"./chunk-ksgeqtcv.js";import{ck as X6,dk as l0,ek as E1,fk as eY,gk as xK,ik as uZ,jk as WK,sk as $5}from"./chunk-6rh3brnr.js";import{Hk as b1}from"./chunk-vpmbynke.js";import{Mk as xG,Rk as IY}from"./chunk-9bcsfce4.js";import{Yk as _Y,bl as c}from"./chunk-9zcsshgb.js";import{cl as rZ,fl as M}from"./chunk-bsnp7h5w.js";import{nl as HY}from"./chunk-ewf24h4z.js";import{ol as XK}from"./chunk-ykd2ayw8.js";import{yl as UY}from"./chunk-7gc1jp2z.js";import{Bl as SG,zl as j8}from"./chunk-sjg5g92s.js";import{Gl as t4}from"./chunk-xe126csw.js";function Z6($){return typeof $==="function"&&$.prototype!==void 0}var Y5=Symbol.for("gemi.HttpResponse"),wK=new Set([301,302,303,307,308]);class G1{kind;body;status;headers;[Y5]=!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 W5(J,"json"),new G1("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 G1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!wK.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 G1("empty",void 0,J,Y)}static noContent($={}){return new G1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return W5(J,"text"),new G1("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 W5($,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&&$[Y5]===!0}function qK($,Z,J={}){return G1.error($,Z,J)}function o0($){return typeof $==="string"?[$]:$}function J6($,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 yK($){return"total"in $&&"partial"in $&&"body"in $}function j5(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function W3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":L8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function vK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(yK($))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 M8($,Z){if($ instanceof Response)return $;if(!$)return j5();let J=await vK($),{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 j5()}let{range:Q}=Z;if(Q){if(z<=0)return W3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=D8(Q,z);if(!K)return W3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),G)V.set("Content-Range",O8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",J6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[K,F]of Object.entries(J.extraHeaders))V.set(K,F);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:V})}return new Response(W,{status:B,headers:V})}class QZ extends z0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var z5={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function j3($){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 z5)))return Math.floor(Number(J[1])*(z5[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var Y3=new WeakMap;function Q5($){return Y3.has($)}function G5($){return Y3.get($)?.limit??null}function K5($){let Z=Y3.get($);return Z?Z.read>Z.limit:!1}function gK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function P8($,Z){let J=gK($);if(J!==null&&J>Z)throw new QZ(Z)}function W6($,Z,J={}){let W=Y3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};Y3.set($,Y),hK($,Y)}if(J.checkDeclared!==!1)P8($,Z)}function mK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function H8($,Z){if(Z.stream!==void 0)return Z.stream;let J=mK($);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 QZ(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 XZ($,Z){if(P8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=H8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function X5($){return $.headers.get("Content-Type")??""}function hK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>H8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>XZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await XZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await XZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await XZ($,Z)))}),J("blob",{value:async()=>new Blob([await XZ($,Z)],{type:X5($)})}),J("formData",{value:async()=>new Response(await XZ($,Z),{headers:{"Content-Type":X5($)}}).formData()}),J("clone",{value:()=>{P8($,Z.limit);let W=H8($,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 B5($){return Z6($)}class o{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(!B5(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(B5(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=o0($),this}}class U5{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=o0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of F5($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(K5($.rawRequest))throw new QZ(G5($.rawRequest));throw J}}}class D5{constructor(...$){return new o(...$)}}class O5 extends o{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=T8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(r1(Y))return Y;return await M8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof N8)return W3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class L5{constructor(...$){return new O5(...$)}}class M5{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new o("GET",$,"list"),post:new o("POST",$,"store")},this.second={get:new o("GET",$,"show"),put:new o("PUT",$,"update"),delete:new o("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 o("GET",$,Z)}post($,Z){return new o("POST",$,Z)}put($,Z){return new o("PUT",$,Z)}patch($,Z){return new o("PATCH",$,Z)}delete($,Z){return new o("DELETE",$,Z)}resource($){return new M5($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${V5($)}.`);return pK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${V5($)}.`);return cK($)}file($,Z){return new D5("GET",$,Z)}stream($,Z){return new L5("GET",$,Z)}proxy($,Z={}){return new U5($,Z)}}function V5($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function pK($){let Z={stream:new o("POST",$,"stream"),attach:new o("POST",$,"attach"),stop:new o("POST",$,"stop"),upload:new o("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/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);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function cK($){let Z={start:new o("POST",$,"voiceStart"),update:new o("PATCH",$,"voiceUpdate"),end:new o("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 t1="access_token";function S$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Y6($,Z){let J=S$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var dK=/^[A-Za-z0-9_-]+$/,uK=/^:[A-Za-z_][A-Za-z0-9_]*$/,H5=/^[A-Za-z0-9_-]{1,128}$/,lK=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function P5($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function GZ($){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(uK.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(!dK.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 z3($,Z={}){let J=GZ($),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 Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!H5.test(Q))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 Q}).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 _8($){if(GZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function T5($){if(typeof $!=="string"||$.length===0||$.length>64||!lK.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function N5($,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(":")&&H5.test(W[j]))}var U0="user";function KZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return z3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class j6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return W6(this.req.rawRequest,j3(Z)),{}}}function iK($){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 sK={"body-limit":j6};class e1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:j3($.bodyLimit)}get aliases(){return{...sK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!Q5($))W6($,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 iK($).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:_5(z)})}}else if(Z6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:_5(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 nK(W.slice(j+1)),z}return Y})()}}function _5($){return $?.runsOnRefusal===!0}async function nK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class z6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...o0($)],this}events(...$){return this}}class A5{static __brand="ChannelRouter";channels={};public(){return new z6("public")}private($){return new z6("private",$)}async authorize($,Z,J={},W={}){try{tK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!S5(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=z3(Z,J??{})}catch(Q){if(Q instanceof u)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return T.exit(()=>X6.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await M(e1).runMiddleware(Y.middlewares);if(Z===U0){let G=await I5(X);if(!G)return{ok:!1,code:"denied"};if(j=KZ(G),Y.visibility==="private"&&Y.authorizer){if(await x5(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 x5(Y.authorizer,X,z):await I5(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(rK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function oK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;E5(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 S5($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function I5($){if(!T.getStore().user&&S$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function x5($,Z,J){if(aK($))return new $().authorize(Z,J);return $(Z,J)}function aK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function rK($){return $?.kind===$$||Z$($)||E$($)}var C5=new WeakSet;function tK($){if(C5.has($))return;E5($),C5.add($)}function E5($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!S5(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=GZ(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(eK(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 eK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class I8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class Q6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class x8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function $B($){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 ZB($,Z){let J=$B($);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 b5{static __brand="McpRouter";routes={};scopes;param($){return new I8($.as,$.input,$.bind)}fromTool($,Z={}){return new x8($,Z)}fromApiRoute($,Z,J){return new Q6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let V={},K=new Map;for(let F of B){let{name:D,casing:U,description:O,params:L,files:P,...H}=Y[F],I=D??(U?ZB(W,U):W);if(K.has(I))throw Error(`${G}: the audiences "${K.get(I)}" and "${F}" are both named "${I}". Give one its own name or casing.`);K.set(I,F);let S=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof S!=="string")throw Error(`${G}: the audience "${F}" has no description, and there is no shared one.`);let A={...Q,...H,description:S};if(z||L)A.params={...z,...L};if(X||P)A.files={...X,...P};V[I]=new Q6($,Z,A)}return V}}function D0($,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 C8 extends z0{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 C1{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 C8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new C8($,Z)}}class R5{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 C1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=o0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function A8($,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[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);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",J6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class f5{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=o0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function k5($,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 w5{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=k5(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=o0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class q5{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends A1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends A1{routes=J??{}}}else this.children=class extends A1{routes=Z},this.handler=()=>({})}async run($,Z){let J=k5(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=o0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class A1{middlewares=[];featureGates=[];routes={};view($,Z){return new w5($,Z)}file($){return new f5($)}redirect($){return new R5($)}layout($,Z,J){return new q5($,Z,J)}}function JB($){return $}function WB(){return{aliases:{},global:[],bodyLimit:null}}var K1="redirect";function B1($,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 BZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function YB($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(M(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function jB($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function G6($,Z){let J=Z||M(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=YB($,!W);if(W||!jB(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(K1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class y5 extends Z0{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await Y6(M(E),J);if(!W)throw new b$({redirectTo:G6(J,$)});return Z.setUser(W),{}}}var E8="gemi_same_site",S8="private, no-cache, no-store, max-age=0, must-revalidate";class K6 extends Z0{run(){let $=T.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(E8))return{};if(S$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(E8,"1"),new v5(`${W.pathname}${W.search}`)}}class v5 extends z0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=zB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":S8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":S8}},viewData:{status:200,data:{},headers:{"Cache-Control":S8},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 zB($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class g5 extends Z0{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 m5={"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 h5 extends Z0{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={...m5,...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={...m5,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var XB="Rate limit exceeded";class W$ extends z0{result;retryAfter;constructor($,Z=XB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?b8($):{}};this.payload={api:{status:429,data:{error:{...J$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function b8($){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 V1{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(p5("window",W),p5("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 W$(W,typeof J==="function"?J(W):J);return W}}function p5($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as R8}from"net";function R$($){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 R8(j)===6?j:null}if(R8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&R8(J[1])===4?J[1]:null}class l5 extends Z0{async run($,Z){let J=QB();if(!J)return{};let W=await J.consume(this.key(),{limit:c5($)??this.config.limit,window:c5(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(b8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new W$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=d5(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${VZ(this.req)}:${this.req.routePath??"*"}`}}function QB(){try{let $=M();return $.bound(V1)?$.make(V1):null}catch{return null}}function VZ($){let Z=u5($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return R$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function c5($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class s5 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new f8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new f8;return{}}}class f8 extends z0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:i5("csrf","Invalid CSRF token",403)}},view:{}}}class n5{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class o5{all($,Z){return!0}}class k8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new FZ:new B6}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 Z0{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 FZ:$ instanceof B6}}function GB($){return new k8($)}async function U6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await NB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return TB(z,Z,J,$.url)}async function TB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new F6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function NB($){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 D6($){return new TextDecoder("utf-8").decode($)}var _B={"&":"&","<":"<",">":">",'"':""","'":"'"};function f$($){return $.replace(/[&<>"']/g,(Z)=>_B[Z])}var IB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function w8($){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 IB[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 q8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function a5($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(w8($.slice(W)));return}if(Y>W)Z.text(w8($.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 Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(q8($.slice(Y+2,j).trim())),W=j+1}else{let j=xB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=q8(z.slice(0,Q));if(G){if(Z.open(G,CB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function xB($,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 CB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[q8(W[1])]=w8(W[2]??W[3]??"");return Z}class X0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var Z2="http://www.sitemaps.org/schemas/sitemap/0.9",AB="http://www.w3.org/1999/xhtml",g8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
-
`,
|
|
4
|
-
`,
|
|
5
|
-
`,k$=50000,
|
|
6
|
-
`}function fB($){let Z=$.maxUrls??k$,J=$.maxBytes??
|
|
7
|
-
`}return`${g8}<sitemapindex xmlns="${
|
|
2
|
+
import{mh as AK}from"./chunk-hr9twa8v.js";import{Gh as CK}from"./chunk-m0nvysa5.js";import{Fi as b1,Hh as G3,Ji as CQ,Ki as ZZ,Lh as AG,Li as JZ,Mh as u5,Mi as jK,Nh as l5,Oh as T8,Oi as zK,Ph as D8,Sh as O8,Th as L8,Uh as tZ,Vh as a4,Wh as fY,Xh as U5,Yh as d,ci as C,di as p8,ei as FZ,fi as N8,gi as B6,ii as b$,ji as m,ki as d4,si as V6,yi as F6}from"./chunk-r22svpab.js";import{Ri as $$,Si as z0,Ti as J$,Ui as s5}from"./chunk-4dnr1vg7.js";import{$i as r4,Vi as t$,Wi as wY,_i as Rj,aj as T}from"./chunk-4hhvaa7a.js";import{dj as DQ,gj as l3}from"./chunk-6srzhv88.js";import{kj as dj,nj as tG}from"./chunk-0v46hne6.js";import{Fj as E$,Kj as Z$}from"./chunk-rjsd8f8q.js";import{Yj as rX}from"./chunk-vzz91xsm.js";import{Zj as WZ,ak as aG}from"./chunk-d7a79eqm.js";import{bk as T1}from"./chunk-ksgeqtcv.js";import{ck as X6,dk as l0,ek as R1,fk as $5,gk as xK,ik as uZ,jk as WK,sk as Z5}from"./chunk-6rh3brnr.js";import{Hk as f1}from"./chunk-vpmbynke.js";import{Mk as IY,Rk as xY}from"./chunk-9bcsfce4.js";import{Yk as _Y,bl as c}from"./chunk-9zcsshgb.js";import{cl as rZ,fl as M}from"./chunk-bsnp7h5w.js";import{nl as HY}from"./chunk-ewf24h4z.js";import{ol as XK}from"./chunk-ykd2ayw8.js";import{yl as UY}from"./chunk-7gc1jp2z.js";import{Bl as SG,zl as j8}from"./chunk-sjg5g92s.js";import{Gl as t4}from"./chunk-xe126csw.js";function Z6($){return typeof $==="function"&&$.prototype!==void 0}var j5=Symbol.for("gemi.HttpResponse"),wK=new Set([301,302,303,307,308]);class K1{kind;body;status;headers;[j5]=!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 Y5(J,"json"),new K1("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 K1.json({error:Z},{...J,status:$})}static redirect($,Z={}){let J=Z.status??303;if(!wK.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 K1("empty",void 0,J,Y)}static noContent($={}){return new K1("empty",null,204,new Headers($.headers))}static text($,Z={}){let J=Z.status??200;return Y5(J,"text"),new K1("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 Y5($,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&&$[j5]===!0}function qK($,Z,J={}){return K1.error($,Z,J)}function a0($){return typeof $==="string"?[$]:$}function J6($,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 yK($){return"total"in $&&"partial"in $&&"body"in $}function z5(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function Y3($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":L8($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function vK($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(yK($))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 M8($,Z){if($ instanceof Response)return $;if(!$)return z5();let J=await vK($),{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 z5()}let{range:Q}=Z;if(Q){if(z<=0)return Y3(Math.max(z,0));if(!X){if(W instanceof Blob){let K=D8(Q,z);if(!K)return Y3(z);W=W.slice(K.start,K.end+1),Y=K.start,j=K.end,X=!0}}}let G=Boolean(Q)&&X,B=G?206:J.status,V=new Headers;if(V.set("Accept-Ranges","bytes"),V.set("Content-Type",J.type||"application/octet-stream"),V.set("X-Content-Type-Options","nosniff"),G)V.set("Content-Range",O8(Y,j,z)),V.set("Content-Length",String(j-Y+1));else if(z>=0)V.set("Content-Length",String(z));if(J.name)V.set("Content-Disposition",J6(J.name,J.download));if(J.etag)V.set("ETag",J.etag);if(J.lastModified)V.set("Last-Modified",J.lastModified.toUTCString());for(let[K,F]of Object.entries(J.extraHeaders))V.set(K,F);if((Z.method??"GET").toUpperCase()==="HEAD"){if(W&&"cancel"in W&&typeof W.cancel==="function")await W.cancel();return new Response(null,{status:B,headers:V})}return new Response(W,{status:B,headers:V})}class QZ extends z0{limit;constructor($){super("The request body is too large.",{status:413});this.limit=$}}var X5={b:1,k:1024,kb:1024,m:1048576,mb:1048576,g:1073741824,gb:1073741824};function z3($){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 X5)))return Math.floor(Number(J[1])*(X5[J[2]]??1))}throw Error(`Invalid body limit ${JSON.stringify($)}. Use a byte count or a size such as "64kb", "1mb" or "none".`)}var j3=new WeakMap;function G5($){return j3.has($)}function K5($){return j3.get($)?.limit??null}function B5($){let Z=j3.get($);return Z?Z.read>Z.limit:!1}function gK($){let Z=$.headers.get("Content-Length");if(Z===null||!/^\s*\d+\s*$/.test(Z))return null;return Number(Z)}function P8($,Z){let J=gK($);if(J!==null&&J>Z)throw new QZ(Z)}function W6($,Z,J={}){let W=j3.get($);if(W)W.limit=Z;else{let Y={limit:Z,read:0,stream:void 0,used:!1};j3.set($,Y),hK($,Y)}if(J.checkDeclared!==!1)P8($,Z)}function mK($){return Reflect.get(Object.getPrototypeOf($),"body",$)??null}function H8($,Z){if(Z.stream!==void 0)return Z.stream;let J=mK($);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 QZ(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 XZ($,Z){if(P8($,Z.limit),Z.used||Z.stream?.locked)throw TypeError("Body already used");Z.used=!0;let J=H8($,Z);if(!J)return new Uint8Array(0);let W=J.getReader(),Y=[],j=0;for(;;){let{done:Q,value:G}=await W.read();if(Q)break;Y.push(G),j+=G.byteLength}let z=new Uint8Array(j),X=0;for(let Q of Y)z.set(Q,X),X+=Q.byteLength;return z}function Q5($){return $.headers.get("Content-Type")??""}function hK($,Z){let J=(W,Y)=>Object.defineProperty($,W,{configurable:!0,...Y});J("body",{get:()=>H8($,Z)}),J("bodyUsed",{get:()=>Z.used||Boolean(Z.stream?.locked)||Reflect.get(Object.getPrototypeOf($),"bodyUsed",$)}),J("bytes",{value:()=>XZ($,Z)}),J("arrayBuffer",{value:async()=>{let W=await XZ($,Z);return W.buffer.slice(W.byteOffset,W.byteOffset+W.byteLength)}}),J("text",{value:async()=>new TextDecoder().decode(await XZ($,Z))}),J("json",{value:async()=>JSON.parse(new TextDecoder().decode(await XZ($,Z)))}),J("blob",{value:async()=>new Blob([await XZ($,Z)],{type:Q5($)})}),J("formData",{value:async()=>new Response(await XZ($,Z),{headers:{"Content-Type":Q5($)}}).formData()}),J("clone",{value:()=>{P8($,Z.limit);let W=H8($,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 V5($){return Z6($)}class o{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(!V5(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(V5(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=a0($),this}}class D5{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=a0($),this}async run(){let $=new C,Z=$.headers.toJSON();for(let J of U5($.rawRequest))delete Z[J];try{return await fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}catch(J){if(B5($.rawRequest))throw new QZ(K5($.rawRequest));throw J}}}class O5{constructor(...$){return new o(...$)}}class L5 extends o{__internal_brand="StreamHandler";async run($){let Z=T.getStore(),J=Z?.req?.rawRequest,W=T8(J?.headers.get("Range"));if(Z)Z.rangeRequest=W;try{let Y=await super.run($);if(r1(Y))return Y;return await M8(Y,{range:W,method:J?.method})}catch(Y){if(Y instanceof N8)return Y3(Y.total);throw Y}finally{if(Z)Z.rangeRequest=null}}}class M5{constructor(...$){return new L5(...$)}}class H5{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new o("GET",$,"list"),post:new o("POST",$,"store")},this.second={get:new o("GET",$,"show"),put:new o("PUT",$,"update"),delete:new o("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 o("GET",$,Z)}post($,Z){return new o("POST",$,Z)}put($,Z){return new o("PUT",$,Z)}patch($,Z){return new o("PATCH",$,Z)}delete($,Z){return new o("DELETE",$,Z)}resource($){return new H5($)}agent($){if($.kind!=="agent-controller")throw TypeError(`this.agent() takes an AgentController class, and got ${F5($)}.`);return pK($)}voice($){if($.kind!=="agent-controller")throw TypeError(`this.voice() takes an AgentController class, and got ${F5($)}.`);return cK($)}file($,Z){return new O5("GET",$,Z)}stream($,Z){return new M5("GET",$,Z)}proxy($,Z={}){return new D5($,Z)}}function F5($){if(typeof $==="function"&&$.name)return $.name;return typeof $}function pK($){let Z={stream:new o("POST",$,"stream"),attach:new o("POST",$,"attach"),stop:new o("POST",$,"stop"),upload:new o("POST",$,"upload")};return class extends C0{static __internal_brand="AgentRoute";static controller=$;static handlers=Z;routes={"/":Z.stream,"/attach":Z.attach,"/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);if(W.stop)Z.stop.middleware(W.stop);if(W.upload)Z.upload.middleware(W.upload);return this}}}function cK($){let Z={start:new o("POST",$,"voiceStart"),update:new o("PATCH",$,"voiceUpdate"),end:new o("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 t1="access_token";function S$($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function Y6($,Z){let J=S$(Z);if(!J)return null;return(await $.getSession(J,Z.headers.get("User-Agent")))?.user??null}var dK=/^[A-Za-z0-9_-]+$/,uK=/^:[A-Za-z_][A-Za-z0-9_]*$/,P5=/^[A-Za-z0-9_-]{1,128}$/,lK=/^[A-Za-z0-9_.:-]+$/;class u extends Error{constructor($){super($);this.name="InvalidChannelError"}}function T5($){return typeof $==="object"&&$!==null&&typeof $.topic==="string"}function GZ($){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(uK.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(!dK.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 X3($,Z={}){let J=GZ($),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 Q=typeof X==="number"&&Number.isFinite(X)?String(X):X;if(typeof Q!=="string"||!P5.test(Q))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 Q}).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 _8($){if(GZ($).some((J)=>J.startsWith(":")))throw new u(`"${$}" is a pattern, not a topic: pass its params, as in Broadcast.to("${$}", { ... }).`);return $}function N5($){if(typeof $!=="string"||$.length===0||$.length>64||!lK.test($))throw new u(`The event name "${String($).slice(0,40)}" must be 1 to 64 letters, digits, "_", "-", "." or ":".`);return $}function _5($,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(":")&&P5.test(W[j]))}var U0="user";function KZ($){let Z=typeof $==="object"&&$!==null?$.id:$;return X3(`${U0}.:id`,{id:Z})}class Z0{req;static runsOnRefusal=!1;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}class j6 extends Z0{run($){let Z=$??this.config.limit;if(Z===void 0||Z==="")throw Error('`body-limit` needs a size, as in "body-limit:64kb".');return W6(this.req.rawRequest,z3(Z)),{}}}function iK($){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 sK={"body-limit":j6};class e1{config;static token="middleware";defaultBodyLimit;constructor($){this.config=$;this.defaultBodyLimit=$.bodyLimit===null||$.bodyLimit===void 0?null:z3($.bodyLimit)}get aliases(){return{...sK,...this.config.aliases}}applyDefaultBodyLimit($){if(this.defaultBodyLimit!==null&&!G5($))W6($,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 iK($).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:I5(z)})}}else if(Z6(Y)){let z=new Y(Z);W.push({run:z.run.bind(z),runsOnRefusal:I5(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 nK(W.slice(j+1)),z}return Y})()}}function I5($){return $?.runsOnRefusal===!0}async function nK($){for(let Z of $){if(!Z.runsOnRefusal)continue;try{await Z.run()}catch(J){console.error(J)}}}class z6{visibility;authorizer;middlewares=[];constructor($,Z){this.visibility=$;this.authorizer=Z}middleware($){return this.middlewares=[...this.middlewares,...a0($)],this}events(...$){return this}}class S5{static __brand="ChannelRouter";channels={};public(){return new z6("public")}private($){return new z6("private",$)}async authorize($,Z,J={},W={}){try{tK(this)}catch(Q){return console.error("[gemi] The channel router is invalid, so every subscription is refused.",Q),{ok:!1,code:"error"}}let Y=Object.hasOwn(this.channels,Z)?this.channels[Z]:void 0;if(!E5(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=X3(Z,J??{})}catch(Q){if(Q instanceof u)return{ok:!1,code:"invalid_params"};throw Q}let z=Object.fromEntries(Object.entries(J??{}).map(([Q,G])=>[Q,String(G)])),X=new C($,z,"api",Z);return T.exit(()=>X6.exit(()=>T.run(X,async()=>{let Q=T.getStore();try{if(Y.middlewares.length>0)await M(e1).runMiddleware(Y.middlewares);if(Z===U0){let G=await x5(X);if(!G)return{ok:!1,code:"denied"};if(j=KZ(G),Y.visibility==="private"&&Y.authorizer){if(await C5(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 C5(Y.authorizer,X,z):await x5(X)!==null)!==!0)return{ok:!1,code:"denied"}}return{ok:!0,topic:j,pattern:Z}}catch(G){if(rK(G))return{ok:!1,code:"denied"};return console.error(`[gemi] Authorizing the channel "${Z}" threw, so the subscription was refused.`,G),{ok:!1,code:"error"}}finally{Q.destroy()}},W.carried)))}}async function oK($,Z,J={},W={}){let Y=typeof $==="function"?new $:$;b5(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 E5($){let Z=$?.visibility;return typeof $==="object"&&$!==null&&Array.isArray($.middlewares)&&(Z==="public"||Z==="private")}async function x5($){if(!T.getStore().user&&S$($)===null)return null;try{return await q0.user()}catch(Z){if(Z?.name==="AuthenticationError")return null;throw Z}}function C5($,Z,J){if(aK($))return new $().authorize(Z,J);return $(Z,J)}function aK($){return typeof $==="function"&&typeof $.prototype?.authorize==="function"}function rK($){return $?.kind===$$||Z$($)||E$($)}var A5=new WeakSet;function tK($){if(A5.has($))return;b5($),A5.add($)}function b5($){let Z=Object.entries($.channels),J=[];for(let[W,Y]of Z){if(!E5(Y))throw new u(`The channel "${W}" is not declared with this.public() or this.private().`);let j=GZ(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(eK(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 eK($,Z){if($.length!==Z.length)return!1;return $.every((J,W)=>J===Z[W]||J.startsWith(":")||Z[W].startsWith(":"))}class I8{as;input;bind;__internal_brand="McpModelParam";constructor($,Z,J){this.as=$;this.input=Z;this.bind=J}}class Q6{method;url;meta;__internal_brand="McpRoute";constructor($,Z,J){this.method=$;this.url=Z;this.meta=J}}class x8{tool;meta;__internal_brand="McpTool";constructor($,Z){this.tool=$;this.meta=Z}}function $B($){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 ZB($,Z){let J=$B($);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 R5{static __brand="McpRouter";routes={};scopes;param($){return new I8($.as,$.input,$.bind)}fromTool($,Z={}){return new x8($,Z)}fromApiRoute($,Z,J){return new Q6($,Z,J)}fromApiRouteFor($,Z,J){let{name:W,audiences:Y,description:j,params:z,files:X,...Q}=J,G=`McpRouter.fromApiRouteFor("${$}", "${Z}")`,B=Object.keys(Y??{});if(B.length===0)throw Error(`${G}: declare at least one audience.`);let V={},K=new Map;for(let F of B){let{name:D,casing:U,description:O,params:L,files:P,...H}=Y[F],I=D??(U?ZB(W,U):W);if(K.has(I))throw Error(`${G}: the audiences "${K.get(I)}" and "${F}" are both named "${I}". Give one its own name or casing.`);K.set(I,F);let E=typeof O==="function"?j===void 0?void 0:O(j):O??j;if(typeof E!=="string")throw Error(`${G}: the audience "${F}" has no description, and there is no shared one.`);let S={...Q,...H,description:E};if(z||L)S.params={...z,...L};if(X||P)S.files={...X,...P};V[I]=new Q6($,Z,S)}return V}}function D0($,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 C8 extends z0{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 S1{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 C8([D0($,Y)||"/",X.toString()].filter(Boolean).join("?"),z??(j?301:307))}static external($,Z=307){throw new C8($,Z)}}class f5{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 S1.to(J,{permanent:W,status:Y}),{}}middleware($){return this.middlewares=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function A8($,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[Q,G]of Object.entries($.headers??{}))Z.set(Q,G);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",J6(Y,z));return new Response(W instanceof Blob?W.stream():W,{status:X,headers:Z})}class k5{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=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function w5($,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 q5{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=w5(await this.handler($),this.viewPath);return{[this.viewPath]:{...J,breadcrumb:{label:J?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=a0($),this}static($={}){return this.staticOptions={...$},this}feature($){return this.featureGates=[...this.featureGates,$],this}}class y5{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,J){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends E1{routes=J??{}};else if(Array.isArray(Z)){let[W,Y]=Z;this.handler=(j)=>{return new W()[Y](j)},this.children=class extends E1{routes=J??{}}}else this.children=class extends E1{routes=Z},this.handler=()=>({})}async run($,Z){let J=w5(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=a0($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class E1{middlewares=[];featureGates=[];routes={};view($,Z){return new q5($,Z)}file($){return new k5($)}redirect($){return new f5($)}layout($,Z,J){return new y5($,Z,J)}}function JB($){return $}function WB(){return{aliases:{},global:[],bodyLimit:null}}var B1="redirect";function V1($,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 BZ($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function YB($,Z=!0){let J=new URL($.rawRequest.url),W=J.pathname.replace(/\.(json|og)$/,""),[,Y,...j]=W.split("/");if(M(c).supportedLocales.includes(Y))W=`/${j.join("/")}`;return Z?`${W}${J.search}`:W}function jB($,Z){let J=(W)=>W.replace(/\/+$/,"")||"/";return J($)===J(Z)}function G6($,Z){let J=Z||M(b).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=YB($,!W);if(W||!jB(new URL(j,Y).pathname,Y.pathname))Y.searchParams.set(B1,j)}return W?Y.href:`${Y.pathname}${Y.search}`}class v5 extends Z0{async run($){let Z=T.getStore(),J=Z.req;if(Z.user)return{};let W=await Y6(M(b),J);if(!W)throw new b$({redirectTo:G6(J,$)});return Z.setUser(W),{}}}var E8="gemi_same_site",S8="private, no-cache, no-store, max-age=0, must-revalidate";class K6 extends Z0{run(){let $=T.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(E8))return{};if(S$(Z))return{};let Y=J.headers.get("Sec-Fetch-Site");if(Y&&Y!=="cross-site")return{};throw W.searchParams.set(E8,"1"),new g5(`${W.pathname}${W.search}`)}}class g5 extends z0{location;constructor($){super("Same-site bounce");this.location=$;this.name="SameSiteBounce";let Z=zB($),J={"Content-Type":"text/html; charset=utf-8","Cache-Control":S8,"Referrer-Policy":"no-referrer","X-Robots-Tag":"noindex"};this.payload={api:{status:401,data:{},headers:{"Cache-Control":S8}},viewData:{status:200,data:{},headers:{"Cache-Control":S8},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 zB($){return $.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}class m5 extends Z0{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 h5={"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 p5 extends Z0{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={...h5,...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={...h5,...this.config.origins["*"]};delete J["Access-Control-Allow-Credentials"];for(let[W,Y]of Object.entries(J))$.ctx().setHeaders(W,Y)}return{}}}var XB="Rate limit exceeded";class W$ extends z0{result;retryAfter;constructor($,Z=XB){super(Z);this.result=$;this.retryAfter=$?.retryAfter;let J={"Content-Type":"application/json",...$?b8($):{}};this.payload={api:{status:429,data:{error:{...J$("rate_limit",Z,429),...$?{retryAfter:$.retryAfter}:{}}},headers:J},view:{error:{message:Z},status:429,headers:J}}}}function b8($){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 F1{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(c5("window",W),c5("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 W$(W,typeof J==="function"?J(W):J);return W}}function c5($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}import{isIP as R8}from"net";function R$($){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 R8(j)===6?j:null}if(R8(Z))return Z;let J=/^(\d{1,3}(?:\.\d{1,3}){3}):\d{1,5}$/.exec(Z);return J&&R8(J[1])===4?J[1]:null}class i5 extends Z0{async run($,Z){let J=QB();if(!J)return{};let W=await J.consume(this.key(),{limit:d5($)??this.config.limit,window:d5(Z)??this.config.window});if(this.config.headers!==!1){let Y=this.req.ctx?.();if(Y)for(let[j,z]of Object.entries(b8(W)))Y.setHeaders(j,z)}if(!W.allowed)throw new W$(W);return{}}key(){if(this.config.key)return this.config.key(this.req);let $=u5(this.req.rawRequest);if($)return`mcp:${$.via}:${$.id}:${this.req.routePath??"*"}`;return`${VZ(this.req)}:${this.req.routePath??"*"}`}}function QB(){try{let $=M();return $.bound(F1)?$.make(F1):null}catch{return null}}function VZ($){let Z=l5($.rawRequest);if(Z!==void 0)return Z;let J=$.headers.get("x-forwarded-for");if(J){let[W]=J.split(",");if(W?.trim())return R$(W)??W.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function d5($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class n5 extends Z0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new f8;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new f8;return{}}}class f8 extends z0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:s5("csrf","Invalid CSRF token",403)}},view:{}}}class o5{policiesList={};constructor(){let $=this.register();for(let Z of $){let J=new Z;this.policiesList[Z.name]=J}}register(){return[]}}class a5{all($,Z){return!0}}class k8{options;param;refuse;answers=new WeakMap;constructor($){this.options=$;this.param=$.param,this.refuse=$.refuse??"not_found"}refusal(){return this.refuse==="forbidden"?new FZ:new B6}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 Z0{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 FZ:$ instanceof B6}}function GB($){return new k8($)}async function U6($,Z,J=!1){if(!$.body)return new Uint8Array;let[W,Y]=await NB($.body),z=W.length>=2&&W[0]===31&&W[1]===139?Y.pipeThrough(new DecompressionStream("gzip")):Y;return TB(z,Z,J,$.url)}async function TB($,Z,J,W){let Y=$.getReader(),j=[],z=0;try{for(;;){let{done:G,value:B}=await Y.read();if(G)break;if(z+B.byteLength>Z){if(!J)throw new F6(W,Z);j.push(B.subarray(0,Z-z)),z=Z;break}j.push(B),z+=B.byteLength}}finally{Y.cancel().catch(()=>{})}let X=new Uint8Array(z),Q=0;for(let G of j)X.set(G,Q),Q+=G.byteLength;return X}async function NB($){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 D6($){return new TextDecoder("utf-8").decode($)}var _B={"&":"&","<":"<",">":">",'"':""","'":"'"};function f$($){return $.replace(/[&<>"']/g,(Z)=>_B[Z])}var IB={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function w8($){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 IB[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 q8($){let Z=$.indexOf(":");return(Z===-1?$:$.slice(Z+1)).toLowerCase()}function r5($,Z){let J=$.length,W=0;while(W<J){if(Z.stopped?.())return;let Y=$.indexOf("<",W);if(Y===-1){Z.text(w8($.slice(W)));return}if(Y>W)Z.text(w8($.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 Q=$.indexOf(">",X+1);if(Q===-1)return;W=Q+1}else W=j+1}else if($[Y+1]==="/"){let j=$.indexOf(">",Y+2);if(j===-1)return;Z.close(q8($.slice(Y+2,j).trim())),W=j+1}else{let j=xB($,Y+1);if(j===-1)return;let z=$.slice(Y+1,j),X=z.endsWith("/");if(X)z=z.slice(0,-1);let Q=z.search(/[\s]|$/),G=q8(z.slice(0,Q));if(G){if(Z.open(G,CB(z.slice(Q)),X),X)Z.close(G)}W=j+1}}}function xB($,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 CB($){let Z={},J=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;for(let W of $.matchAll(J))Z[q8(W[1])]=w8(W[2]??W[3]??"");return Z}class X0 extends Error{url;status;constructor($,Z=null,J=null){super($);this.url=Z;this.status=J;this.name="SitemapError"}}var Jj="http://www.sitemaps.org/schemas/sitemap/0.9",AB="http://www.w3.org/1999/xhtml",g8=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
|
+
`,t5=`<urlset xmlns="${Jj}" xmlns:xhtml="${AB}">
|
|
4
|
+
`,e5=`</urlset>
|
|
5
|
+
`,k$=50000,Q3=52428800,$j=2048,SB=new Set(["always","hourly","daily","weekly","monthly","yearly","never"]),EB=/^\d{4}(-\d{2}(-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?)?)?$/,bB="application/xml; charset=utf-8",Zj=new TextEncoder;function m8($,Z){let J;try{J=new URL($)}catch{throw new X0(`Sitemap: ${Z} "${$}" is not an absolute URL.`)}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new X0(`Sitemap: ${Z} "${$}" is not an http(s) URL.`);let W=J.href;if(W.length>$j)throw new X0(`Sitemap: ${Z} is over ${$j} characters: "${W.slice(0,80)}\u2026".`);return W}function Wj($,Z){if($ instanceof Date){if(Number.isNaN($.getTime()))throw new X0(`Sitemap: lastmod of ${Z} is an invalid Date.`);return $.toISOString()}if(!EB.test($))throw new X0(`Sitemap: lastmod "${$}" of ${Z} is not a W3C datetime (e.g. "2026-10-07" or "2026-10-07T12:00:00Z").`);return $}function RB($){let Z=m8($.loc,"loc"),J=`<url><loc>${f$(Z)}</loc>`;if($.lastmod!=null)J+=`<lastmod>${f$(Wj($.lastmod,Z))}</lastmod>`;if($.changefreq!=null){if(!SB.has($.changefreq))throw new X0(`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 X0(`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 X0(`Sitemap: an alternate of ${Z} has no hrefLang.`);let j=m8(W.href,`alternate href of ${Z}`);J+=`<xhtml:link rel="alternate" hreflang="${f$(Y)}" href="${f$(j)}"/>`}return`${J}</url>
|
|
6
|
+
`}function fB($){let Z=$.maxUrls??k$,J=$.maxBytes??Q3;if(!Number.isInteger(Z)||Z<1||Z>k$)throw RangeError(`Sitemap: maxUrls must be an integer from 1 to ${k$}.`);if(!Number.isInteger(J)||J<1||J>Q3)throw RangeError(`Sitemap: maxBytes must be an integer from 1 to ${Q3}.`);return{maxUrls:Z,maxBytes:J}}function Yj($,Z={}){let{maxUrls:J,maxBytes:W}=fB(Z),Y=Zj.encode(g8+t5+e5).byteLength,j=[],z=[],X=Y,Q=()=>{j.push(g8+t5+z.join("")+e5),z=[],X=Y};for(let G of $){let B=RB(G),V=Zj.encode(B).byteLength;if(Y+V>W)throw new X0(`Sitemap: the entry for ${G.loc} alone is over maxBytes (${W}).`);if(z.length===J||X+V>W)Q();z.push(B),X+=V}if(z.length>0||j.length===0)Q();return j}function jj($){let Z="",J=0;for(let W of $){if(++J>k$)throw new X0(`Sitemap: an index can list at most ${k$} sitemaps.`);let Y=m8(W.loc,"sitemap loc");if(Z+=`<sitemap><loc>${f$(Y)}</loc>`,W.lastmod!=null)Z+=`<lastmod>${f$(Wj(W.lastmod,Y))}</lastmod>`;Z+=`</sitemap>
|
|
7
|
+
`}return`${g8}<sitemapindex xmlns="${Jj}">
|
|
8
8
|
${Z}</sitemapindex>
|
|
9
|
-
`}function y8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",bB);return new Response($,{status:Z,headers:W})}function kB($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function wB($,Z={}){let J=
|
|
10
|
-
`)));return
|
|
11
|
-
`}function
|
|
9
|
+
`}function y8($,Z,J){let W=new Headers(J);if(!W.has("content-type"))W.set("content-type",bB);return new Response($,{status:Z,headers:W})}function kB($){if($===null||$===void 0||$==="")return null;let Z=String($);return/^[1-9]\d{0,8}$/.test(Z)?Number(Z):NaN}function wB($,Z={}){let J=Yj($,Z),W=kB(Z.page);if(W!==null){let j=J[W-1];return j?y8(j,200,Z.headers):new Response("Not found",{status:404,headers:{"cache-control":"no-store"}})}if(J.length===1)return y8(J[0],200,Z.headers);let Y=Z.pageUrl;if(!Y)throw new X0(`Sitemap: the entries need ${J.length} files, so Sitemap.response needs \`pageUrl\` to list them in an index.`);return y8(jj(J.map((j,z)=>({loc:Y(z+1)}))),200,Z.headers)}function v8($){try{let Z=new URL($.trim());return Z.protocol==="http:"||Z.protocol==="https:"?Z.href:null}catch{return null}}function zj($,Z={}){let J=Z.maxUrls??1/0,W=$.replace(/^\uFEFF/,"").trimStart();if(!W.startsWith("<")){let K=[];for(let F of W.split(/\r?\n/)){if(K.length>=J)break;let D=F.trim()?v8(F):null;if(D)K.push({loc:D})}if(K.length===0&&W.length>0)throw new X0("Sitemap: the document is neither XML nor a list of URLs.");return{kind:"urlset",urls:K}}let Y=null,j=[],z=[],X=[],Q=null,G=null,B="",V=()=>Y==="index"?z.length:j.length;if(r5(W,{stopped:()=>V()>=J,open(K,F){let D=X[X.length-1];if(X.push(K),Y===null){if(K==="urlset")Y="urlset";else if(K==="sitemapindex")Y="index";return}if(Y==="urlset"&&K==="url"&&D==="urlset"||Y==="index"&&K==="sitemap"&&D==="sitemapindex")Q={};else if(Q&&(D==="url"||D==="sitemap")&&(K==="loc"||K==="lastmod"||K==="changefreq"||K==="priority"))G=K,B="";else if(Q&&Y==="urlset"&&D==="url"&&K==="link"){let U=F.href?v8(F.href):null;if(F.rel?.toLowerCase()==="alternate"&&F.hreflang&&U)(Q.alternates??=[]).push({hrefLang:F.hreflang,href:U})}},close(K){let F=X.lastIndexOf(K);if(F===-1)return;if(X.length=F,G&&K===G&&Q)Q[G]=B.trim(),G=null;else if(Q&&(K==="url"||K==="sitemap")){let D=Q;Q=null,G=null;let U=D.loc?v8(D.loc):null;if(!U)return;if(Y==="index"){z.push(D.lastmod?{loc:U,lastmod:D.lastmod}:{loc:U});return}let O={loc:U};if(D.lastmod)O.lastmod=D.lastmod;if(D.changefreq)O.changefreq=D.changefreq;let L=D.priority?Number(D.priority):NaN;if(Number.isFinite(L))O.priority=L;if(D.alternates)O.alternates=D.alternates;j.push(O)}},text(K){if(G)B+=K}}),Y===null)throw new X0("Sitemap: the document has no <urlset> or <sitemapindex>.");return Y==="index"?{kind:Y,sitemaps:z}:{kind:Y,urls:j}}async function*qB($,Z={}){let{maxUrls:J=k$,maxSitemaps:W=50,maxDepth:Y=3,maxSize:j=Q3,onError:z,...X}=Z,Q=[{url:String($),depth:0}],G=new Set,B=0,V=0;while(Q.length>0&&V<J&&B<W){let K=Q.shift(),F=K.url.replace(/#.*$/,"");if(G.has(F))continue;G.add(F),B++;let D;try{let U=await b1(K.url,{...X,maxSize:j});if(!U.ok)throw U.body?.cancel().catch(()=>{}),new X0(`Sitemap: ${K.url} answered ${U.status}.`,K.url,U.status);let O=D6(await U6(U,j));D=zj(O,{maxUrls:Math.max(J-V,W-B)})}catch(U){if(K.depth===0||!z||X.signal?.aborted)throw U;z(U,K.url);continue}if(D.kind==="index"){if(K.depth>=Y)continue;Q=D.sitemaps.slice(0,W-B).map((O)=>({url:O.loc,depth:K.depth+1})).concat(Q);continue}for(let U of D.urls)if(yield{...U,sitemap:K.url},++V>=J)return}}var Xj={response:wB,chunk:Yj,index:jj,parse:zj,read:qB,MAX_URLS:k$,MAX_BYTES:Q3};var yB=512000,vB=new TextEncoder;function Qj($){let Z=$.trim();if(Z==="*")return"*";return(/^[a-zA-Z_-]+/.exec(Z)?.[0]??"").toLowerCase()}function Gj($){let Z="";for(let J=0;J<$.length;J++){let W=$[J];if(W==="%"&&/^[0-9a-fA-F]{2}$/.test($.slice(J+1,J+3)))Z+=`%${$.slice(J+1,J+3).toUpperCase()}`,J+=2;else if(W.charCodeAt(0)>126||W.charCodeAt(0)<=32){let Y=$.codePointAt(J);if(Y>65535)J++;for(let j of vB.encode(String.fromCodePoint(Y)))Z+=`%${j.toString(16).toUpperCase().padStart(2,"0")}`}else Z+=W}return Z}function gB($,Z){let J=$.endsWith("$"),W=J?$.slice(0,-1):$,Y=0,j=0,z=-1,X=0;while(j<Z.length)if(Y<W.length&&W[Y]!=="*"&&W[Y]===Z[j])Y++,j++;else if(Y<W.length&&W[Y]==="*")z=Y++,X=j;else if(Y===W.length&&!J)return!0;else if(z!==-1)Y=z+1,j=++X;else return!1;while(Y<W.length&&W[Y]==="*")Y++;return Y===W.length}class UZ{groups;sitemaps;status;constructor($,Z,J="parsed"){this.groups=$;this.sitemaps=Z;this.status=J}groupsFor($){let Z=Qj($)||"*";if(Z!=="*"){let J=this.groups.filter((W)=>W.userAgents.includes(Z));if(J.length>0)return J}return this.groups.filter((J)=>J.userAgents.includes("*"))}isAllowed($,Z="*"){let J;if($ instanceof URL||/^[a-z][a-z0-9+.-]*:/i.test($)){let Y=new URL(String($));J=Y.pathname+Y.search}else J=$.startsWith("/")?$:`/${$}`;if(J==="/robots.txt")return!0;if(this.status==="unavailable")return!0;if(this.status==="unreachable")return!1;J=Gj(J);let W=null;for(let Y of this.groupsFor(Z))for(let j of Y.rules){if(!gB(j.path,J))continue;let z=j.path.length,X=j.type==="allow";if(!W||z>W.length||z===W.length&&X)W={length:z,allow:X}}return W?W.allow:!0}crawlDelay($="*"){for(let Z of this.groupsFor($))if(Z.crawlDelay!==void 0)return Z.crawlDelay;return null}}var mB={"user-agent":"user-agent",useragent:"user-agent","user agent":"user-agent",allow:"allow",disallow:"disallow",dissallow:"disallow",disalow:"disallow",sitemap:"sitemap","site-map":"sitemap","crawl-delay":"crawl-delay"};function Kj($,Z={}){let J=[],W=[],Y=null,j=!1;for(let z of $.replace(/^\uFEFF/,"").split(/\r\n|\r|\n/)){let X=z.indexOf("#"),Q=(X===-1?z:z.slice(0,X)).trim(),G=Q.indexOf(":");if(G===-1)continue;let B=mB[Q.slice(0,G).trim().toLowerCase()],V=Q.slice(G+1).trim();if(!B)continue;if(B==="sitemap"){if(!V||/\s/.test(V))continue;try{let K=Z.url?new URL(V,Z.url):new URL(V);if(K.protocol==="http:"||K.protocol==="https:")W.push(K.href)}catch{}continue}if(B==="user-agent"){if(!j||!Y)Y={userAgents:[],rules:[]},J.push(Y),j=!0;let K=Qj(V);if(K)Y.userAgents.push(K);continue}if(!Y)continue;if(j=!1,B==="crawl-delay"){let K=Number(V);if(Number.isFinite(K)&&K>=0)Y.crawlDelay=K;continue}if(!V)continue;Y.rules.push({type:B,path:Gj(V)})}return new UZ(J,W)}async function hB($,Z={}){let{maxSize:J=yB,...W}=Z,Y=new URL("/robots.txt",$),j=await b1(Y,{...W,maxSize:Number.MAX_SAFE_INTEGER}),z=j.status;if(z===429||z>=500)return j.body?.cancel().catch(()=>{}),new UZ([],[],"unreachable");if(z>=400)return j.body?.cancel().catch(()=>{}),new UZ([],[],"unavailable");let X=await U6(j,J,!0),Q=D6(X);if(X.byteLength>=J)Q=Q.slice(0,Math.max(0,Q.lastIndexOf(`
|
|
10
|
+
`)));return Kj(Q,{url:j.url})}function h8($){return $===void 0?[]:typeof $==="string"?[$]:$}function O6($,Z){if(/[\r\n]/.test(Z))throw TypeError(`Robots: the ${$} value ${JSON.stringify(Z)} has a line break in it.`);return`${$}: ${Z}
|
|
11
|
+
`}function Bj($){let Z=[];for(let W of $.rules??[]){let Y=h8(W.userAgent);if(Y.length===0)throw TypeError("Robots: a rule needs at least one userAgent.");let j=Y.map((X)=>O6("User-agent",X)).join(""),z=[...h8(W.allow).map((X)=>["Allow",X]),...h8(W.disallow).map((X)=>["Disallow",X])];for(let[X,Q]of z){if(!Q.startsWith("/")&&!Q.startsWith("*"))throw TypeError(`Robots: ${X} "${Q}" must start with "/" or "*".`);j+=O6(X,Q)}if(z.length===0)j+=`Disallow:
|
|
12
12
|
`;if(W.crawlDelay!==void 0){if(!Number.isFinite(W.crawlDelay)||W.crawlDelay<0)throw TypeError(`Robots: crawlDelay ${W.crawlDelay} is not a number of seconds.`);j+=O6("Crawl-delay",String(W.crawlDelay))}Z.push(j)}let J=($.sitemaps??[]).map((W)=>{let Y;try{Y=new URL(W)}catch{throw TypeError(`Robots: sitemap "${W}" is not an absolute URL.`)}return O6("Sitemap",Y.href)});if(J.length>0)Z.push(J.join(""));return Z.join(`
|
|
13
|
-
`)}function pB($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(K2($),{status:200,headers:J})}var B2={response:pB,text:K2,parse:G2,fetch:hB};import{createHmac as V2,randomBytes as cB}from"crypto";var c8="v2.";function d8($){return $.startsWith(c8)}function DZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function F2($){let Z=cB(16).toString("hex"),J=V2("sha256",DZ()).update(`${$}:${Z}`).digest("hex");return`${c8}${J}`}function L6($,Z){let J=V2("sha256",DZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${c8}${J}`}import{createHash as lB,createHmac as iB,randomInt as sB,timingSafeEqual as O2}from"crypto";function U2($,Z){return Math.floor($/Z)*Z}function dB($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function u8($,Z,J,W){return Z*dB(J,W)+$}function uB($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let B=Y*(1-(X-Z)/J);if(B<=Y)return Math.max(0,Math.ceil(B-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function D2($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let B=u8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-B)),resetAt:Y-j+z,retryAfter:0}}let G=uB({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class l8{}class i8 extends l8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=U2(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let B=u8(Q.current,Q.previous,X,W)+Y<=J;if(B)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return D2({allowed:B,current:Q.current,previous:Q.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var H2="h1.";function M6($,Z,J){let W=iB("sha256",DZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${H2}${W}`}function OZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(H2),X=M6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return O2(Q,Q),!1;return O2(Q,G)}function P2($){let Z="";for(let J=0;J<$;J++)Z+=String(sB(0,10));return Z}var T2=320;function G3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>T2)return null;return Z.toLowerCase()}function H6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>T2)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var L2=null;function N2(){try{let $=M();if(typeof $?.bound==="function"&&$.bound(V1))return $.make(V1)}catch{}return L2??=new V1({driver:new i8,limit:1000,window:60}),L2}function M2($){return $.length<=64?$:`sha256:${lB("sha256").update($).digest("hex")}`}async function LZ($,Z,J,W){let Y=N2(),j=[[`auth:code-${$}:ip:${M2(VZ(J))}`,W.perIp]];if(Z!==null)j.push([`auth:code-${$}:email:${M2(Z)}`,W.perEmail]);for(let[z,X]of j){if(!X)continue;let[Q,G]=X,B=await Y.consume(z,{limit:Q,window:G});if(!B.allowed)throw new W$(B)}}async function _2($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await N2().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as n8}from"crypto";class s8 extends C{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}function K3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function nB($={}){for(let Z of["password","magicLink"]){let J=$?.[Z];if(J!==void 0&&typeof J!=="boolean")throw Error(`auth.${Z} must be true or false, got ${JSON.stringify(J)}`)}}function o8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return K3("length",Z,4,12),K3("expiresInMinutes",J,1),K3("linkExpiresInMinutes",W,1),K3("maxAttempts",Y,1),K3("activeCodes",j,1,5),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)})}}async function oB($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function I2($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function x2($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature } with an OAuthProvider.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function CP($){return $}function C2($={}){return nB($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:s8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:oB,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>n8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return n8(32).toString("hex")},generateMagicLinkToken:()=>n8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:o8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var aB=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),rB=new Set(["svg","math"]);function A2($){return $===32||$===9||$===10||$===12||$===13}function S2($){return $>=65&&$<=90||$>=97&&$<=122}function P6($){return $>=65&&$<=90?$+32:$}function E2(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,B=()=>{if(!J&&aB.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(rB.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},V=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",j=0;else if(K===47)$="endTagOpen";else if(S2(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(P6(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(S2(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(P6(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(A2(K)||K===47)$="inTag",z=K===47;else if(K===62)B();else Z+=String.fromCharCode(P6(K));return;case"inTag":if(K===62){B();return}if(z=K===47,K===34)$="attrDouble";else if(K===39)$="attrSingle";return;case"attrDouble":if(K===34)$="inTag";z=!1;return;case"attrSingle":if(K===39)$="inTag";z=!1;return;case"bang":if(K===45){if(j+=1,j===2)$="comment",j=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)j=j<2?j+1:2;else if(K===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(P6(K)===W.charCodeAt(Y))Y+=1;else Y=K===60?1:0;return}if(K===62)$="data",Z="";else if(A2(K)||K===47)$="inTag",Z="";else Y=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let F=0;F<K.length;F++){if(G())return F;V(K[F])}return K.length},write(K){for(let F=0;F<K.length;F++)V(K[F])},isSafe:G}}function a0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function tB($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${a0([$.path,$.variantKey,$.data])})</script>`}function eB($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${a0([$.id,$.locale,$.strings])})</script>`}function a8($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;j.push(tB(D))}),W?.onUse((D)=>{j.push(eB(D))});let G=$.getReader(),B=E2(),V=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},K=(D)=>{while(j.length>0){let U=Y.encode(j.shift());B.write(U),V(D,U)}},F=(D,U)=>{if(j.length===0){B.write(U),V(D,U);return}let O=B.scanToInsertionPoint(U);if(O>0)V(D,U.subarray(0,O));if(B.isSafe())K(D);let L=U.subarray(O);if(L.length>0)B.write(L),V(D,L)};return new ReadableStream({async pull(D){let U;try{U=await G.read()}catch(P){throw Q(),P}let{done:O,value:L}=U;if(O){K(D),D.close(),Q();return}if(!z){if(z=!0,B.write(L),V(D,L),J.onShell?.(),B.isSafe())K(D);return}F(D,L)},cancel(D){return Q(),G.cancel(D)}})}var $V=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function T6($){if(!$)return!1;return $V.test($)}async function R2($,Z=()=>{}){let J=T.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await ZV($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:b2(),isBot:T6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function f2($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function ZV($,Z){if(!$.context)return{};try{let J=T.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function k2($,Z){return`${$}:${Z}`}function r8($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function w2($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function q2($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=WV($,Z,J,W.buckets);return w2(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function JV($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function WV($,Z,J,W){let Y=k2(Z.salt??$,JV(J));if(!W)return r8(Y);let j=W.get(Y);if(j!==void 0)return j;let z=r8(Y);return W.set(Y,z),z}class y2 extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class t8{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new y2(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=YV(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function YV($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class jV{}class zV extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class e8 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class v2 extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class g2{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class Y${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new t8($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{T.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new v2(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=XV(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new e8(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new g2(this,f2($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),Q=q2($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=T.getStore();if($?.featureContext)return $.featureContext;let Z=await R2(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=T.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=T.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function XV($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function m2($){if($===void 0)return!0;return await M(Y$).enabled($)}async function MZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=I2($[Z]);if(!J||!await m2(J.feature))return null;return J.provider}async function h2($){let Z=[];for(let J of Object.keys($))if(await MZ($,J))Z.push(J);return Z}function $7($){if($&&typeof $==="object")delete $.password;return $}function QV(){return new Proxy({},{get:($,Z)=>c2(Z)})}var p2=new WeakMap;function d2($){if($&&typeof $==="object"){for(let Z of Object.values($))d2(Z);Object.freeze($)}return $}var GV={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},KV=d2({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:GV});class Z7{models;constructor($=QV()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return KV}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??E1(),W=M(b1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await l0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||l0())return Y();let z=(p2.get(W)??Promise.resolve()).then(Y,Y);return p2.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return $7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return $7(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?$7(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as UD}from"crypto";function y0($,Z,J,W,Y){return r0(Z,jj($,Z),J,W,Y)}function r0($,Z,J,W,Y,j){let z=z7(Z,J,W);if(Y&&Z!==z)throw RangeError(cz($,Z,J,W,j));return z}function jj($,Z){let J=$[Z];if(J===void 0)throw TypeError(qJ(Z));return J}function L0($){return $!==null&&/object|function/.test(typeof $)}function m0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function U7($){return v$({name:$},1)}function v$($,Z){return Z1((J)=>({value:J,configurable:1,writable:!Z}),$)}function zj($){return Z1((Z)=>({get:Z,configurable:1}),$)}function v6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function xZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function Z1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function H3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function BV($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function D7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function O7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function Xj($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function Qj($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function Gj($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function w($,...Z){return(...J)=>$(...Z,...J)}function u2($){return $[0].toUpperCase()+$.substring(1)}function P3($){return $.slice().sort()}function S6($,Z){return String(Z).padStart($,"0")}function j$($,Z){return Math.sign($-Z)}function z7($,Z,J){return Math.min(Math.max($,Z),J)}function f1($,Z){return[Math.floor($/Z),V3($,Z)]}function V3($,Z){return($%Z+Z)%Z}function Q$($,Z){return[g6($,Z),L7($,Z)]}function g6($,Z){return Math.trunc($/Z)||0}function L7($,Z){return $%Z||0}function N6($){return Math.abs($%1)===0.5}function Kj($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=U1[X],B=l/G,[V,K]=Q$(Q,B);W+=K*G,Y+=V}let[j,z]=Q$(W,l);return[Y+j,z]}function m6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=U1[Y];W[J[Y]]=g6($,j),$=L7($,j)}return W}function Bj($){return $===q?H4:[]}function Vj($){return $===q?b3:[]}function Fj($){return $===q?["year","day"]:[]}function Uj($){if($!==void 0)return J0($)}function Dj($){if($!==void 0)return J1($)}function M7($){if($!==void 0)return T3($)}function J1($){return Mj(T3($))}function T3($){return Lj(JF($))}function H7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function Oj($,Z){if(Z==null)throw RangeError(qJ($));return Z}function w1($){if(!L0($))throw TypeError(pz);return $}function h6($,Z,J=$){if(typeof Z!==$)throw TypeError(A3(J,Z));return Z}function Lj($,Z="number"){if(!Number.isInteger($))throw RangeError(AV(Z,$));return $||0}function Mj($,Z="number"){if($<=0)throw RangeError(SV(Z,$));return $}function P7($){if(typeof $=="symbol")throw TypeError(fV);return String($)}function E6($,Z){return L0($)?String($):J0($,Z)}function p6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(RV($));return $}function Hj($,Z="number"){if(typeof $=="bigint")throw TypeError(bV(Z));if($=Number($),!Number.isFinite($))throw RangeError(EV(Z,$));return $}function A0($,Z){return Math.trunc(Hj($,Z))||0}function Pj($,Z){return Lj(Hj($,Z),Z)}function l2($,Z){return Mj(A0($,Z),Z)}function T7($,Z){let[J,W]=Q$(Z,l),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*l),[Y,W]}function PZ($,Z,J=1){return T7($[0]+Z[0]*J,$[1]+Z[1]*J)}function TZ($,Z){return T7($[0],$[1]+Z)}function i0($,Z){return PZ(Z,$,-1)}function E0($,Z){return j$($[0],Z[0])||j$($[1],Z[1])}function Tj($,Z,J){return E0($,Z)===-1||E0($,J)===1}function c6($,Z=1){let J=BigInt(l/Z);return[Number($/J),Number($%J)*Z]}function NZ($,Z=1){let J=l/Z,[W,Y]=Q$($,J);return[W,Y*Z]}function Nj($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=l/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function s0($,Z=1,J){let[W,Y]=$,[j,z]=Q$(Y,Z);return W*(l/Z)+(j+(J?z/Z:0))}function N7($,Z,J=f1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(l/Z)+j,z]}function _7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function I7($){return y0($,"isoYear",M3,L3,1),$.isoYear===M3?y0($,"isoMonth",4,12,1):$.isoYear===L3&&y0($,"isoMonth",1,9,1),$}function z$($){return q1({...$,...$1,isoHour:12}),$}function q1($){let Z=y0($,"isoYear",M3,L3,1),J=Z===M3?1:Z===L3?-1:0;return J&&n0(S0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function n0($){if(!$||Tj($,GF,QF))throw RangeError(D4);return $}function G$($){return Kj($,5,z1)[1]}function d6($){let[Z,J]=f1($,l);return[m6(J,5,z1),Z]}function _j($){return Ij($)[0]}function Ij($){return N7($,e0)}function b0($){return CZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function S0($){let Z=b0($);if(Z!==void 0){let[J,W]=Q$(Z,g0);return[J,W*D1+($.isoMicrosecond||0)*i$+($.isoNanosecond||0)]}}function x7($,Z){let[J,W]=d6(G$($)-Z);return n0(S0({...$,isoDay:$.isoDay+W,...J}))}function b6(...$){return CZ(...$)/ez}function CZ(...$){let[Z,J]=xj(...$),W=Z.valueOf();if(!isNaN(W))return W-J*g0}function xj($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===M3?1:$===L3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function B$($,Z){let[J,W]=TZ($,Z);W<0&&(W+=l,J-=1);let[Y,j]=f1(W,D1),[z,X]=f1(j,i$);return u6(J*g0+Y,z,X)}function u6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-XF)/g0)*Math.sign($),Y=new Date($-W*g0);return xZ(T4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function Cj($){return[$.isoYear,$.isoMonth,$.isoDay]}function Aj(){return R1}function C7($,Z){switch(Z){case 2:return A7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function Sj($){return A7($)?366:365}function A7($){return $%4==0&&($%100!=0||$%400==0)}function Ej($){let[Z,J]=xj($.isoYear,$.isoMonth,$.isoDay);return V3(Z.getUTCDay()-J,7)||7}function bj({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function VV($){let Z=b0($);if(Z<BF)return bj($);let J=_7(eJ(_Z),Z),{era:W,eraYear:Y}=p9(J,_Z);return[W,Y]}function l6($){return g$($),i6($,1),$}function g$($){return Rj($,1),$}function i2($){return Qj(lJ,$,Rj($))}function Rj($,Z){let{isoYear:J}=$,W=y0($,"isoMonth",1,Aj(),Z);return{isoYear:J,isoMonth:W,isoDay:y0($,"isoDay",1,C7(J,W),Z)}}function i6($,Z){return xZ(z1,[y0($,"isoHour",0,23,Z),y0($,"isoMinute",0,59,Z),y0($,"isoSecond",0,59,Z),y0($,"isoMillisecond",0,999,Z),y0($,"isoMicrosecond",0,999,Z),y0($,"isoNanosecond",0,999,Z)])}function g($){return $===void 0?0:OX(w1($))}function N3($,Z=0){$=W1($);let J=LX($),W=TF($,Z);return[OX($),W,J]}function S7($){return LX(W1($))}function fj($){return $=W1($),nJ($,9,6,1)}function AZ($,Z,J,W=9,Y=0,j=4){Z=W1(Z);let z=nJ(Z,W,Y),X=R7(Z),Q=f3(Z,j),G=R3(Z,W,Y,1);return z==null?z=Math.max(J,G):yj(z,G),X=f7(X,G,1),$&&(Q=((B)=>B<4?(B+2)%4:B)(Q)),[z,G,X,Q]}function s6($,Z=6,J){let W=R7($=k7($,y6)),Y=f3($,7),j=R3($,Z);return j=Oj(y6,j),W=f7(W,j,void 0,J),[j,W,Y]}function E7($){return oJ(W1($))}function kj($,Z){return b7(W1($),Z)}function b7($,Z=4){let J=qj($);return[f3($,4),...wj(R3($,Z),J)]}function wj($,Z){return $!=null?[U1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function R7($){let Z=$[F3];return Z===void 0?1:A0(Z,F3)}function f7($,Z,J,W){let Y=W?l:U1[Z+1];if(Y){let j=U1[Z];if(Y%(($=r0(F3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(A3(F3,$))}else $=r0(F3,$,1,J?1e9:1,1);return $}function qj($){let Z=$[j7];if(Z!==void 0){if(typeof Z!="number"){if(P7(Z)==="auto")return;throw RangeError(A3(j7,Z))}Z=r0(j7,Math.floor(Z),0,9,1)}return Z}function W1($){return $===void 0?{}:w1($)}function k7($,Z){return typeof $=="string"?{[Z]:$}:w1($)}function Q0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(pz)}}function n6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:FF[Z]})}function w7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=P7(j),j==="auto")return Y?W:null;let z=K7[j];if(z===void 0&&(z=jF[j]),z===void 0)throw RangeError(lz($,j,K7));return r0($,z,W,J,1,E3),z}function m$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=P7(Y),z=Z[j];if(z===void 0)throw RangeError(lz($,j,Z));return z}function yj($,Z){if(Z>$)throw RangeError(rV)}function M0($){return{branding:_4,epochNanoseconds:$}}function N0($,Z,J){return{branding:m1,calendar:J,timeZone:Z,epochNanoseconds:$}}function G0($,Z=$.calendar){return{branding:n$,calendar:Z,...p0(VX,$)}}function K0($,Z=$.calendar){return{branding:s$,calendar:Z,...p0(iJ,$)}}function q$($,Z=$.calendar){return{branding:qZ,calendar:Z,...p0(iJ,$)}}function R6($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0(iJ,$)}}function Y1($){return{branding:N4,...p0(BX,$)}}function t($){return{branding:I4,sign:V$($),...p0(cJ,$)}}function vj($){return _j($.epochNanoseconds)}function o6($){return N7($.epochNanoseconds,D1)[0]}function gj($){return Nj($.epochNanoseconds,i$)}function mj($){return Nj($.epochNanoseconds)}function hj($){return $.epochNanoseconds}function P0($){return typeof $=="string"?$:J0($.id)}function SZ($,Z){return $===Z||P0($)===P0(Z)}function pj($,Z,J,W,Y){let j=y$(W),[z,X]=((O,L)=>{let P=L((O=k7(O,F7))[UX]),H=PF(O);return H=Oj(F7,H),[H,P]})(Y,$);if(D3(Math.max(z,j),X))return s2(W,z);if(!X)throw RangeError(O4);let[Q,G,B]=Z4(Z,J,X),V=YJ(B),K=J4(B),F=jJ(B),D=K(G,Q,W),U=F(G,Q,D,z);return D3(z,X)?s2(U,z):((O,L,P,H,I,S,A)=>{let b=V$(O),[k,N]=q7(H,uJ(P,O),P,b,I,S,A),v=y7(L,k,N);return O[h[P]]+v*b})(U,V(D),z,G,Q,V,K)}function s2($,Z){return s0(O0($),U1[Z],1)}function q7($,Z,J,W,Y,j,z){let X=h[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),B=z($,Y,Q);return[j(G),j(B)]}function y7($,Z,J){let W=s0(i0(Z,J));if(!W)throw RangeError(S3);return s0(i0(Z,$))/W}function cj($,Z){let[J,W,Y]=s6(Z,5,1);return M0(r6($.epochNanoseconds,J,W,Y,1))}function dj($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=s6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((B,V,K,F)=>{let D=R0(K,V),[U,O]=B(D),L=K.epochNanoseconds,P=h0(V,U),H=h0(V,O);if(Tj(L,P,H))throw RangeError(S3);return tj(y7(L,P,H),F)?H:P})(aj,G,Z,Q);else{let B=G.getOffsetNanosecondsFor(W);W=p$(G,nj(B$(W,B),z,X,Q),B,2,0,1)}return N0(W,Y,j)}function uj($,Z){return G0(nj($,...s6(Z)),$.calendar)}function lj($,Z){let[J,W,Y]=s6(Z,5);var j;return Y1((j=Y,v7($,_3(J,W),j)[0]))}function ij($,Z){let J=$(Z.timeZone),W=R0(Z,J),[Y,j]=aj(W),z=s0(i0(h0(J,Y),h0(J,j)),M4,1);if(z<=0)throw RangeError(S3);return z}function sj($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(R0(X,z))))(rj,$(J),Z);return N0(Y,J,W)}function nj($,Z,J,W){return oj($,_3(Z,J),W)}function oj($,Z,J){let[W,Y]=v7($,Z,J);return q1({...c$($,Y),...W})}function v7($,Z,J){return d6(K$(G$($),Z,J))}function f6($){return K$($,L4,7)}function _3($,Z){return U1[$]*Z}function aj($){let Z=rj($);return[Z,c$(Z,1)]}function rj($){return zF(6,$)}function FV($,Z,J){let W=Math.min(y$($),6);return bZ(t6(O0($,W),Z,J),W)}function a6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let B=D3(W,X)?W4(X)&&W<6&&J>=6?DV:UV:OV,[V,K,F]=B($,Z,J,W,Y,j,z,X,Q,G);return F&&W!==7&&(V=((D,U,O,L,P,H,I,S)=>{let A=V$(D);for(let b=L+1;b<=O;b++){if(b===7&&O!==7)continue;let k=uJ(b,D);k[h[b]]+=A;let N=s0(i0(I(S(P,H,k)),U));if(N&&Math.sign(N)!==A)break;D=k}return D})(V,K,J,Math.max(6,W),z,X,Q,G)),V}function r6($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/l)($);return[K$(j,J,W),0]}return t6($,_3(Z,J),W,Y)}function t6($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=l,Y-=1);let[z,X]=f1(K$(j,Z,J),l);return T7(Y+z,X)}function K$($,Z,J){return tj($/Z,J)*Z}function tj($,Z){return IF[Z]($)}function UV($,Z,J,W,Y,j){let z=V$($),X=O0($),Q=r6(X,W,Y,j),G=i0(X,Q),B=Math.sign(Q[0]-X[0])===z,V=bZ(Q,Math.min(J,6));return[{...$,...V},PZ(Z,G),B]}function DV($,Z,J,W,Y,j,z,X,Q,G){let B=V$($),V=s0(O0($,5)),K=_3(W,Y),F=K$(V,K,j),[D,U]=q7(z,{...$,...dJ},6,B,X,Q,G),O=F-s0(i0(D,U)),L=0;O&&Math.sign(O)!==B?Z=TZ(D,F):(L+=B,F=K$(O,K,j),Z=TZ(U,F));let P=j4(F);return[{...$,...P,days:$.days+L},Z,Boolean(L)]}function OV($,Z,J,W,Y,j,z,X,Q,G){let B=V$($),V=h[W],K=uJ(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let F=g6($[V],Y)*Y;K[V]=F;let[D,U]=q7(z,K,W,Y*B,X,Q,G),O=F+y7(Z,D,U)*B*Y,L=K$(O,Y,j),P=Math.sign(L-O)===B;return K[V]=L,[K,P?U:D,P]}function g7($,Z,J,W){let[Y,j,z,X]=((G)=>{let B=b7(G=W1(G));return[G.timeZone,...B]})(W),Q=Y!==void 0;return((G,B,V,K,F,D)=>{V=t6(V,F,K,1);let U=B.getOffsetNanosecondsFor(V);return l7(B$(V,U),D)+(G?h$(f6(U)):"Z")})(Q,Z(Q?$(Y):o$),J.epochNanoseconds,j,z,X)}function m7($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=W1(G);let B=oJ(G),V=qj(G),K=_F(G),F=f3(G,4),D=R3(G,4);return[B,NF(G),K,F,...wj(D,V)]})(J);return((G,B,V,K,F,D,U,O,L,P)=>{K=t6(K,L,O,1);let H=G(V).getOffsetNanosecondsFor(K);return l7(B$(K,H),P)+h$(f6(H),U)+((I,S)=>S!==1?"["+(S===2?"!":"")+P0(I)+"]":"")(V,D)+i7(B,F)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function h7($,Z){let[J,W,Y,j]=((G)=>(G=W1(G),[oJ(G),...b7(G)]))(Z);return z=$.calendar,X=J,Q=j,l7(oj($,Y,W),Q)+i7(z,X);var z,X,Q}function p7($,Z){return J=$.calendar,W=$,Y=E7(Z),k6(W)+i7(J,Y);var J,W,Y}function c7($,Z){return ej($.calendar,$9,$,E7(Z))}function d7($,Z){return ej($.calendar,LV,$,E7(Z))}function u7($,Z){let[J,W,Y]=kj(Z);return j=Y,Z9(v7($,W,J)[0],j);var j}function e6($,Z){let[J,W,Y]=kj(Z,3);return W>1&&($={...$,...FV($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?f0(j):j,{hours:G,minutes:B}=Q,[V,K]=N7(O0(Q,3),e0,Q$);G9(V);let F=s7(K,z),D=z>=0||!X||F;return(X<0?"-":"")+"P"+n2({Y:w$(Q.years),M:w$(Q.months),W:w$(Q.weeks),D:w$(Q.days)})+(G||B||V||D?"T"+n2({H:w$(G),M:w$(B),S:w$(V,D)+F}):"")})($,Y)}function ej($,Z,J,W){let Y=P0($),j=W>1||W===0&&Y!==q;return W===1?Y===q?Z(J):k6(J):j?k6(J)+J9(Y,W===2):Z(J)}function n2($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function l7($,Z){return k6($)+"T"+Z9($,Z)}function k6($){return $9($)+"-"+t0($.isoDay)}function $9($){let{isoYear:Z}=$;return(Z<0||Z>9999?W9(Z)+S6(6,Math.abs(Z)):S6(4,Z))+"-"+t0($.isoMonth)}function LV($){return t0($.isoMonth)+"-"+t0($.isoDay)}function Z9($,Z){let J=[t0($.isoHour),t0($.isoMinute)];return Z!==-1&&J.push(t0($.isoSecond)+((W,Y,j,z)=>s7(W*D1+Y*i$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function h$($,Z=0){if(Z===1)return"";let[J,W]=f1(Math.abs($),M4),[Y,j]=f1(W,L4),[z,X]=f1(j,e0);return W9($)+t0(J)+":"+t0(Y)+(z||X?":"+t0(z)+s7(X):"")}function i7($,Z){if(Z!==1){let J=P0($);if(Z>1||Z===0&&J!==q)return J9(J,Z===2)}return""}function J9($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function s7($,Z){let J=S6(9,$);return J=Z===void 0?J.replace(AF,""):J.slice(0,Z),J?"."+J:""}function W9($){return $<0?"-":"+"}function w$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function MV($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=B$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function Y9($,Z){let J=R0(Z,$);return{calendar:Z.calendar,...p0(VX,J),offset:h$(J.offsetNanoseconds),timeZone:Z.timeZone}}function p$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return x7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,B,V,K)=>{let F=S0(B);K&&(V=f6(V));for(let D of G){let U=s0(i0(D,F));if(K&&(U=f6(U)),U===V)return D}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(lV)}return z?S0(Z):h0($,Z,Y,X)}function h0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(iV);if(W.length)return W[J===3?1:0];let Y=S0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(TZ(Q,-l));return o7(X.getOffsetNanosecondsFor(TZ(Q,l))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(B$(Y,z)))[J===2?0:W.length-1]}function n7($){if(Math.abs($)>=l)throw RangeError(dV);return $}function o7($){if($>l)throw RangeError(uV);return $}function a7($,Z,J){return M0(n0(PZ(Z.epochNanoseconds,((W)=>{if(K9(W))throw RangeError(oV);return O0(W,5)})($?f0(J):J))))}function r7($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...JJ(z,X,W,J?f0(Y):Y,j)}}function t7($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return G0(WJ($(j),J,Z?f0(W):W,Y),j)}function e7($,Z,J,W,Y){let{calendar:j}=J;return K0($4($(j),J,Z?f0(W):W,Y),j)}function $J($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=U3(z,J);Z&&(W=Y4(W)),W.sign<0&&(X=z.dateAdd(X,{...T0,months:1}),X=c$(X,-1));let Q=z.dateAdd(X,W,Y);return q$(U3(z,Q),j)}function ZJ($,Z,J){return Y1(j9(Z,$?f0(J):J)[0])}function JJ($,Z,J,W,Y){let j=O0(W,5),z=J.epochNanoseconds;if(K9(W)){let X=R0(J,$);z=PZ(h0($,{...$4(Z,X,{...W,...dJ},Y),...p0(z1,X)}),j)}else z=PZ(z,j),g(Y);return{epochNanoseconds:n0(z)}}function WJ($,Z,J,W){let[Y,j]=j9(Z,J);return q1({...$4($,Z,{...J,...dJ,days:J.days+j},W),...Y})}function $4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);g(W);let Y=J.days+O0(J,5)[0];return Y?z$(c$(Z,Y)):Z}function U3($,Z,J=1){return c$(Z,J-$.day(Z))}function j9($,Z){let[J,W]=O0(Z,5),[Y,j]=d6(G$($)+W);return[Y,J+j]}function c$($,Z){return Z?{...$,...u6(b0($)+Z*g0)}:$}function Z4($,Z,J){let W=$(J.calendar);return W4(J)?[J,W,Z(J.timeZone)]:[{...J,...$1},W]}function YJ($){return $?hj:S0}function J4($){return $?w(JJ,$):WJ}function jJ($){return $?w(PV,$):TV}function W4($){return $&&$.epochNanoseconds}function D3($,Z){return $<=6-(W4(Z)?1:0)}function zJ($,Z,J,W,Y,j,z){let X=$(W1(z).relativeTo),Q=Math.max(y$(Y),y$(j));if(D3(Q,X))return t(EZ(((U,O,L,P)=>{let H=PZ(O0(U),O0(O),P?-1:1);if(!Number.isFinite(H[0]))throw RangeError(D4);return{...T0,...bZ(H,L)}})(Y,j,Q,W)));if(!X)throw RangeError(O4);W&&(j=f0(j));let[G,B,V]=Z4(Z,J,X),K=J4(V),F=jJ(V),D=K(B,G,Y);return t(F(B,G,K(B,D,j),Q))}function z9($,Z,J,W,Y){let j=y$(W),[z,X,Q,G,B]=((A,b,k)=>{A=k7(A,y6);let N=nJ(A),v=k(A[UX]),_=R7(A),f=f3(A,7),H0=R3(A);if(N===void 0&&H0===void 0)throw RangeError(aV);return H0==null&&(H0=0),N==null&&(N=Math.max(H0,b)),yj(N,H0),_=f7(_,H0,1),[N,H0,_,f,v]})(Y,j,$),V=Math.max(j,z);if(!W4(B)&&V<=6)return t(EZ(((A,b,k,N,v)=>{let _=r6(O0(A),k,N,v);return{...T0,...bZ(_,b)}})(W,z,X,Q,G)));if(!B)throw RangeError(O4);let[K,F,D]=Z4(Z,J,B),U=YJ(D),O=J4(D),L=jJ(D),P=O(F,K,W),H=L(F,K,P,z),I=W.sign,S=V$(H);if(I&&S&&I!==S)throw RangeError(S3);return S&&(H=a6(H,U(P),z,X,Q,G,F,K,U,O)),t(H)}function X9($){return $.sign===-1?Y4($):$}function Y4($){return t(f0($))}function f0($){let Z={};for(let J of h)Z[J]=-1*$[J]||0;return Z}function Q9($){return!$.sign}function V$($,Z=h){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(nV);J=Y}}return J}function EZ($){for(let Z of YF)r0(Z,$[Z],-Zj,Zj,1);return G9(s0(O0($),e0)),$}function G9($){if(!Number.isSafeInteger($))throw RangeError(sV)}function O0($,Z=6){return Kj($,Z,h)}function bZ($,Z=6){let[J,W]=$,Y=m6(W,Z,h);if(Y[h[Z]]+=J*(l/U1[Z]),!Number.isFinite(Y[h[Z]]))throw RangeError(D4);return Y}function j4($,Z=5){return m6($,Z,h)}function K9($){return Boolean(V$($,KX))}function y$($){let Z=9;for(;Z>0&&!$[h[Z]];Z--);return Z}function HV($,Z){return[$,Z]}function o2($){let Z=Math.floor($/C6)*C6;return[Z,Z+C6]}function B9($){let Z=F$($=E6($));if(!Z)throw RangeError(v0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(v0($));J=RZ(Z.offset)}return Z.timeZone&&KJ(Z.timeZone,1),M0(x7(l6(Z),J))}function V9($){let Z=F$(J0($));if(!Z)throw RangeError(v0($));if(Z.timeZone)return T9(Z,Z.offset?RZ(Z.offset):void 0);if(Z.m)throw RangeError(v0($));return _9(Z)}function F9($,Z){let J=F$(J0($));if(!J||!J.timeZone)throw RangeError(v0($));let{offset:W}=J,Y=W?RZ(W):void 0,[,j,z]=N3(Z);return T9(J,Y,j,z)}function RZ($){let Z=KJ($);if(Z===void 0)throw RangeError(v0($));return Z}function U9($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(v0($));return G0(N9(Z))}function z4($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(v0($));return K0(Z.p?N9(Z):_9(Z))}function D9($,Z){let J=QJ(J0(Z));if(J)return XJ(J),q$(I7(g$(J)));let W=z4(Z);return q$(U3($(W.calendar),W))}function XJ($){if($.calendar!==q)throw RangeError(k1($.calendar))}function O9($,Z){let J=GJ(J0(Z));if(J)return XJ(J),R6(g$(J));let W=z4(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,B]=j.I(z,X),[V,K]=j.N(G,B,Q);return R6(z$(j.P(V,K,Q)),Y)}function L9($){let Z,J=((W)=>{let Y=fF.exec(W);return Y?(X4(Y[10]),C9(Y)):void 0})(J0($));if(!J){if(J=F$($),!J)throw RangeError(v0($));if(!J.p)throw RangeError(v0($));if(J.m)throw RangeError(k1("Z"));XJ(J)}if((Z=QJ($))&&i2(Z))throw RangeError(v0($));if((Z=GJ($))&&i2(Z))throw RangeError(v0($));return Y1(i6(J,1))}function M9($){let Z=((J)=>{let W=qF.exec(J);return W?((Y)=>{function j(B,V,K){let F=0,D=0;if(K&&([F,Q]=f1(Q,U1[K])),B!==void 0){if(X)throw RangeError(k1(B));D=((U)=>{let O=parseInt(U);if(!Number.isFinite(O))throw RangeError(k1(U));return O})(B),z=1,V&&(Q=BJ(V)*(U1[K]/e0),X=1)}return F+D}let z=0,X=0,Q=0,G={...xZ(h,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...m6(Q,2,h)};if(!z)throw RangeError(dz(h));return VJ(Y[1])<0&&(G=f0(G)),G})(W):void 0})(J0($));if(!Z)throw RangeError(v0($));return t(EZ(Z))}function H9($){let Z=F$($)||QJ($)||GJ($);return Z?Z.calendar:$}function P9($){let Z=F$($);return Z&&(Z.timeZone||Z.m&&o$||Z.offset)||$}function T9($,Z,J=0,W=0){let Y=Q4($.timeZone),j=x4(Y);return N0(p$(j,l6($),Z,J,W,!j.v,$.m),Y,I3($.calendar))}function N9($){return I9(q1(l6($)))}function _9($){return I9(z$(g$($)))}function I9($){return{...$,calendar:I3($.calendar)}}function F$($){let Z=RF.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:x9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...C9(J.slice(5)),...X4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function QJ($){let Z=EF.exec($);return Z?((J)=>({isoYear:x9(J),isoMonth:parseInt(J[4]),isoDay:1,...X4(J[5])}))(Z):void 0}function GJ($){let Z=bF.exec($);return Z?((J)=>({isoYear:IZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...X4(J[3])}))(Z):void 0}function KJ($,Z){let J=kF.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(k1(j));return n7((HZ(W[2])*M4+HZ(W[3])*L4+HZ(W[4])*e0+BJ(W[5]||""))*VJ(W[1]))})(J,Z):void 0}function x9($){let Z=VJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(k1(-0));return Z*J}function C9($){let Z=HZ($[3]);return{...d6(BJ($[4]||""))[0],isoHour:HZ($[1]),isoMinute:HZ($[2]),isoSecond:Z===60?59:Z}}function X4($){let Z,J,W=[];if($.replace(wF,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(k1(Y))}else{if(J)throw RangeError(k1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(k1($));return{timeZone:J,calendar:W[0]||q}}function BJ($){return parseInt($.padEnd(9,"0"))}function fZ($){return new RegExp(`^${$}$`,"i")}function VJ($){return $&&$!=="+"?-1:1}function HZ($){return $===void 0?0:parseInt($)}function A9($){return Q4(J0($))}function Q4($){let Z=FJ($);return typeof Z=="number"?h$(Z):Z?((J)=>{if(vF.test(J))throw RangeError(cV);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?u2(j).replace(/island|noronha|murdo|rivadavia|urville/,u2):j)).join("/")})($):o$}function a2($){let Z=FJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:o$}function FJ($){let Z=KJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==o$?yF($):void 0}function UJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function DJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function S9($,Z,J,W,Y,j){let z=$(W1(j).relativeTo),X=Math.max(y$(W),y$(Y));if(Qj(h,W,Y))return 0;if(D3(X,z))return E0(O0(W),O0(Y));if(!z)throw RangeError(O4);let[Q,G,B]=Z4(Z,J,z),V=YJ(B),K=J4(B);return E0(V(K(G,Q,W)),V(K(G,Q,Y)))}function OJ($,Z){return d$($,Z)||G4($,Z)}function d$($,Z){return j$(b0($),b0(Z))}function G4($,Z){return j$(G$($),G$(Z))}function E9($,Z){return!UJ($,Z)}function b9($,Z){return!DJ($,Z)&&!!K4($.timeZone,Z.timeZone)&&SZ($.calendar,Z.calendar)}function R9($,Z){return!OJ($,Z)&&SZ($.calendar,Z.calendar)}function f9($,Z){return!d$($,Z)&&SZ($.calendar,Z.calendar)}function k9($,Z){return!d$($,Z)&&SZ($.calendar,Z.calendar)}function w9($,Z){return!d$($,Z)&&SZ($.calendar,Z.calendar)}function q9($,Z){return!G4($,Z)}function K4($,Z){if($===Z)return 1;let J=P0($),W=P0(Z);if(J===W)return 1;try{return a2(J)===a2(W)}catch(Y){}}function LJ($,Z,J,W){let Y=AZ($,Q0(W),3,5),j=B4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return t($?f0(j):j)}function MJ($,Z,J,W,Y,j){let z=F4(W.calendar,Y.calendar),X=Q0(j),[Q,G,B,V]=AZ(J,X,5),K=W.epochNanoseconds,F=Y.epochNanoseconds,D=E0(F,K),U;if(D)if(Q<6)U=B4(K,F,Q,G,B,V);else{let O=Z(((P,H)=>{if(!K4(P,H))throw RangeError(oz);return P})(W.timeZone,Y.timeZone)),L=$(z);U=v9(L,O,W,Y,D,Q,X),U=a6(U,F,Q,G,B,V,L,W,hj,w(JJ,O))}else U=T0;return t(J?f0(U):U)}function HJ($,Z,J,W,Y){let j=F4(J.calendar,W.calendar),z=Q0(Y),[X,Q,G,B]=AZ(Z,z,6),V=S0(J),K=S0(W),F=E0(K,V),D;if(F)if(X<=6)D=B4(V,K,X,Q,G,B);else{let U=$(j);D=g9(U,J,W,F,X,z),D=a6(D,K,X,Q,G,B,U,J,S0,WJ)}else D=T0;return t(Z?f0(D):D)}function PJ($,Z,J,W,Y){let j=F4(J.calendar,W.calendar),z=Q0(Y);return y9(Z,()=>$(j),J,W,...AZ(Z,z,6,9,6),z)}function TJ($,Z,J,W,Y){let j=F4(J.calendar,W.calendar),z=Q0(Y),X=AZ(Z,z,9,9,8),Q=$(j);return y9(Z,()=>Q,U3(Q,J),U3(Q,W),...X,z)}function y9($,Z,J,W,Y,j,z,X,Q){let G=S0(J),B=S0(W),V;if(E0(B,G))if(Y===6)V=B4(G,B,Y,j,z,X);else{let K=Z();V=K.dateUntil(J,W,Y,Q),j===6&&z===1||(V=a6(V,B,Y,j,z,X,K,J,S0,$4))}else V=T0;return t($?f0(V):V)}function NJ($,Z,J,W){let Y=Q0(W),[j,z,X,Q]=AZ($,Y,5,5),G=K$(_J(Z,J),_3(z,X),Q),B={...T0,...j4(G,j)};return t($?f0(B):B)}function PV($,Z,J,W,Y,j){let z=E0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?m9(J.epochNanoseconds,W.epochNanoseconds,Y):v9(Z,$,J,W,z,Y,j):T0}function TV($,Z,J,W,Y){let j=S0(Z),z=S0(J),X=E0(z,j);return X?W<=6?m9(j,z,W):g9($,Z,J,X,W,Y):T0}function v9($,Z,J,W,Y,j,z){let[X,Q,G]=((K,F,D,U)=>{function O(){return b={...c$(H,S++*-U),...P},k=h0(K,b),E0(I,k)===-U}let L=R0(F,K),P=p0(z1,L),H=R0(D,K),I=D.epochNanoseconds,S=0,A=_J(L,H),b,k;if(Math.sign(A)===-U&&S++,O()&&(U===-1||O()))throw RangeError(S3);let N=s0(i0(k,I));return[L,b,N]})(Z,J,W,Y);var B,V;return{...j===6?(B=X,V=Q,{...T0,days:h9(B,V)}):$.dateUntil(X,Q,j,z),...j4(G)}}function g9($,Z,J,W,Y,j){let[z,X,Q]=((G,B,V)=>{let K=B,F=_J(G,B);return Math.sign(F)===-V&&(K=c$(B,-V),F+=l*V),[G,K,F]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...j4(Q)}}function B4($,Z,J,W,Y,j){return{...T0,...bZ(r6(i0($,Z),W,Y,j),J)}}function m9($,Z,J){return{...T0,...bZ(i0($,Z),J)}}function h9($,Z){return V4(b0($),b0(Z))}function V4($,Z){return Math.trunc((Z-$)/g0)}function _J($,Z){return G$(Z)-G$($)}function F4($,Z){if(!SZ($,Z))throw RangeError(gJ);return $}function NV($){function Z(Y){return((j,z)=>({...p9(j,z),F:j.month,day:parseInt(j.day)}))(_7(J,Y),W)}let J=eJ($),W=w6($);return{id:$,O:_V(Z),B:IV(Z)}}function _V($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function IV($){let Z=$(0).year-KF;return m0((J)=>{let W,Y=CZ(J-Z),j=[],z=[];do Y+=400*g0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*g0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=g0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:tz(z.reverse())}})}function p9($,Z){let J,W,Y=c9($);if($.era){let j=XX[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=s9(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function c9($){return parseInt($.relatedYear||$.year)}function X7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function O3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*g0}function _6($){let Z=t2(this,$),J=t2(this,$-1),W=Z.length;if(W>J.length){let Y=n9(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function I6($){return V4(O3.call(this,$),O3.call(this,$+1))}function r2($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),V4(J[Z-1],Y[W-1])}function x6($){return this.B($).k.length}function t2($,Z){return Object.keys($.B(Z).C)}function d9($){return I3(J0($))}function I3($){if(($=$.toLowerCase())!==q&&$!==P4&&w6($)!==w6(eJ($).resolvedOptions().calendar))throw RangeError(pV($));return $}function w6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function u9($){return this.R($)[0]}function l9($){return this.R($)[1]}function IJ($){let[Z]=this.h($);return V4(this.q(Z),b0($))+1}function i9($){let Z=mF.exec($);if(!Z)throw RangeError(mV($));return[parseInt(Z[1]),Boolean(Z[2])]}function q6($,Z,J){return $+(Z||J&&$>=J?1:0)}function Q7($,Z){return $-(Z&&$>=Z?1:0)}function s9($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function G7($){return XX[o9($)]}function n9($){return ZF[o9($)]}function o9($){return w6($.id||q)}function a9($,Z,J,W){let Y=U$(J,W,j1,[],WX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=u$(Y),X=$(Y.timeZone);return{epochNanoseconds:p$(Z(X),{...j,...z},Y.offset!==void 0?RZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...$1}}function r9($,Z,J,W,Y,j){let z=U$(J,Y,j1,ZX,WX),X=$(z.timeZone),[Q,G,B]=N3(j),V=J.dateFromFields(z,n6(j,Q)),K=u$(z,Q);return N0(p$(Z(X),{...V,...K},z.offset!==void 0?RZ(z.offset):void 0,G,B),X,W)}function t9($,Z,J){let W=U$($,Z,j1,[],g1),Y=g(J);return G0(q1({...$.dateFromFields(W,n6(J,Y)),...u$(W,Y)}))}function xJ($,Z,J,W=[]){let Y=U$($,Z,j1,W);return $.dateFromFields(Y,J)}function CJ($,Z,J,W){let Y=U$($,Z,pJ,W);return $.yearMonthFromFields(Y,J)}function AJ($,Z,J,W,Y=[]){let j=U$($,J,j1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=IZ),$.monthDayFromFields(j,W)}function e9($,Z){let J=g(Z);return Y1(u$(F1($,B7,[],1),J))}function $z($){let Z=F1($,cJ);return t(EZ({...T0,...Z}))}function U$($,Z,J,W=[],Y=[]){return F1(Z,[...$.fields(J),...Y].sort(),W)}function F1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(kV(X));if(X==="constructor"||X==="__proto__")throw RangeError(yJ(X));let Q=$[X];if(Q!==void 0)z=1,Jj[X]&&(Q=Jj[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(qJ(X));Y[X]=zX[X]}j=X}if(W&&!z)throw TypeError(dz(Z));return Y}function u$($,Z){return i6(dF({...zX,...$}),Z)}function Zz($,Z,J,W,Y,j){let z=Q0(j),{calendar:X,timeZone:Q}=J;return N0(((G,B,V,K,F)=>{let D=x3(G,V,K,j1,JX,$X),[U,O,L]=N3(F,2);return p$(B,{...G.dateFromFields(D,n6(F,U)),...u$(D,U)},RZ(D.offset),O,L)})($(X),Z(Q),W,Y,z),Q,X)}function Jz($,Z,J,W,Y){let j=Q0(Y);return G0(((z,X,Q,G)=>{let B=x3(z,X,Q,j1,g1),V=g(G);return q1({...z.dateFromFields(B,n6(G,V)),...u$(B,V)})})($(Z.calendar),J,W,j))}function Wz($,Z,J,W,Y){let j=Q0(Y);return((z,X,Q,G)=>{let B=x3(z,X,Q,j1);return z.dateFromFields(B,G)})($(Z.calendar),J,W,j)}function Yz($,Z,J,W,Y){let j=Q0(Y);return q$(((z,X,Q,G)=>{let B=x3(z,X,Q,pJ);return z.yearMonthFromFields(B,G)})($(Z.calendar),J,W,j))}function jz($,Z,J,W,Y){let j=Q0(Y);return((z,X,Q,G)=>{let B=x3(z,X,Q,j1);return z.monthDayFromFields(B,G)})($(Z.calendar),J,W,j)}function zz($,Z,J){return Y1(((W,Y,j)=>{let z=g(j);return u$({...p0(B7,W),...F1(Y,B7)},z)})($,Z,J))}function Xz($,Z){return t((J=$,W=Z,EZ({...J,...F1(W,cJ)})));var J,W}function x3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=F1(Z,z,j),Q=F1(J,z);return X=$.mergeFields(X,Q),F1(X,z,[])}function SJ($,Z){let J=U$($,Z,jX);return $.monthDayFromFields(J)}function EJ($,Z,J){let W=U$($,Z,YX);return $.yearMonthFromFields(W,J)}function Qz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=F1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=F1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function J7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=G7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(qV);if(!j)throw RangeError(wV);let z=j[J];if(z===void 0)throw RangeError(vV(J));let X=s9(W,z);if(Y!==void 0&&Y!==X)throw RangeError(yV);Y=X}else if(Y===void 0)throw TypeError(gV(j));return Y}function W7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,B)=>{let V=X.U(G),[K,F]=i9(Q),D=q6(K,F,V);if(F){let U=n9(X);if(U===void 0)throw RangeError(B3);if(U>0){if(D>U)throw RangeError(B3);if(V===void 0){if(B===1)throw RangeError(B3);D--}}else{if(D!==-U)throw RangeError(B3);if(V===void 0&&B===1)throw RangeError(B3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(sz);Y=z,W=1}else if(Y===void 0)throw TypeError(hV);return r0("month",Y,1,$.L(J),W)}function e2($,Z,J,W,Y){return y0(Z,"day",1,$.j(W,J),Y)}function Y7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Gz($){return M0(n0(c6(p6($))))}function Kz($,Z,J,W,Y=q){return N0(n0(c6(p6(J))),Z(W),$(Y))}function Bz($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,B=q){return G0(q1(l6(Z1(A0,xZ(T4,[Z,J,W,Y,j,z,X,Q,G])))),$(B))}function Vz($,Z,J,W,Y=q){return K0(z$(g$(Z1(A0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function Fz($,Z,J,W=q,Y=1){let j=A0(Z),z=A0(J),X=$(W);return q$(I7(g$({isoYear:j,isoMonth:z,isoDay:A0(Y)})),X)}function Uz($,Z,J,W=q,Y=IZ){let j=A0(Z),z=A0(J),X=$(W);return R6(z$(g$({isoYear:A0(Y),isoMonth:j,isoDay:z})),X)}function Dz($=0,Z=0,J=0,W=0,Y=0,j=0){return Y1(i6(Z1(A0,xZ(z1,[$,Z,J,W,Y,j])),1))}function Oz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return t(EZ(Z1(Pj,xZ(h,[$,Z,J,W,Y,j,z,X,Q,G]))))}function bJ($,Z,J=q){return N0($.epochNanoseconds,Z,J)}function Lz($){return M0($.epochNanoseconds)}function RJ($,Z){return G0(R0(Z,$))}function fJ($,Z){return K0(R0(Z,$))}function Mz($,Z,J){return EJ($(Z.calendar),J)}function Hz($,Z,J){return SJ($(Z.calendar),J)}function kJ($,Z){return Y1(R0(Z,$))}function Pz($,Z,J,W){let Y=((j,z,X,Q)=>{let G=S7(Q);return h0(j(z),X,G)})($,J,Z,W);return N0(n0(Y),J,Z.calendar)}function Tz($,Z,J){let W=$(Z.calendar);return q$({...Z,...EJ(W,J)})}function Nz($,Z,J){return SJ($(Z.calendar),J)}function _z($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):$1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function Iz($,Z=$1){return G0(q1({...$,...Z}))}function xz($,Z,J){return EJ($(Z.calendar),J)}function Cz($,Z,J){return SJ($(Z.calendar),J)}function Az($,Z,J,W){return((Y,j,z)=>Qz(Y,j,YX,w1(z),b3))($(Z.calendar),J,W)}function Sz($,Z,J,W){return((Y,j,z)=>Qz(Y,j,jX,w1(z),H4))($(Z.calendar),J,W)}function Ez($,Z,J,W,Y){let j=w1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function bz($,Z){return G0(q1({...$,...Z}))}function Rz($){return M0(n0(NZ($,e0)))}function fz($){return M0(n0(NZ($,D1)))}function kz($){return M0(n0(c6(p6($),i$)))}function wz($){return M0(n0(c6(p6($))))}function qz($,Z,J=$1){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J};return N0(p$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function yz($,Z,J){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J},z=hz(Z.calendar,J.calendar);return N0(p$(Y,j,j.offsetNanoseconds,2),W,z)}function vz($,Z=$1){return G0({...$,...Z})}function gz($,Z){return G0({...$,...Z},hz($.calendar,Z.calendar))}function U4($,Z){return{...$,calendar:Z}}function mz($,Z){return{...$,timeZone:Z}}function hz($,Z){if($===Z)return $;let J=P0($),W=P0(Z);if(J===W||J===q)return Z;if(W===q)return $;throw RangeError(gJ)}function xV($,Z){return(J)=>J===q?$:J===P4||J===_Z?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),gF(J))}function l$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=D7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=o$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function y1($,Z=wJ){let[J,,,W]=$;return(Y,j=jU,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...CV($,Q,z)]}}function wJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(tV);J.timeZone=$}return new D$(Z,J)}function CV($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==q)&&z!==X)throw RangeError(gJ)})(P0(j.calendar),Z.calendar,Y),W(j,Z)))}function kZ($){let Z=C3();return B$(Z,$.getOffsetNanosecondsFor(Z))}function C3(){return NZ(Date.now(),D1)}function v1(){return Yj||(Yj=new D$().resolvedOptions().timeZone)}var AV=($,Z)=>`Non-integer ${$}: ${Z}`,SV=($,Z)=>`Non-positive ${$}: ${Z}`,EV=($,Z)=>`Non-finite ${$}: ${Z}`,bV=($)=>`Cannot convert bigint to ${$}`,RV=($)=>`Invalid bigint: ${$}`,fV="Cannot convert Symbol to string",pz="Invalid object",cz=($,Z,J,W,Y)=>Y?cz($,Y[Z],Y[J],Y[W]):A3($,Z)+`; must be between ${J}-${W}`,A3=($,Z)=>`Invalid ${$}: ${Z}`,qJ=($)=>`Missing ${$}`,yJ=($)=>`Invalid field ${$}`,kV=($)=>`Duplicate field ${$}`,dz=($)=>"No valid fields: "+$.join(),uz="Invalid bag",lz=($,Z,J)=>A3($,Z)+"; must be "+Object.keys(J).join(),iz="Cannot use valueOf",vJ="Invalid calling context",wV="Forbidden era/eraYear",qV="Mismatching era/eraYear",yV="Mismatching year/eraYear",vV=($)=>`Invalid era: ${$}`,gV=($)=>"Missing year"+($?"/era/eraYear":""),mV=($)=>`Invalid monthCode: ${$}`,sz="Mismatching month/monthCode",hV="Missing month/monthCode",$j="Cannot guess year",B3="Invalid leap month",nz="Invalid protocol",S3="Invalid protocol results",gJ="Mismatching Calendars",pV=($)=>`Invalid Calendar: ${$}`,oz="Mismatching TimeZones",cV="Forbidden ICU TimeZone",dV="Out-of-bounds offset",uV="Out-of-bounds TimeZone gap",lV="Invalid TimeZone offset",iV="Ambiguous offset",D4="Out-of-bounds date",sV="Out-of-bounds duration",nV="Cannot mix duration signs",O4="Missing relativeTo",oV="Cannot use large units",aV="Required smallestUnit or largestUnit",rV="smallestUnit > largestUnit",v0=($)=>`Cannot parse: ${$}`,k1=($)=>`Invalid substring: ${$}`,az=($)=>`Cannot format ${$}`,rz="Mismatching types for formatting",tV="Cannot specify TimeZone",tz=w(H3,($,Z)=>Z),wZ=w(H3,($,Z,J)=>J),t0=w(S6,2),K7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},E3=Object.keys(K7),g0=86400000,ez=1000,i$=1000,D1=1e6,e0=1e9,L4=60000000000,M4=3600000000000,l=86400000000000,U1=[1,i$,D1,e0,L4,M4,l],g1=E3.slice(0,6),B7=P3(g1),$X=["offset"],ZX=["timeZone"],JX=g1.concat($X),WX=JX.concat(ZX),V7=["era","eraYear"],eV=V7.concat(["year"]),H4=["year"],mJ=["monthCode"],hJ=["month"].concat(mJ),b3=["day"],pJ=hJ.concat(H4),YX=mJ.concat(H4),j1=b3.concat(pJ),$F=b3.concat(hJ),jX=b3.concat(mJ),zX=wZ(g1,0),q="iso8601",P4="gregory",_Z="japanese",XX={[P4]:{bce:-1,ce:0},[_Z]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},ZF={chinese:13,dangi:13,hebrew:-6},J0=w(h6,"string"),QX=w(h6,"boolean"),JF=w(h6,"number"),GX=w(h6,"function"),h=E3.map(($)=>$+"s"),cJ=P3(h),WF=h.slice(0,6),KX=h.slice(6),YF=KX.slice(1),jF=tz(h),T0=wZ(h,0),dJ=wZ(WF,0),uJ=w(Gj,h),z1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],lJ=["isoDay","isoMonth","isoYear"],T4=z1.concat(lJ),iJ=P3(lJ),BX=P3(z1),VX=P3(T4),$1=wZ(BX,0),zF=w(Gj,T4),D$=Intl.DateTimeFormat,FX="en-GB",sJ=1e8,XF=sJ*g0,QF=[sJ,0],GF=[-sJ,0],L3=275760,M3=-271821,KF=1970,IZ=1972,R1=12,BF=CZ(1868,9,8),VF=m0(VV,WeakMap),y6="smallestUnit",F7="unit",F3="roundingIncrement",j7="fractionalSecondDigits",UX="relativeTo",DX={constrain:0,reject:1},FF=Object.keys(DX),UF={compatible:0,reject:1,earlier:2,later:3},DF={reject:0,use:1,prefer:2,ignore:3},OF={auto:0,never:1,critical:2,always:3},LF={auto:0,never:1,critical:2},MF={auto:0,never:1},HF={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},R3=w(w7,y6),nJ=w(w7,"largestUnit"),PF=w(w7,F7),OX=w(m$,"overflow",DX),LX=w(m$,"disambiguation",UF),TF=w(m$,"offset",DF),oJ=w(m$,"calendarName",OF),NF=w(m$,"timeZoneName",LF),_F=w(m$,"offset",MF),f3=w(m$,"roundingMode",HF),qZ="PlainYearMonth",yZ="PlainMonthDay",s$="PlainDate",n$="PlainDateTime",N4="PlainTime",m1="ZonedDateTime",_4="Instant",I4="Duration",IF=[Math.floor,($)=>N6($)?Math.floor($):Math.round($),Math.ceil,($)=>N6($)?Math.ceil($):Math.round($),Math.trunc,($)=>N6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>N6($)?($=Math.trunc($)||0)+$%2:Math.round($)],o$="UTC",C6=5184000,xF=b6(1847),CF=b6(new Date().getUTCFullYear()+10),AF=/0+$/,R0=m0(MV,WeakMap),Zj=4294967295,x4=m0(($)=>{let Z=FJ($);return typeof Z=="object"?new HX(Z):new MX(Z||0)});class MX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[x7($,this.v)]}l(){}}class HX{constructor($){this.$=((Z)=>{function J(Q){let G=z7(Q,z,X),[B,V]=o2(G),K=Y(B),F=Y(V);return K===F?K:W(j(B,V),K,F,Q)}function W(Q,G,B,V){let K,F;for(;(V===void 0||(K=V<Q[0]?G:V>=Q[1]?B:void 0)===void 0)&&(F=Q[1]-Q[0]);){let D=Q[0]+Math.floor(F/2);Z(D)===B?Q[1]=D:Q[0]=D+1}return K}let Y=m0(Z),j=m0(HV),z=xF,X=CF;return{G(Q){let G=J(Q-86400),B=J(Q+86400),V=Q-G,K=Q-B;if(G===B)return[V];let F=J(V);return F===J(K)?[Q-F]:G>B?[V,K]:[]},V:J,l(Q,G){let B=z7(Q,z,X),[V,K]=o2(B),F=C6*G,D=G<0?()=>K>z||(z=B,0):()=>V<X||(X=B,0);for(;D();){let U=Y(V),O=Y(K);if(U!==O){let L=j(V,K);W(L,U,O);let P=L[0];if((j$(P,Q)||1)===G)return P}V+=F,K+=F}}}})(((Z)=>(J)=>{let W=_7(Z,J*ez);return b6(c9(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(_j($))*e0}getPossibleInstantsFor($){let[Z,J]=[b6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*D1+W.isoMicrosecond*i$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>n0(TZ(NZ(Y,e0),J)))}l($,Z){let[J,W]=Ij($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return NZ(Y,e0)}}var aJ="([+\u2212-])",A6="(?:[.,](\\d{1,9}))?",PX=`(?:(?:${aJ}(\\d{6}))|(\\d{4}))-?(\\d{2})`,rJ="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+A6+")?)?",tJ=aJ+rJ,SF=PX+"-?(\\d{2})(?:[T ]"+rJ+"(Z|"+tJ+")?)?",TX="\\[(!?)([^\\]]*)\\]",C4=`((?:${TX}){0,9})`,EF=fZ(PX+C4),bF=fZ("(?:--)?(\\d{2})-?(\\d{2})"+C4),RF=fZ(SF+C4),fF=fZ("T?"+rJ+"(?:"+tJ+")?"+C4),kF=fZ(tJ),wF=new RegExp(TX,"g"),qF=fZ(`${aJ}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${A6}H)?(?:(\\d+)${A6}M)?(?:(\\d+)${A6}S)?)?`),yF=m0(($)=>new D$(FX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),vF=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,gF=m0(NV),eJ=m0(($)=>new D$(FX,{calendar:$,timeZone:o$,era:"short",year:"numeric",month:"short",day:"numeric"})),mF=/^M(\d{2})(L?)$/,hF={era:E6,eraYear:A0,year:A0,month:l2,monthCode:E6,day:l2},pF=wZ(g1,A0),cF=wZ(h,Pj),Jj=Object.assign({},hF,pF,cF,{offset:E6}),dF=w(BV,g1,z1),Wj={dateAdd($,Z,J){let W=g(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=O0(Z,5)[0],j||z)Y=((G,B,V,K,F)=>{let[D,U,O]=G.h(B);if(V){let[L,P]=G.I(D,U);D+=V,U=q6(L,P,G.U(D)),U=r0("month",U,1,G.L(D),F)}return K&&([D,U]=G._(D,U,K)),O=r0("day",O,1,G.j(D,U),F),G.q(D,U,O)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=b0($)}return Y+=(7*X+Q)*g0,z$(u6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=h9({...$,...$1},{...Z,...$1});return J===7&&([Q,G]=Q$(G,7)),{...T0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,B,V,K,F,D)=>{let U=K-G,O=F-B,L=D-V;if(U||O){let P=Math.sign(U||O),H=Q.j(K,F),I=0;if(Math.sign(L)===-P){let S=H;[K,F]=Q._(K,F,-P),U=K-G,O=F-B,H=Q.j(K,F),I=P<0?-S:H}if(L=D-Math.min(V,H)+I,U){let[S,A]=Q.I(G,B),[b,k]=Q.I(K,F);if(O=b-S||Number(k)-Number(A),Math.sign(O)===-P){let N=P<0&&-Q.L(K);U=(K-=P)-G,O=F-q6(S,A,Q.U(K))+(N||Q.L(K))}}}return[U,O,L]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...T0,years:j,months:z,days:X}},dateFromFields($,Z){let J=g(Z),W=J7(this,$),Y=W7(this,$,W,J),j=e2(this,$,Y,W,J);return K0(z$(this.P(W,Y,j)),this.id||q)},yearMonthFromFields($,Z){let J=g(Z),W=J7(this,$),Y=W7(this,$,W,J);return q$(I7(this.P(W,Y,1)),this.id||q)},monthDayFromFields($,Z){let J=g(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,B,V;if(Y!==void 0){[X,Q]=i9(Y),V=jj($,"day");let K=this.N(X,Q,V);if(!K)throw RangeError($j);if([G,B]=K,z!==void 0&&z!==B)throw RangeError(sz);W&&(B=r0("month",B,1,R1,1),V=r0("day",V,1,C7(j!==void 0?j:G,B),J))}else{G=j===void 0&&W?IZ:J7(this,$),B=W7(this,$,G,J),V=e2(this,$,B,G,J);let K=this.U(G);Q=B===K,X=Q7(B,K);let F=this.N(X,Q,V);if(!F)throw RangeError($j);[G,B]=F}return R6(z$(this.P(G,B,V)),this.id||q)},fields($){return G7(this)&&$.includes("year")?[...$,...V7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return Y7(J,Z,hJ),G7(this)&&(Y7(J,Z,eV),this.id===_Z&&Y7(J,Z,$F,V7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:IJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+t0(j)+(z?"L":""))(W,Y)},dayOfWeek:Ej,daysInWeek(){return 7}},uF={dayOfYear:IJ,h:Cj,q:CZ},lF=Object.assign({},uF,{weekOfYear:u9,yearOfWeek:l9,R($){function Z(F){return(7-F<W?7:0)-F}function J(F){let D=Sj(K+F),U=F||1,O=Z(V3(Q+D*U,7));return B=(D+(O-G)*U)/7}let W=this.id?1:4,Y=Ej($),j=this.dayOfYear($),z=V3(Y-1,7),X=j-1,Q=V3(z-X,7),G=Z(Q),B,V=Math.floor((X-G)/7)+1,K=$.isoYear;return V?V>J(0)&&(V=1,K++):(V=J(-1),K--),[V,K,B]}}),iF={dayOfYear:IJ,h:X7,q:O3,weekOfYear:u9,yearOfWeek:l9,R(){return[]}},vZ=xV(Object.assign({},Wj,lF,{h:Cj,ee($){return this.id===P4?bj($):this.id===_Z?VF($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[IZ,$]},K:A7,U(){},L:Aj,J:($)=>$*R1,j:C7,X:Sj,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:CZ,_:($,Z,J)=>($+=g6(J,R1),(Z+=L7(J,R1))<1?($--,Z+=R1):Z>R1&&($++,Z-=R1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},Wj,iF,{h:X7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=_6.call(this,$);return[Q7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=X7.call(this,{isoYear:IZ,isoMonth:R1,isoDay:31}),z=_6.call(this,W),X=Y===z;(j$($,Q7(Y,z))||j$(Number(Z),Number(X))||j$(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,B=_6.call(this,G),V=q6($,Z,B);if(Z===(V===B)&&J<=r2.call(this,G,V))return[G,V]}},K($){let Z=I6.call(this,$);return Z>I6.call(this,$-1)&&Z>I6.call(this,$+1)},U:_6,L:x6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=x6.call(this,z+Y);return j},j:r2,X:I6,P($,Z,J){return u6(O3.call(this,$,Z,J))},q:O3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(D4);if(J<0)for(;Z<1;)Z+=x6.call(this,--$);else{let W;for(;Z>(W=x6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),X$="numeric",gZ=["timeZoneName"],NX={month:X$,day:X$},$W={year:X$,month:X$},ZW=Object.assign({},$W,{day:X$}),JW={hour:X$,minute:X$,second:X$},WW=Object.assign({},ZW,JW),sF=Object.assign({},WW,{timeZoneName:"short"}),nF=Object.keys($W),oF=Object.keys(NX),aF=Object.keys(ZW),rF=Object.keys(JW),YW=["dateStyle"],tF=nF.concat(YW),eF=oF.concat(YW),jW=aF.concat(YW,["weekday"]),k3=rF.concat(["dayPeriod","timeStyle"]),zW=jW.concat(k3),$U=zW.concat(gZ),ZU=gZ.concat(k3),JU=gZ.concat(jW),WU=gZ.concat(["day","weekday"],k3),YU=gZ.concat(["year","weekday"],k3),jU={},XW=[l$(zW,WW),o6],_X=[l$($U,sF),o6,0,($,Z)=>{let J=P0($.timeZone);if(Z&&P0(Z.timeZone)!==J)throw RangeError(oz);return J}],QW=[l$(zW,WW,gZ),b0],GW=[l$(jW,ZW,ZU),b0],KW=[l$(k3,JW,JU),($)=>G$($)/D1],BW=[l$(tF,$W,WU),b0,1],VW=[l$(eF,NX,YU),b0,1],Yj;function M1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(vJ);AX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...B){return Q.call(this,X(this),...B)},U7(G))}function X(Q){let G=x0(Q);if(!G||G.branding!==$)throw TypeError(vJ);return G}return Object.defineProperties(j.prototype,{...zj(Z1(z,J)),...v$(Z1(z,W)),...v6("Temporal."+$)}),Object.defineProperties(j,{...v$(Y),...U7($)}),[j,(Q)=>{let G=Object.create(j.prototype);return AX(G,Q),G},X]}function bX($){return $=$.concat("id").sort(),(Z)=>{if(!Xj(Z,$))throw TypeError(nz);return Z}}function cZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(uz);return $}function A4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=x0(j)||{},{branding:X}=z,Q=X===s$||Z.includes(X)?z:w0(j);return Y[W](Q)};return J}function DW($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?vZ(j):(z=j,Object.assign(Object.create(TU),{i:z})))[J](W);var j,z};return Z}function P$(){throw TypeError(iz)}function q3({calendar:$}){return typeof $=="string"?new IW($):$}function IX($,Z){if(Z=Q0(Z),L0($)){let W=x0($);if(W&&W.branding===yZ)return g(Z),W;let Y=kX($);return AJ(w4(Y||q),!Y,$,Z)}let J=O9(vZ,$);return g(Z),J}function RX($,Z,J){return W=Z.call($,k0(M0(J))),n7(T3(W));var W}function S4($,Z=vX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=w(Z[Y],$,GX($[Y]));return W}function i($,Z){return typeof $=="string"?x4($):S4($,Z)}function V0($){return i($,UW)}function O1($){if(L0($)){let Z=x0($);if(Z)switch(Z.branding){case _4:return Z;case m1:return M0(Z.epochNanoseconds)}}return B9($)}function xX($,Z,J){let W=Z.l(O1(J).epochNanoseconds,$);return W?k0(M0(W)):null}function a($){return L0($)?(x0($)||{}).timeZone||AU($):((Z)=>Q4(P9(J0(Z))))($)}function O$($,Z){if(L0($)){let J=x0($)||{};switch(J.branding){case N4:return g(Z),J;case n$:return g(Z),Y1(J);case m1:return g(Z),kJ(V0,J)}return e9($,Z)}return g(Z),L9($)}function OW($){return $===void 0?void 0:O$($)}function mZ($,Z){if(Z=Q0(Z),L0($)){let W=x0($);return W&&W.branding===qZ?(g(Z),W):CJ(f4(y3($)),$,Z)}let J=D9(vZ,$);return g(Z),J}function L$($,Z){if(Z=Q0(Z),L0($)){let W=x0($)||{};switch(W.branding){case n$:return g(Z),W;case s$:return g(Z),G0({...W,...$1});case m1:return g(Z),RJ(V0,W)}return t9(k4(y3($)),$,Z)}let J=U9($);return g(Z),J}function w0($,Z){if(Z=Q0(Z),L0($)){let W=x0($)||{};switch(W.branding){case s$:return g(Z),W;case n$:return g(Z),K0(W);case m1:return g(Z),fJ(V0,W)}return xJ(k4(y3($)),$,Z)}let J=z4($);return g(Z),J}function fX($,Z,J){return J1(Z.call($,Y0(K0(J,$))))}function H1($){return(Z)=>typeof Z=="string"?vZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=w(W[z],J,J[z]);return j})(Z,$)}function W0($){if(L0($)){let Z=x0($);return Z&&Z.branding===I4?Z:$z($)}return M9($)}function w3($){if($!==void 0){if(L0($)){let Z=x0($)||{};switch(Z.branding){case m1:case s$:return Z;case n$:return K0(Z)}let J=y3($);return{...a9(a,i,k4(J),$),calendar:J}}return V9($)}}function y3($){return kX($)||q}function kX($){let{calendar:Z}=$;if(Z!==void 0)return I0(Z)}function I0($){return L0($)?(x0($)||{}).calendar||cU($):((Z)=>I3(H9(J0(Z))))($)}function hZ($,Z){if(Z=Q0(Z),L0($)){let J=x0($);if(J&&J.branding===m1)return N3(Z),J;let W=y3($);return r9(a,i,k4(W),W,$,Z)}return F9($,Z)}function CX($){return Z1((Z)=>(J)=>Z(FW(J)),$)}function FW($){return R0($,V0)}function zU(){let $=D$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(D$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);xW.set(this,((z,X={})=>{let Q=new D$(z,X),G=Q.resolvedOptions(),B=G.locale,V=p0(Object.keys(X),G),K=m0(GU),F=(...D)=>{let U,O=D.map((L,P)=>{let H=x0(L),I=(H||{}).branding;if(P&&U&&U!==I)throw TypeError(rz);return U=I,H});return U?K(U)(B,V,...O):[Q,...D]};return F.u=Q,F})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&XU(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||QU(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function XU($){return function(...Z){let J=xW.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function QU($){return function(...Z){return xW.get(this).u[$](...Z)}}function GU($){let Z=KU[$];if(!Z)throw TypeError(az($));return y1(Z,m0(wJ))}var KU={Instant:XW,PlainDateTime:QW,PlainDate:GW,PlainTime:KW,PlainYearMonth:BW,PlainMonthDay:VW},BU=y1(XW),VU=y1(_X),FU=y1(QW),UU=y1(GW),DU=y1(KW),OU=y1(BW),LU=y1(VW),LW={era:Uj,eraYear:M7,year:T3,month:J1,daysInMonth:J1,daysInYear:J1,inLeapYear:QX,monthsInYear:J1},b4={monthCode:J0},MW={day:J1},wX={dayOfWeek:J1,dayOfYear:J1,weekOfYear:Dj,yearOfWeek:M7,daysInWeek:J1},qX=Object.assign({},LW,b4,MW,wX),E4=new WeakMap,x0=E4.get.bind(E4),AX=E4.set.bind(E4),MU={...A4(LW,[qZ]),...A4(wX,[]),...A4(b4,[qZ,yZ]),...A4(MW,[yZ])},HW=DW(qX),HU=DW({...LW,...b4}),PU=DW({...b4,...MW}),v3={calendarId:($)=>P0($.calendar)},TU=Z1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Y0(K0(J,W))))},qX),NU=H3(($)=>(Z)=>Z[$],h.concat("sign")),PW=H3(($,Z)=>(J)=>J[z1[Z]],g1),yX={epochSeconds:vj,epochMilliseconds:o6,epochMicroseconds:gj,epochNanoseconds:mj},g3=w(D7,new Set(["branding"])),[_U,pZ,IU]=M1(yZ,w(Uz,I0),{...v3,...PU},{getISOFields:g3,getCalendar:q3,with($,Z,J){return pZ(jz(mU,$,this,cZ(Z),J))},equals:($,Z)=>w9($,IX(Z)),toPlainDate($,Z){return Y0(Sz(m3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=LU(Z,J,$);return W.format(Y)},toString:d7,toJSON:($)=>d7($),valueOf:P$},{from:($,Z)=>pZ(IX($,Z))}),vX={getOffsetNanosecondsFor:RX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,_0(G0(J,q)))].map((j)=>CU(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(E0),o7(s0(i0(W[0],W[Y-1])))),W}},UW={getOffsetNanosecondsFor:RX},[xU,k0,CU]=M1(_4,Gz,yX,{add:($,Z)=>k0(a7(0,$,W0(Z))),subtract:($,Z)=>k0(a7(1,$,W0(Z))),until:($,Z,J)=>s(LJ(0,$,O1(Z),J)),since:($,Z,J)=>s(LJ(1,$,O1(Z),J)),round:($,Z)=>k0(cj($,Z)),equals:($,Z)=>E9($,O1(Z)),toZonedDateTime($,Z){let J=w1(Z);return B0(bJ($,a(J.timeZone),I0(J.calendar)))},toZonedDateTimeISO:($,Z)=>B0(bJ($,a(Z))),toLocaleString($,Z,J){let[W,Y]=BU(Z,J,$);return W.format(Y)},toString:($,Z)=>g7(a,V0,$,Z),toJSON:($)=>g7(a,V0,$),valueOf:P$},{from:($)=>k0(O1($)),fromEpochSeconds:($)=>k0(Rz($)),fromEpochMilliseconds:($)=>k0(fz($)),fromEpochMicroseconds:($)=>k0(kz($)),fromEpochNanoseconds:($)=>k0(wz($)),compare:($,Z)=>UJ(O1($),O1(Z))}),[R4,YT]=M1("TimeZone",($)=>{let Z=A9($);return{branding:"TimeZone",id:Z,o:x4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(L$(Z)).map((J)=>k0(M0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(O1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=O1(Z).epochNanoseconds,W=S4(this,UW).getOffsetNanosecondsFor(J);return h$(W)},getPlainDateTimeFor($,Z,J=q){let W=O1(Z).epochNanoseconds,Y=S4(this,UW).getOffsetNanosecondsFor(W);return _0(G0(B$(W,Y),I0(J)))},getInstantFor($,Z,J){let W=L$(Z),Y=S7(J),j=S4(this);return k0(M0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>xX(1,$,Z),getPreviousTransition:({o:$},Z)=>xX(-1,$,Z),equals($,Z){return!!K4(this,a(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=a($);return typeof Z=="string"?new R4(Z):Z}}),AU=bX(Object.keys(vX)),[SU,M$]=M1(N4,Dz,PW,{getISOFields:g3,with($,Z,J){return M$(zz(this,cZ(Z),J))},add:($,Z)=>M$(ZJ(0,$,W0(Z))),subtract:($,Z)=>M$(ZJ(1,$,W0(Z))),until:($,Z,J)=>s(NJ(0,$,O$(Z),J)),since:($,Z,J)=>s(NJ(1,$,O$(Z),J)),round:($,Z)=>M$(lj($,Z)),equals:($,Z)=>q9($,O$(Z)),toZonedDateTime:($,Z)=>B0(Ez(a,w0,i,$,Z)),toPlainDateTime:($,Z)=>_0(bz($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=DU(Z,J,$);return W.format(Y)},toString:u7,toJSON:($)=>u7($),valueOf:P$},{from:($,Z)=>M$(O$($,Z)),compare:($,Z)=>G4(O$($),O$(Z))}),[EU,H$,bU]=M1(qZ,w(Fz,I0),{...v3,...HU},{getISOFields:g3,getCalendar:q3,with($,Z,J){return H$(Yz(gU,$,this,cZ(Z),J))},add:($,Z,J)=>H$($J(SX,0,$,W0(Z),J)),subtract:($,Z,J)=>H$($J(SX,1,$,W0(Z),J)),until:($,Z,J)=>s(TJ(EX,0,$,mZ(Z),J)),since:($,Z,J)=>s(TJ(EX,1,$,mZ(Z),J)),equals:($,Z)=>k9($,mZ(Z)),toPlainDate($,Z){return Y0(Az(m3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=OU(Z,J,$);return W.format(Y)},toString:c7,toJSON:($)=>c7($),valueOf:P$},{from:($,Z)=>H$(mZ($,Z)),compare:($,Z)=>d$(mZ($),mZ(Z))}),[RU,_0]=M1(n$,w(Bz,I0),{...v3,...HW,...PW},{getISOFields:g3,getCalendar:q3,with($,Z,J){return _0(Jz(m3,$,this,cZ(Z),J))},withCalendar:($,Z)=>_0(U4($,I0(Z))),withPlainDate:($,Z)=>_0(gz($,w0(Z))),withPlainTime:($,Z)=>_0(vz($,OW(Z))),add:($,Z,J)=>_0(t7(a$,0,$,W0(Z),J)),subtract:($,Z,J)=>_0(t7(a$,1,$,W0(Z),J)),until:($,Z,J)=>s(HJ(L1,0,$,L$(Z),J)),since:($,Z,J)=>s(HJ(L1,1,$,L$(Z),J)),round:($,Z)=>_0(uj($,Z)),equals:($,Z)=>R9($,L$(Z)),toZonedDateTime:($,Z,J)=>B0(Pz(i,$,a(Z),J)),toPlainDate:($)=>Y0(K0($)),toPlainTime:($)=>M$(Y1($)),toPlainYearMonth($){return H$(Tz(f4,$,this))},toPlainMonthDay($){return pZ(Nz(w4,$,this))},toLocaleString($,Z,J){let[W,Y]=FU(Z,J,$);return W.format(Y)},toString:h7,toJSON:($)=>h7($),valueOf:P$},{from:($,Z)=>_0(L$($,Z)),compare:($,Z)=>OJ(L$($),L$(Z))}),[fU,Y0,gX]=M1(s$,w(Vz,I0),{...v3,...HW},{getISOFields:g3,getCalendar:q3,with($,Z,J){return Y0(Wz(m3,$,this,cZ(Z),J))},withCalendar:($,Z)=>Y0(U4($,I0(Z))),add:($,Z,J)=>Y0(e7(a$,0,$,W0(Z),J)),subtract:($,Z,J)=>Y0(e7(a$,1,$,W0(Z),J)),until:($,Z,J)=>s(PJ(L1,0,$,w0(Z),J)),since:($,Z,J)=>s(PJ(L1,1,$,w0(Z),J)),equals:($,Z)=>f9($,w0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof R4?{timeZone:Z}:Z;return B0(_z(a,O$,i,$,J))},toPlainDateTime:($,Z)=>_0(Iz($,OW(Z))),toPlainYearMonth($){return H$(xz(f4,$,this))},toPlainMonthDay($){return pZ(Cz(w4,$,this))},toLocaleString($,Z,J){let[W,Y]=UU(Z,J,$);return W.format(Y)},toString:p7,toJSON:($)=>p7($),valueOf:P$},{from:($,Z)=>Y0(w0($,Z)),compare:($,Z)=>d$(w0($),w0(Z))}),TW={fields($,Z,J){return[...Z.call($,J)]}},mX=Object.assign({dateFromFields($,Z,J,W){return gX(Z.call($,Object.assign(Object.create(null),J),W))}},TW),hX=Object.assign({yearMonthFromFields($,Z,J,W){return bU(Z.call($,Object.assign(Object.create(null),J),W))}},TW),pX=Object.assign({monthDayFromFields($,Z,J,W){return IU(Z.call($,Object.assign(Object.create(null),J),W))}},TW),NW={mergeFields($,Z,J,W){return w1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},kU=Object.assign({},mX,NW),wU=Object.assign({},hX,NW),qU=Object.assign({},pX,NW),_W={dateAdd($,Z,J,W,Y){return gX(Z.call($,Y0(K0(J,$)),s(t(W)),Y))}},cX=Object.assign({},_W,{dateUntil($,Z,J,W,Y,j){return pU(Z.call($,Y0(K0(J,$)),Y0(K0(W,$)),Object.assign(Object.create(null),j,{largestUnit:E3[Y]})))}}),yU=Object.assign({},_W,{day:fX}),vU=Object.assign({},cX,{day:fX}),f4=H1(hX),k4=H1(mX),w4=H1(pX),gU=H1(wU),m3=H1(kU),mU=H1(qU),a$=H1(_W),L1=H1(cX),SX=H1(yU),EX=H1(vU),[hU,s,pU]=M1(I4,Oz,{...NU,blank:Q9},{with:($,Z)=>s(Xz($,Z)),negated:($)=>s(Y4($)),abs:($)=>s(X9($)),add:($,Z,J)=>s(zJ(w3,L1,i,0,$,W0(Z),J)),subtract:($,Z,J)=>s(zJ(w3,L1,i,1,$,W0(Z),J)),round:($,Z)=>s(z9(w3,L1,i,$,Z)),total:($,Z)=>pj(w3,L1,i,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):e6($)},toString:e6,toJSON:($)=>e6($),valueOf:P$},{from:($)=>s(W0($)),compare:($,Z,J)=>S9(w3,a$,i,W0($),W0(Z),J)}),dX={toString:($)=>$.id,toJSON:($)=>$.id,...MU,dateAdd:({id:$,o:Z},J,W,Y)=>Y0(K0(Z.dateAdd(w0(J),W0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>s(t($.dateUntil(w0(Z),w0(J),fj(W)))),dateFromFields:({id:$,o:Z},J,W)=>Y0(xJ(Z,J,W,Fj($))),yearMonthFromFields:({id:$,o:Z},J,W)=>H$(CJ(Z,J,W,Bj($))),monthDayFromFields:({id:$,o:Z},J,W)=>pZ(AJ(Z,0,J,W,Vj($))),fields({o:$},Z){let J=new Set(j1),W=[];for(let Y of Z){if(J0(Y),!J.has(Y))throw RangeError(yJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(O7(H7(Z)),O7(H7(J)))},[IW]=M1("Calendar",($)=>{let Z=d9($);return{branding:"Calendar",id:Z,o:vZ(Z)}},{id:($)=>$.id},dX,{from($){let Z=I0($);return typeof Z=="string"?new IW(Z):Z}}),cU=bX(Object.keys(dX).slice(4)),[dU,B0]=M1(m1,w(Kz,I0,a),{...yX,...v3,...CX(HW),...CX(PW),offset:($)=>h$(FW($).offsetNanoseconds),offsetNanoseconds:($)=>FW($).offsetNanoseconds,timeZoneId:($)=>P0($.timeZone),hoursInDay:($)=>ij(i,$)},{getISOFields:($)=>Y9(V0,$),getCalendar:q3,getTimeZone:({timeZone:$})=>typeof $=="string"?new R4($):$,with($,Z,J){return B0(Zz(m3,i,$,this,cZ(Z),J))},withCalendar:($,Z)=>B0(U4($,I0(Z))),withTimeZone:($,Z)=>B0(mz($,a(Z))),withPlainDate:($,Z)=>B0(yz(i,$,w0(Z))),withPlainTime:($,Z)=>B0(qz(i,$,OW(Z))),add:($,Z,J)=>B0(r7(a$,i,0,$,W0(Z),J)),subtract:($,Z,J)=>B0(r7(a$,i,1,$,W0(Z),J)),until:($,Z,J)=>s(t(MJ(L1,i,0,$,hZ(Z),J))),since:($,Z,J)=>s(t(MJ(L1,i,1,$,hZ(Z),J))),round:($,Z)=>B0(dj(i,$,Z)),startOfDay:($)=>B0(sj(i,$)),equals:($,Z)=>b9($,hZ(Z)),toInstant:($)=>k0(Lz($)),toPlainDateTime:($)=>_0(RJ(V0,$)),toPlainDate:($)=>Y0(fJ(V0,$)),toPlainTime:($)=>M$(kJ(V0,$)),toPlainYearMonth($){return H$(Mz(f4,$,this))},toPlainMonthDay($){return pZ(Hz(w4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=VU(Z,J,$);return W.format(Y)},toString:($,Z)=>m7(V0,$,Z),toJSON:($)=>m7(V0,$),valueOf:P$},{from:($,Z)=>B0(hZ($,Z)),compare:($,Z)=>DJ(hZ($),hZ(Z))}),uU=Object.defineProperties({},{...v6("Temporal.Now"),...v$({timeZoneId:()=>v1(),instant:()=>k0(M0(C3())),zonedDateTime:($,Z=v1())=>B0(N0(C3(),a(Z),I0($))),zonedDateTimeISO:($=v1())=>B0(N0(C3(),a($),q)),plainDateTime:($,Z=v1())=>_0(G0(kZ(V0(a(Z))),I0($))),plainDateTimeISO:($=v1())=>_0(G0(kZ(V0(a($))),q)),plainDate:($,Z=v1())=>Y0(K0(kZ(V0(a(Z))),I0($))),plainDateISO:($=v1())=>Y0(K0(kZ(V0(a($))),q)),plainTimeISO:($=v1())=>M$(Y1(kZ(V0(a($)))))})}),dZ=Object.defineProperties({},{...v6("Temporal"),...v$({PlainYearMonth:EU,PlainMonthDay:_U,PlainDate:fU,PlainTime:SU,PlainDateTime:RU,ZonedDateTime:dU,Instant:xU,Calendar:IW,TimeZone:R4,Duration:hU,Now:uU})}),lU=zU(),xW=new WeakMap,iU=Object.defineProperties(Object.create(Intl),v$({DateTimeFormat:lU}));var q4="x-gemi-socket";var KT="gemi.v1",uX="/__gemi/socket",BT=/^[A-Za-z0-9_-]{1,32}$/,VT={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function OT($){return $}function lX(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:uX,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as sU,randomBytes as nU}from"crypto";function oU($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(sU("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var aU="__control",CW=250,rU=1e4,tU=15000;class AW{config;prefix;controlChannel;instanceId=nU(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??oU(),this.controlChannel=this.prefix+aU,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=h3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),tU,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${iX(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(rU,CW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(CW,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;h3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${iX(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??eU(Math.min(Z,CW));await h3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await h3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await h3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function h3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function eU($){return new Promise((Z)=>setTimeout(Z,$))}function iX($){return $ instanceof Error?$.message:String($)}import{createHmac as $D,hkdfSync as ZD,randomBytes as sX}from"crypto";function nX($){return $D("sha256",JD()).update($).digest("base64url").slice(0,22)}var y4=null;function JD(){let $=process.env.SECRET||void 0;if(y4&&y4.secret===$)return y4.key;let Z=$?Buffer.from(ZD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):sX(32);return y4={secret:$,key:Z},Z}function TT(){return sX(16).toString("base64url")}var WD=/^[A-Za-z0-9_-]{8,64}$/;function SW($){return typeof $==="string"&&WD.test($)}function oX($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class rX extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=P1(lX(),$),this.driver=zD(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new p3(this,v4($,Z[0]),null)}toUser($){return new p3(this,{topic:KZ($),pattern:U0},null)}toOthers($){return new tX(this,jD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(v4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){T5(Z);let Y;try{Y=oX($.topic,Z,J,W?nX(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){uZ(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=YD($);uZ(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new rX(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class p3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class tX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new p3(this.manager,v4($,Z[0]),this.except)}toUser($){return new p3(this.manager,{topic:KZ($),pattern:U0},this.except)}}function v4($,Z){if(P5($))return{topic:_8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:z3($,Z??{}),pattern:$};if($===U0)throw new u('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:_8($)}}function YD($){if($&&typeof $==="object"&&"user"in $)return{user:KZ($.user).slice(U0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:v4($.channel,$.params).topic};throw new u("Broadcast.revoke takes { user } or { channel }.")}function jD($){if($===null||$===void 0)return null;if(typeof $==="string")return SW($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(q4);return SW(J)?J:null}function zD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new aX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new AW({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class EW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class XD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as bW,createHmac as QD,randomBytes as eX,timingSafeEqual as JQ}from"crypto";var d3=600,g4="gemi_oauth",GD=`__Host-${g4}`;function lZ($,Z=g4){if(Z===g4)return $?GD:g4;return $?`__Host-${Z}`:Z}function c3($){return $.toString("base64url")}function WQ($){return QD("sha256",DZ()).update(`gemi-oauth-state:${$}`).digest()}function $Q($,Z){let J=bW("sha256").update($).digest(),W=bW("sha256").update(Z).digest();return JQ(J,W)&&$.length===Z.length}function m4($,Z=Date.now(),J={}){let W=c3(eX(32)),Y=c3(eX(32)),j=KD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+d3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:BD(z)}}function KD($){return c3(bW("sha256").update($).digest())}function BD($){let Z=c3(Buffer.from(JSON.stringify($)));return`${Z}.${c3(WQ(Z))}`}function VD($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=WQ(J);if(W.length!==Y.length||!JQ(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string")return null;return j}catch{return null}}var T$=new Map,ZQ=1e4;function FD($,Z,J){if(T$.size>=ZQ){for(let[W,Y]of T$)if(Y<=J)T$.delete(W);while(T$.size>=ZQ){let W=T$.keys().next().value;if(W===void 0)break;T$.delete(W)}}T$.set($,Z)}function h4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=VD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=$Q(J.state,$.returnedState),Y=$Q(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(T$.has(J.state))return{ok:!1,reason:"invalid_state"};return FD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var RW=new WeakMap;function DD($){let Z=RW.get($);if(!Z)Z=$(UD(32).toString("hex")),RW.set($,Z),Z.catch(()=>RW.delete($));return Z}async function fW($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await DD($.hashPassword))}catch{}return!1}async function r$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class wW extends Error{}function kW($){return typeof $==="string"&&$!==""?$:null}function YQ($){return G3($)}var OD=256;function jQ($){return typeof $==="string"&&$!==""&&$.length<=OD?$:null}function zQ($){let{password:Z,code:J,...W}=$;return W}var p4="intended_url";function QQ($){if($.cookies.get(p4))$.ctx().setCookie(p4,"",{maxAge:-1})}function XQ($){let Z=$.cookies.get(p4);if(!Z)return null;QQ($);try{return B1(decodeURIComponent(Z),"")||null}catch{return null}}class qW extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class GQ extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class KQ extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function h1($){if(M(E).config[$]===!1)throw new z0("Not found",{status:404})}class e extends Q3{async me(){let $=await q0.user();if(!$)throw new p8;return $}async verifyEmail($=new C){h1("password");let Z=await $.input(),{userProvider:J}=M(E),W=kW(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=M(E),{userProvider:J}=Z,W=kW($.search.get("token")),Y=null;try{Y=G3(decodeURIComponent($.search.get("email")??""))}catch{}if(await LZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,M(E).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await r$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){h1("magicLink");let Z=M(E),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=G3(W),z=jQ(Y);if(await LZ("verify",j,$,Z.config.emailCode.verifyLimit),!j||!z)throw new d({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new d({pin:["Too many attempts"]});if(X.status!=="ok")throw new d({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await r$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=M(E),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,M(E).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await r$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new qW){h1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await fW(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(E).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await r$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signIn($=new qW){h1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(E),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await fW(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(E).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await r$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signUp(){h1("password");let $=M(E),{userProvider:Z,config:J}=$,W=new J.signUpRequest,Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G={method:"password",input:zQ(Y.toJSON())},B=YQ(j);if(!B)throw new d({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new d({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new d({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(B,!1))throw new d({email:["Email address already exists"]});let K=await J.hashPassword(z),F=M(c).detectLocale(W),D;if(Q)D=await Z.findInvitation(Q,B);let U,O="";if(D)U=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let L=await Z.createUser({email:B,name:X,password:K,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:D.organizationId,userId:L.id,organizationRole:D.role}),await J.onUserCreated(L,G),L});else O=await J.generateEmailVerificationToken(B),U=await Z.transaction(async()=>{let L=await Z.createUser({email:B,name:X,password:K,verificationToken:O,locale:F});return await J.onUserCreated(L,G),L});return await J.onSignUp(U,O,W.search.toJSON()),U}async signOut($=new C){let Z=S$($),J=M(E),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",M(E).accessTokenCookieOptions($,new Date(0))),M(E).cookieDomain($))$.ctx().setCookie("access_token","",{...M(E).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)LD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user);return{}}async forgotPassword($=new GQ){h1("password");let Z=await $.input(),J=YQ(Z.get("email"));if(!J)return{};let{userProvider:W,config:Y}=M(E),j=await W.findUserByEmailAddress(J,Y.verifyEmail);if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z),{}}async resetPassword($=new KQ){h1("password");let{userProvider:Z,config:J}=M(E),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=kW(j),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new d({token:["Invalid token"]});if(dZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(dZ.Now.instant()).sign>=0)throw new d({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new d({email:["User not found"]});let B=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:B}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new C){h1("password");let{userProvider:Z,config:J}=M(E),W=await q0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new d({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof j==="string"&&await fW(J,j,X?.password)))throw new d({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=M(E).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await MZ(J,Z);if(!Y){if(W)throw new z0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=BZ($.rawRequest),z=B1($.search.get(K1),"");if(z)$.ctx().setCookie(p4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else QQ($);let{state:X,codeChallenge:Q,cookieValue:G}=m4(Z);return $.ctx().setCookie(lZ(j),G,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:d3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=M(E),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await MZ(Y.oauthProviders,Z);if(j&&!z)throw new z0("Not found",{status:404});let X=BZ($.rawRequest),Q=lZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let B=$.search.get("error");if(B)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");let V=h4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let K;try{K=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(N){if(N instanceof EW)return this.oauthFailure($,N.code);return console.error("Authentication error: OAuth provider callback failed",N),this.oauthFailure($,"provider_error")}let{name:F,username:D,providerId:U,emailVerified:O}=K??{},L=typeof K?.email==="string"?K.email:void 0,P=L?H6(L):null,H=U?await W.findUserBySocialAccount(Z,U):null,I="signin",S=!H&&!P&&!L&&!!U&&z.createUsersWithoutEmail===!0;if(!H&&S){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{H=await this.createOAuthUserWithoutEmail({provider:Z,providerId:U,name:F,username:D,locale:M(c).detectLocale($)}),I="signup"}catch(N){let v=await W.findUserBySocialAccount(Z,U);if(!v)throw N;H=v}}if(!H){if(!P)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,L?"invalid_email":U?"missing_email":"no_identity");if(O===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let N=M(c).detectLocale($);try{let v=await this.linkOAuthAccount({provider:Z,providerId:U,email:P,rawEmail:L,name:F,username:D,locale:N,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(v==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(v==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(v)H=v.user,I=v.action}catch(v){let _=U?await W.findUserBySocialAccount(Z,U):null;if(!_)throw v;H=_}if(!H)return this.oauthFailure($,"account_conflict")}let A=await J.createOrUpdateSessionV2({email:H.email,id:H.id});if($.ctx().setCookie("access_token",A.token,M(E).accessTokenCookieOptions($,A.expiresAt)),I==="signup")await Y.onSignUp(H,"",$.search.toJSON());else await Y.onSignIn(H,$.search.toJSON());await r$(J.config,{session:A,user:H,isNewUser:I==="signup",method:"oauth",req:$});let b=XQ($)??Y.redirectPath,k=Y.oauthCompleteProfilePath?B1(Y.oauthCompleteProfilePath,""):"";if(k&&!H.email){let N=new URL(k,"http://gemi.invalid");N.searchParams.set(K1,b),b=`${N.pathname}${N.search}${N.hash}`}return{session:A,redirectTo:b}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=M(E);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{}}),W})}oauthFailure($,Z){let J=XQ($),W=M(E).config.oauthFailurePath;if(W){let Y=B1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(K1,J);C1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=M(E),B=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await Q.findUserByEmailAddress(W,!1),K=Y?.trim();if(!V&&K&&K!==W)V=await Q.findUserByEmailAddress(K,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!J)return{user:V,action:"signin"};let D=await Q.findSocialAccounts(V.id,Z);if(D.some((O)=>O.providerId===J))return{user:V,action:"signin"};if(D.some((O)=>O.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let U=D[0];if(U){if(!await Q.claimSocialAccount(U,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(B(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let D=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(B(D.id));return await G.onUserCreated(D,{method:"oauth",input:{}}),D}),action:"signup"}}async createMagicLinkToken($=new C){h1("magicLink");let Z=await $.input(),J=G3(Z.get("email")),W=M(E),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await LZ("request",J,$,j),!J)return{email:null};let{user:z,pin:X,token:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=M(E),J=Z.config.emailCode;if(!J.enabled)throw new z0("Not found",{status:404});let W=await $.input(),Y=H6(W.get("email"));if(await LZ("request",Y,$,J.requestLimit),!Y)throw new d({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=M(E),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new z0("Not found",{status:404});let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=H6(j),G=jQ(z);if(await LZ("verify",Q,$,W.emailCode.verifyLimit),!Q||!G)throw new d({code:["invalid_code"]});let B=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(B.status==="too_many_attempts")throw new d({code:["too_many_attempts"]});if(B.status!=="ok")throw new d({code:["invalid_code"]});let V=B.row,K=await J.findUserByEmailAddress(Q,!1),F=!1;if(K){if(!await Z.claimOneTimeCode(Q,V.id))throw new d({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let U=M(c).detectLocale($);try{K=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(Q,V.id))throw new wW;let O=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await W.onUserCreated(O,{method:"email-code",input:zQ(Y.toJSON())}),O}),F=!0}catch(O){if(O instanceof wW)throw new d({code:["invalid_code"]});throw O}}else throw await Z.claimOneTimeCode(Q,V.id),new d({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:Q,id:K.id});return $.ctx().setCookie("access_token",D.token,M(E).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON()),await r$(Z.config,{session:D,isNewUser:F,method:"email-code",req:$}),{session:D,isNewUser:F}}}function LD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=M();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var BQ="gemi_oauth_connection";class c4 extends Q3{async connect($=new C){let Z=String($.params.provider??""),W=M(u3).providers[Z],Y=await q0.user(),j=B1($.search.get(K1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=BZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=m4(VQ(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(lZ(z,BQ),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:d3}),C1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:FQ($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=M(u3),W=await q0.user(),Y=BZ($.rawRequest),j=lZ(Y,BQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=h4({provider:VQ(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let B=$.search.get("error");if(B)return this.finish(Q,Z,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(Q,Z,"missing_code");try{let K=await G.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:FQ($,Z,G.config.redirectUri)}),F=await J.save(W,Z,K);await M(E).config.onConnected({user:W,provider:Z,connection:F,profile:K.profile??null,req:$})}catch(K){if(K instanceof UQ)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(Q,Z,K.providerError??K.code);throw K}return this.finish(Q,Z)}finish($,Z,J){let W=$||B1(M(E).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw C1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function VQ($){return`connection:${$}`}function FQ($,Z,J){if(J)return J;return`${t$()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function DQ($){return $.magicLink!==!1||$.emailCode?.enabled===!0}function OQ($){return Object.keys($.oauthProviders??{}).length>0}function LQ($={}){let Z=[];if(DQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:$.emailCode?.enabled===!0&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(OQ($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class MQ extends A1{middlewares=["cache:private"];routes={"/:provider":this.redirect([c4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([c4,"callback"]).middleware([K6,"auth"])}}function HQ($={}){let Z=DQ($),J=OQ($);class W extends A1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[e,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[e,"oauthCallback"])}}return class extends A1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[e,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":MQ}}}class yW extends C0{middlewares=["cache:private"];routes={"/sign-in":this.post(e,"signIn"),"/sign-in-v2":this.post(e,"signInV2"),"/sign-up":this.post(e,"signUp"),"/sign-out":this.post(e,"signOut"),"/forgot-password":this.post(e,"forgotPassword"),"/reset-password":this.post(e,"resetPassword"),"/change-password":this.post(e,"changePassword"),"/verify-email":this.post(e,"verifyEmail"),"/me":this.get(e,"me").middleware(["auth"]),"/magic-link":this.post(e,"createMagicLinkToken"),"/sign-in-with-pin":this.post(e,"signInWithPin"),"/sign-in-with-pin-v2":this.post(e,"signInWithPinV2"),"/email-code":this.post(e,"requestEmailCode"),"/email-code/verify":this.post(e,"verifyEmailCode")}}class vW extends C0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await M(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=M(c),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class gW{}class mW extends gW{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await d4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function RN($){return $}function PQ(){return{driver:new mW,allowedHosts:[],maxSize:10485760,timeout:1e4}}class F0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var MD=new Set([301,302,303,307,308]),HD="/api/__gemi__/services/image/";async function NQ($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=TQ($,Y);try{for(let z=0;;z++){let X=await PD(j,Z,W),Q=X.headers.get("location");if(MD.has(X.status)&&Q){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new F0(502,"The image redirects too many times");j=TQ(Q,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new F0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new F0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw ND(z,W)}}function TQ($,Z){let J;try{J=new URL($,Z)}catch{throw new F0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new F0(400,"Only http(s) images can be resized");return J}async function PD($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(HD))throw new F0(403,"This image source is not allowed");if(TD($.pathname))throw new F0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return S1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new F0(403,"This image source is not allowed");return S1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function TD($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function ND($,Z){if($ instanceof F0)return $;if(Z.aborted)return new F0(504,"The image took too long to load",{cause:$});if($ instanceof V6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new F0(403,"This image source is not allowed",{cause:$});case"too-large":return new F0(413,"The image is too large",{cause:$});case"timeout":return new F0(504,"The image took too long to load",{cause:$})}return new F0(502,"The image could not be loaded",{cause:$})}class hW extends C0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return _Q(400,"url query parameter is required");let X=M(IQ),Q=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],G=t$();if(G&&URL.canParse(G))Q.push(new URL(G).origin);let B;try{B=await NQ(J,{ownOrigins:Q,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(F){if(F instanceof F0)return _Q(F.status,F.message);throw F}let V=await X.resize(B.bytes,{height:Y,width:W,fit:j,quality:z}),K=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(B.cacheControl)K.set("Cache-Control",B.cacheControl);return new Response(new Uint8Array(V),{headers:K})})}}function _Q($,Z){return Response.json({error:Z},{status:$})}class IQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=PQ();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class pW extends C0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(M(xQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function iN($){return $}function CQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function AQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function _D($){return"run"in $}function ID($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function xD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function CD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function AD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function SQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function SD($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function cW($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let B=j==="/"?"":j,V=Z==="/"?"":Z,K=SD((`${V}${B}`===""?"/":`${V}${B}`).replaceAll("//","/"));if(!W[K])W[K]={};W[K][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[K].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(AD(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(_D(z)){let X=z,Q=X.method,G=X.middlewares,B=X.run.bind(X);if(Y(j,Q,B,G,X.source),SQ(z))Y(j,"HEAD",B,G,X.source)}if(ID(z))for(let[X,Q]of Object.entries(z)){let G=Q,B=G.middlewares,V=G.run.bind(G);if(Y(j,X,V,B,G.source),X==="get"&&SQ(G))Y(j,"HEAD",V,B,G.source)}if(CD(z)){let X=new z,Q=cW(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[G,B]of Object.entries(Q)){let V=G.replaceAll("//","/");W[V]={...W[V],...B}}}if(xD(z)){let{first:X,second:Q}=z;for(let[G,B]of Object.entries(X)){let V=B.middlewares,K=B.run.bind(B),[F,...D]=j.split("/").reverse();if(!F.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),G,K,V,B.source)}for(let[G,B]of Object.entries(Q)){let V=B.middlewares,K=B.run.bind(B);Y(j,G,K,V,B.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function u4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function dW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function uW($){let Z=u4($);return Z.length>1?Z.replace(/\/$/,""):Z}function EQ($,Z){return Z.map((J)=>({...J,path:uW(dW($,J.path))}))}function l4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=l4(j.routes);for(let[X,{exec:Q,middleware:G,segments:B,features:V,static:K}]of Object.entries(z)){let F=dW(J,X),D=(U)=>Y.run.call(Y,U,J);Z[u4(F)]={exec:[D,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...V],viewPath:Y.viewPath,segments:[{path:uW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...EQ(J,B)],...K?{static:K}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[u4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:uW(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=l4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:B,features:V,static:K}]of Object.entries(j)){let F=dW(J,z);Z[u4(F)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...V],viewPath:G,segments:EQ(J,B),...K?{static:K}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var lW="theme";function bQ($){return $==="light"||$==="dark"||$==="system"}function RQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
|
|
13
|
+
`)}function pB($,Z={}){let J=new Headers(Z.headers);if(!J.has("content-type"))J.set("content-type","text/plain; charset=utf-8");return new Response(Bj($),{status:200,headers:J})}var Vj={response:pB,text:Bj,parse:Kj,fetch:hB};import{createHmac as Fj,randomBytes as cB}from"crypto";var c8="v2.";function d8($){return $.startsWith(c8)}function DZ(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function Uj($){let Z=cB(16).toString("hex"),J=Fj("sha256",DZ()).update(`${$}:${Z}`).digest("hex");return`${c8}${J}`}function L6($,Z){let J=Fj("sha256",DZ()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${c8}${J}`}import{createHash as lB,createHmac as iB,randomInt as sB,timingSafeEqual as Lj}from"crypto";function Dj($,Z){return Math.floor($/Z)*Z}function dB($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function u8($,Z,J,W){return Z*dB(J,W)+$}function uB($){let{current:Z,previous:J,elapsed:W,window:Y,limit:j,cost:z}=$,X=j-z;if(X<0)return Y;let Q=Math.max(0,Y-W);if(J>0){let B=Y*(1-(X-Z)/J);if(B<=Y)return Math.max(0,Math.ceil(B-W))}if(Z<=X)return Q;if(Z<=0)return Q;let G=Y*(1-X/Z);return Q+Math.max(0,Math.ceil(G))}function Oj($){let{allowed:Z,current:J,previous:W,now:Y,elapsed:j,window:z,limit:X,cost:Q}=$;if(Z){let B=u8(J,W,j,z);return{allowed:!0,limit:X,remaining:Math.max(0,Math.floor(X-B)),resetAt:Y-j+z,retryAfter:0}}let G=uB({current:J,previous:W,elapsed:j,window:z,limit:X,cost:Q});return{allowed:!1,limit:X,remaining:0,resetAt:Y+G,retryAfter:G}}class l8{}class i8 extends l8{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:J,window:W}=$,Y=$.cost??1,j=Date.now(),z=Dj(j,W),X=j-z,Q=this.roll(Z,W,z);Q.limit=J;let B=u8(Q.current,Q.previous,X,W)+Y<=J;if(B)Q.current+=Y;if(this.buckets.delete(Z),this.buckets.set(Z,Q),this.buckets.size>this.maxKeys)this.evict(j);return Oj({allowed:B,current:Q.current,previous:Q.previous,now:j,elapsed:X,window:W,limit:J,cost:Y})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,J){let W=this.buckets.get($);if(!W||W.window!==Z)return{window:Z,limit:0,windowStart:J,current:0,previous:0};if(W.windowStart===J)return W;if(W.windowStart+Z===J)return W.previous=W.current,W.current=0,W.windowStart=J,W;return W.previous=0,W.current=0,W.windowStart=J,W}evict($){for(let[W,Y]of this.buckets)if($-Y.windowStart>=Y.window*2)this.buckets.delete(W);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let J=[...this.buckets].map(([W,Y],j)=>({key:W,order:j,spent:Y.limit>0?(Y.current+Y.previous)/Y.limit:0}));J.sort((W,Y)=>W.spent-Y.spent||W.order-Y.order);for(let{key:W}of J){if(this.buckets.size<=Z)break;this.buckets.delete(W)}}}var Pj="h1.";function M6($,Z,J){let W=iB("sha256",DZ()).update(`gemi:one-time:${$}:${Z}:${J}`).digest("hex");return`${Pj}${W}`}function OZ($,Z,J,W){let Y=typeof W==="string"?W:"",j=typeof J==="string"?J:"",z=j.startsWith(Pj),X=M6($,Z,Y),Q=Buffer.from(z?X:Y),G=Buffer.from(j);if(Q.length!==G.length||Y===""||j==="")return Lj(Q,Q),!1;return Lj(Q,G)}function Tj($){let Z="";for(let J=0;J<$;J++)Z+=String(sB(0,10));return Z}var Nj=320;function K3($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>Nj)return null;return Z.toLowerCase()}function H6($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>Nj)return null;let J=Z.toLowerCase();if(J.length<3||J.length>254||!/^[^\s@]+@[^\s@]+$/.test(J))return null;return J}var Mj=null;function _j(){try{let $=M();if(typeof $?.bound==="function"&&$.bound(F1))return $.make(F1)}catch{}return Mj??=new F1({driver:new i8,limit:1000,window:60}),Mj}function Hj($){return $.length<=64?$:`sha256:${lB("sha256").update($).digest("hex")}`}async function LZ($,Z,J,W){let Y=_j(),j=[[`auth:code-${$}:ip:${Hj(VZ(J))}`,W.perIp]];if(Z!==null)j.push([`auth:code-${$}:email:${Hj(Z)}`,W.perEmail]);for(let[z,X]of j){if(!X)continue;let[Q,G]=X,B=await Y.consume(z,{limit:Q,window:G});if(!B.allowed)throw new W$(B)}}async function Ij($,Z,J,W=10){let Y=Math.max(86400,Math.ceil(W*60*(J+1)));return(await _j().consume(`auth:code-attempt:${$}:${Z}`,{limit:J,window:Y})).allowed}import{randomBytes as n8}from"crypto";class s8 extends C{schema={name:{string:"Invalid name",required:"Name is required","min:2":"Name must be at least 3 characters"},email:{string:"Invalid email",required:"Email is required",email:"Invalid email"},password:{"min:8":"Password must be at least 9 characters"}}}function B3($,Z,J,W=1/0){if(!Number.isInteger(Z)||Z<J||Z>W){let Y=W===1/0?`an integer of at least ${J}`:`an integer from ${J} to ${W}`;throw Error(`auth.emailCode.${$} must be ${Y}, got ${Z}`)}}function nB($={}){for(let Z of["password","magicLink"]){let J=$?.[Z];if(J!==void 0&&typeof J!=="boolean")throw Error(`auth.${Z} must be true or false, got ${JSON.stringify(J)}`)}}function o8($={}){let Z=$.length??6,J=$.expiresInMinutes??10,W=$.linkExpiresInMinutes??10080,Y=$.maxAttempts??5,j=$.activeCodes??1;return B3("length",Z,4,12),B3("expiresInMinutes",J,1),B3("linkExpiresInMinutes",W,1),B3("maxAttempts",Y,1),B3("activeCodes",j,1,5),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:J,linkExpiresInMinutes:W,maxAttempts:Y,activeCodes:j,requestLimit:{perEmail:$.requestLimit?.perEmail??[5,900],perIp:$.requestLimit?.perIp??[20,900]},verifyLimit:{perEmail:$.verifyLimit?.perEmail??[10,900],perIp:$.verifyLimit?.perIp??[50,900]},uniformMagicLinkResponse:$.uniformMagicLinkResponse??!1,send:$.send??(({email:z,code:X})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${X} (set auth.emailCode.send to deliver it)`)})}}async function oB($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function xj($){if(!$)return null;if(typeof $.getRedirectUrl==="function")return{provider:$};let{provider:Z,feature:J}=$;return{provider:Z,...J!==void 0?{feature:J}:{}}}function Cj($){for(let[Z,J]of Object.entries($??{})){if(typeof J?.getRedirectUrl==="function")continue;let W=J;if(typeof W?.provider?.getRedirectUrl!=="function")throw Error(`auth.oauthProviders.${Z} must be an OAuthProvider, or { provider, feature } with an OAuthProvider.`);if(W.feature!==void 0&&(typeof W.feature!=="string"||W.feature===""))throw Error(`auth.oauthProviders.${Z}.feature must be a feature key from app/features.`)}}function CP($){return $}function Aj($={}){return nB($),{basePath:"/auth",verifyEmail:!0,password:!0,magicLink:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:s8,oauthProviders:{},oauthFailurePath:null,oauthCompleteProfilePath:null,connections:{},connectionStore:null,onConnected:()=>{},verifyPassword:oB,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>n8(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return n8(32).toString("hex")},generateMagicLinkToken:()=>n8(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:o8($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}var aB=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),rB=new Set(["svg","math"]);function Sj($){return $===32||$===9||$===10||$===12||$===13}function Ej($){return $>=65&&$<=90||$>=97&&$<=122}function P6($){return $>=65&&$<=90?$+32:$}function bj(){let $="data",Z="",J=!1,W="",Y=0,j=0,z=!1,X=0,Q=0,G=()=>$==="data"&&X===0&&Q===0,B=()=>{if(!J&&aB.has(Z)){$="rawText",W=`</${Z}`,Y=0,Z="";return}if($="data",Z==="template")if(J)X=Math.max(0,X-1);else X+=1;else if(rB.has(Z)){if(J)Q=Math.max(0,Q-1);else if(!z)Q+=1}Z=""},V=(K)=>{switch($){case"data":if(K===60)$="tagOpen";return;case"tagOpen":if(K===33)$="bang",j=0;else if(K===47)$="endTagOpen";else if(Ej(K))$="tagName",J=!1,z=!1,Z=String.fromCharCode(P6(K));else if(K===63)$="bogus";else if(K===60)$="tagOpen";else $="data";return;case"endTagOpen":if(Ej(K))$="tagName",J=!0,z=!1,Z=String.fromCharCode(P6(K));else if(K===62)$="data";else $="bogus";return;case"tagName":if(Sj(K)||K===47)$="inTag",z=K===47;else if(K===62)B();else Z+=String.fromCharCode(P6(K));return;case"inTag":if(K===62){B();return}if(z=K===47,K===34)$="attrDouble";else if(K===39)$="attrSingle";return;case"attrDouble":if(K===34)$="inTag";z=!1;return;case"attrSingle":if(K===39)$="inTag";z=!1;return;case"bang":if(K===45){if(j+=1,j===2)$="comment",j=0}else if(K===62)$="data";else $="bogus";return;case"bogus":if(K===62)$="data";return;case"comment":if(K===45)j=j<2?j+1:2;else if(K===62&&j>=2)$="data",j=0;else j=0;return;case"rawText":{if(Y<W.length){if(P6(K)===W.charCodeAt(Y))Y+=1;else Y=K===60?1:0;return}if(K===62)$="data",Z="";else if(Sj(K)||K===47)$="inTag",Z="";else Y=K===60?1:0;return}}};return{scanToInsertionPoint(K){for(let F=0;F<K.length;F++){if(G())return F;V(K[F])}return K.length},write(K){for(let F=0;F<K.length;F++)V(K[F])},isSafe:G}}function r0($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function tB($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${r0([$.path,$.variantKey,$.data])})</script>`}function eB($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${r0([$.id,$.locale,$.strings])})</script>`}function a8($,Z,J={},W){let Y=new TextEncoder,j=[],z=!1,X=!1,Q=()=>{if(X)return;X=!0,J.onClose?.()};Z.onSettle((D)=>{if(D.status!=="resolved")return;j.push(tB(D))}),W?.onUse((D)=>{j.push(eB(D))});let G=$.getReader(),B=bj(),V=(D,U)=>{D.enqueue(U),J.onChunk?.(U)},K=(D)=>{while(j.length>0){let U=Y.encode(j.shift());B.write(U),V(D,U)}},F=(D,U)=>{if(j.length===0){B.write(U),V(D,U);return}let O=B.scanToInsertionPoint(U);if(O>0)V(D,U.subarray(0,O));if(B.isSafe())K(D);let L=U.subarray(O);if(L.length>0)B.write(L),V(D,L)};return new ReadableStream({async pull(D){let U;try{U=await G.read()}catch(P){throw Q(),P}let{done:O,value:L}=U;if(O){K(D),D.close(),Q();return}if(!z){if(z=!0,B.write(L),V(D,L),J.onShell?.(),B.isSafe())K(D);return}F(D,L)},cancel(D){return Q(),G.cancel(D)}})}var $V=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function T6($){if(!$)return!1;return $V.test($)}async function fj($,Z=()=>{}){let J=T.getStore(),W=J?.req??null,Y=null;if(W?.rawRequest?.url)try{Y=new URL(W.rawRequest.url).pathname}catch{Y=null}return{user:J?.user??null,attributes:await ZV($,Z),request:{path:Y,routePath:W?.routePath??null,locale:J?.locale??null},anonymousId:Rj(),isBot:T6(W?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function kj($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function ZV($,Z){if(!$.context)return{};try{let J=T.getStore();return await $.context(J?.req??null)??{}}catch(J){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${J instanceof Error?J.message:String(J)}`),{}}}function wj($,Z){return`${$}:${Z}`}function r8($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),J=Number.parseInt(Z.slice(0,8),16);return Math.floor(J/4294967296*1e4)}function qj($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function yj($,Z,J,W){if(W.unavailable)return{value:!1,reason:"unavailable"};if(W.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let j;try{j=Z.when(J)}catch(z){return W.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${z instanceof Error?z.message:String(z)}`),{value:!1,reason:"error"}}if(typeof j==="boolean")return{value:j,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(J.isBot)return{value:!1,reason:"bot"};let Y=WV($,Z,J,W.buckets);return qj(Y,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function JV($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function WV($,Z,J,W){let Y=wj(Z.salt??$,JV(J));if(!W)return r8(Y);let j=W.get(Y);if(j!==void 0)return j;let z=r8(Y);return W.set(Y,z),z}class vj extends Error{cause;kind="FeatureReloadFailed";constructor($){super(`Could not reload feature switches after a write, so the cached switches may still predate it: ${$ instanceof Error?$.message:String($)}`);this.cause=$}}class t8{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,J,W=()=>{}){this.source=$;this.declared=Z;this.ttlMs=J;this.warn=W}async get(){let $=this.snapshot;if($&&Date.now()-$.loadedAt<this.ttlMs)return $;if($){if(Date.now()>=this.retryAfter)this.refresh().catch(()=>{});return $}return await this.refresh()}refresh(){return this.inflight??=this.load().finally(()=>{this.inflight=null}),this.inflight}async invalidate(){await this.inflight?.catch(()=>{});let $=this.generation,Z=await this.refresh();if(this.generation===$)throw new vj(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:J}=this.readRows($);return this.snapshot={active:Z,audit:J,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,J=new Map;for(let W of $??[]){let Y=typeof W?.key==="string"?W.key:null;if(!Y){this.warn("Ignoring a feature row with no `key`.");continue}if(!(Y in this.declared)){this.warn(`Feature row "${Y}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(Y,W.active===!0);let j=YV(W);if(j)J.set(Y,j)}return{active:Z,audit:J}}handleFailure($){let Z=$ instanceof Error?$.message:String($),J=Date.now();if(this.lastError=$,this.retryAfter=J+this.ttlMs,J-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=J,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:J,unavailable:!0},this.snapshot}}function YV($){let Z={},J=$.updatedBy;if(typeof J==="string")Z.updatedBy=J;else if(J===null)Z.updatedBy=null;let W=$.updatedAt;if(W instanceof Date||typeof W==="string"||typeof W==="number"){let Y=W instanceof Date?W:new Date(W);if(!Number.isNaN(Y.getTime()))Z.updatedAt=Y}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class jV{}class zV extends Error{modelName;kind="FeatureModelMissing";constructor($){super(`No "${$}" model is registered, so every feature stays off. Add the model to prisma/schema.prisma and export it from app/models \u2014 see docs/feature-flags.md.`);this.modelName=$}}class e8 extends Error{sourceName;kind="FeatureSourceReadOnly";constructor($){super(`The feature source (${$}) is read-only, so Features.set() cannot write to it. Change the switch where that source reads from, or give the source a write() method.`);this.sourceName=$}}class gj extends Error{key;kind="UndeclaredFeature";constructor($){super(`"${$}" is not declared in app/features, so it cannot be switched. A row for it would be ignored \u2014 declare the feature first.`);this.key=$}}class mj{manager;ctx;constructor($,Z){this.manager=$;this.ctx=Z}async enabled($){return(await this.explain($)).value}async explain($){return await this.manager.evaluateIn($,this.ctx,new Map)}async all(){return await this.manager.evaluateAllIn(this.ctx,new Map,{clientOnly:!1})}}class Y${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new t8($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:J}=await this.switches();return{unavailable:J,features:Object.entries(this.declared).map(([W,Y])=>({key:W,describe:Y.describe,rollout:Y.rollout,targeted:Y.when!==void 0,serverOnly:Y.serverOnly,salt:Y.salt,active:$.get(W),...Z.get(W)}))}}async refresh(){if(!this.config.enabled)return;if(Object.keys(this.declared).length===0)return;await this.store.refresh()}async invalidate(){try{if(this.config.enabled&&Object.keys(this.declared).length>0)await this.store.invalidate()}finally{T.getStore()?.featureEvaluations?.clear()}}async set($,Z,J={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new gj(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let W=XV(J.actor),Y=this.config.source;if(typeof Y.write!=="function")throw new e8(Y.constructor?.name||"an anonymous source");let{actorRecorded:j}=await Y.write($,Z,{actor:W});if(W!==null&&!j&&!this.warnedAboutActor)this.warnedAboutActor=!0,this.log('Features.set() was given an actor, but the feature source has nowhere to record it. For the database source, add a nullable `updatedBy String?` column to the feature flag model to keep "last changed by".');await this.invalidate()}async enabled($){return(await this.explain($)).value}async explain($){let Z=await this.requestContext();return await this.evaluateIn($,Z,this.requestBuckets())}async all(){let $=await this.requestContext();return await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!1})}async forClient(){if(!this.config.enabled)return{};let $=await this.requestContext(),Z=await this.evaluateAllIn($,this.requestBuckets(),{clientOnly:!0});return this.warnIfOversized(Object.keys(Z).length),Z}for($){return new mj(this,kj($))}async evaluateIn($,Z,J){let W=this.memoFor(Z),Y=W?.get($);if(Y)return Y;let j=this.declared[$];if(!j)return{value:!1,reason:"undeclared"};let{active:z,unavailable:X}=await this.switchFor($),Q=yj($,j,Z,{active:z,unavailable:X,buckets:J,warn:this.log});return W?.set($,Q),this.notify($,Q,Z),Q}async evaluateAllIn($,Z,J){let W={};for(let[Y,j]of Object.entries(this.declared)){if(J.clientOnly&&j.serverOnly)continue;W[Y]=(await this.evaluateIn(Y,$,Z)).value}return W}async switches(){if(!this.config.enabled||Object.keys(this.declared).length===0)return{active:new Map,audit:new Map,unavailable:!1};let $=await this.store.get();return{active:$.active,audit:$.audit,unavailable:$.unavailable}}async switchFor($){if(!this.config.enabled)return{active:!1,unavailable:!1};let Z=await this.store.get();return{active:Z.active.get($),unavailable:Z.unavailable}}async requestContext(){let $=T.getStore();if($?.featureContext)return $.featureContext;let Z=await fj(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=T.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=T.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,J){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,J)}catch(W){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${W instanceof Error?W.message:String(W)}`)}}warnIfOversized($){if(this.warnedAboutSize||$<=this.config.maxClientFlags)return;this.warnedAboutSize=!0,this.log(`${$} client-visible features are embedded in every document. Mark the ones only the server reads with \`serverOnly: true\` to keep them out of the payload.`)}}function XV($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:J}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof J==="string"&&J.length>0||typeof J==="number")return String(J)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}async function hj($){if($===void 0)return!0;return await M(Y$).enabled($)}async function MZ($,Z){if(typeof Z!=="string"||!Object.hasOwn($,Z))return null;let J=xj($[Z]);if(!J||!await hj(J.feature))return null;return J.provider}async function pj($){let Z=[];for(let J of Object.keys($))if(await MZ($,J))Z.push(J);return Z}function $7($){if($&&typeof $==="object")delete $.password;return $}function QV(){return new Proxy({},{get:($,Z)=>dj(Z)})}var cj=new WeakMap;function uj($){if($&&typeof $==="object"){for(let Z of Object.values($))uj(Z);Object.freeze($)}return $}var GV={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},KV=uj({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:GV});class Z7{models;constructor($=QV()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return KV}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let J=this.models.User.$connection??R1(),W=M(f1).connection(J),Y=()=>this.transaction(async()=>{if(W.dialect==="postgres"){let X=`gemi:legacy-session:${$}`;await l0()`SELECT pg_advisory_xact_lock(hashtextextended(${X}, 0))`}return Z()});if(W.dialect!=="sqlite"||l0())return Y();let z=(cj.get(W)??Promise.resolve()).then(Y,Y);return cj.set(W,z.catch(()=>{})),z}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return $7(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return $7(Z)}async findUserByEmailAddress($,Z){return await this.run(()=>this.models.User.findUnique({where:Z?{email:$,emailVerifiedAt:{not:null}}:{email:$}}))}async findUserByVerificationToken($){if(typeof $!=="string"||$==="")return null;return await this.run(()=>this.models.User.findFirst({where:{verificationToken:$}}))}async verifyUser($){return await this.run(()=>this.models.User.update({where:{email:$},data:{emailVerifiedAt:new Date}}))}async createSession($){return await this.run(()=>this.models.Session.create({data:$,include:{user:!0}}))}async createSessionV2($){return await this.run(()=>this.models.Session.create({data:$,select:this.sessionSelect()}))}async findSession($){if(!$.token)return null;try{return await this.run(()=>this.models.Session.findUnique({where:{token:$.token},select:this.sessionSelect()}))}catch(Z){return console.error("findSession failed:",Z),null}}async updateSession($){return await this.run(()=>this.models.Session.update({where:{token:$.token},data:{expiresAt:$.expiresAt},select:this.sessionSelect()}))}async deleteSession($){if(!$.token)return;await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}))}async claimLegacySession($){if(!$.token)return!1;let{count:Z}=await this.run(()=>this.models.Session.deleteMany({where:{token:$.token}}));return Z>0}async deleteAllUserSessions($){await this.run(()=>this.models.Session.deleteMany({where:{userId:$}}))}async createPasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.create({data:{token:$.token,user:{connect:{id:$.user.id}}}}))}async findPasswordResetToken($){if(typeof $.token!=="string"||$.token==="")return null;return await this.run(()=>this.models.PasswordResetToken.findUnique({where:{token:$.token},include:{user:!0}}))}async deletePasswordResetToken($){return await this.run(()=>this.models.PasswordResetToken.delete({where:{token:$.token}}))}async findInvitation($,Z){if(typeof $!=="string"||typeof Z!=="string")return null;return await this.run(()=>this.models.OrganizationInvitation.findFirst({where:{publicId:$,email:Z}}))}async deleteInvitationById($){await this.run(()=>this.models.OrganizationInvitation.delete({where:{publicId:$}}))}async createAccount($){return await this.run(()=>this.models.Account.create({data:{userId:$.userId,organizationId:$.organizationId,organizationRole:$.organizationRole}}))}async createMagicLinkToken($){return await this.run(()=>this.models.MagicLinkToken.create({data:{email:$.email,token:$.token,pin:$.pin}}))}async findUserMagicLinkToken($){let Z=(J)=>typeof J==="string"&&J!=="";if(!Z($.email))return null;if($.token!==void 0&&!Z($.token))return null;if($.token===void 0&&!Z($.pin))return null;return await this.run(()=>$.token?this.models.MagicLinkToken.findUnique({where:{token_email:{token:$.token,email:$.email}}}):this.models.MagicLinkToken.findUnique({where:{pin_email:{pin:$.pin,email:$.email}}}))}async findMagicLinkTokenByEmail($){return await this.run(()=>this.models.MagicLinkToken.findFirst({where:{email:$},orderBy:{id:"desc"}}))}async listMagicLinkTokensByEmail($,Z){return await this.run(()=>this.models.MagicLinkToken.findMany({where:{email:$},orderBy:{id:"desc"},take:Z}))}async deleteMagicLinkTokensExcept($,Z){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$,id:{notIn:Z}}}))}async claimMagicLinkToken($){let{count:Z}=await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{id:$}}));return Z===1}async deleteMagicLinkToken($){await this.run(()=>this.models.MagicLinkToken.deleteMany({where:{email:$}}))}async createSocialAccount($){return await this.run(()=>this.models.SocialAccount.create({data:$}))}async findUserBySocialAccount($,Z){if(!Z)return null;let J=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return J?$7(J.user):null}async findSocialAccounts($,Z){return await this.run(()=>this.models.SocialAccount.findMany({where:{userId:$,provider:Z},orderBy:{id:"asc"}}))}async claimSocialAccount($,Z){let{count:J}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return J===1}}import{randomBytes as UD}from"crypto";function y0($,Z,J,W,Y){return t0(Z,z2($,Z),J,W,Y)}function t0($,Z,J,W,Y,j){let z=z7(Z,J,W);if(Y&&Z!==z)throw RangeError(dz($,Z,J,W,j));return z}function z2($,Z){let J=$[Z];if(J===void 0)throw TypeError(qJ(Z));return J}function L0($){return $!==null&&/object|function/.test(typeof $)}function m0($,Z=Map){let J=new Z;return(W,...Y)=>{if(J.has(W))return J.get(W);let j=$(W,...Y);return J.set(W,j),j}}function U7($){return v$({name:$},1)}function v$($,Z){return J1((J)=>({value:J,configurable:1,writable:!Z}),$)}function X2($){return J1((Z)=>({get:Z,configurable:1}),$)}function v6($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function xZ($,Z){let J={},W=$.length;for(let Y of Z)J[$[--W]]=Y;return J}function J1($,Z,J){let W={};for(let Y in Z)W[Y]=$(Z[Y],Y,J);return W}function P3($,Z,J){let W={};for(let Y=0;Y<Z.length;Y++){let j=Z[Y];W[j]=$(j,Y,J)}return W}function BV($,Z,J){let W={};for(let Y=0;Y<$.length;Y++)W[Z[Y]]=J[$[Y]];return W}function p0($,Z){let J={};for(let W of $)J[W]=Z[W];return J}function D7($,Z){let J={};for(let W in Z)$.has(W)||(J[W]=Z[W]);return J}function O7($){$={...$};let Z=Object.keys($);for(let J of Z)$[J]===void 0&&delete $[J];return $}function Q2($,Z){for(let J of Z)if(!(J in $))return 0;return 1}function G2($,Z,J){for(let W of $)if(Z[W]!==J[W])return 0;return 1}function K2($,Z,J){let W={...J};for(let Y=0;Y<Z;Y++)W[$[Y]]=0;return W}function w($,...Z){return(...J)=>$(...Z,...J)}function lj($){return $[0].toUpperCase()+$.substring(1)}function T3($){return $.slice().sort()}function S6($,Z){return String(Z).padStart($,"0")}function j$($,Z){return Math.sign($-Z)}function z7($,Z,J){return Math.min(Math.max($,Z),J)}function w1($,Z){return[Math.floor($/Z),F3($,Z)]}function F3($,Z){return($%Z+Z)%Z}function Q$($,Z){return[g6($,Z),L7($,Z)]}function g6($,Z){return Math.trunc($/Z)||0}function L7($,Z){return $%Z||0}function N6($){return Math.abs($%1)===0.5}function B2($,Z,J){let W=0,Y=0;for(let X=0;X<=Z;X++){let Q=$[J[X]],G=D1[X],B=l/G,[V,K]=Q$(Q,B);W+=K*G,Y+=V}let[j,z]=Q$(W,l);return[Y+j,z]}function m6($,Z,J){let W={};for(let Y=Z;Y>=0;Y--){let j=D1[Y];W[J[Y]]=g6($,j),$=L7($,j)}return W}function V2($){return $===q?H4:[]}function F2($){return $===q?R3:[]}function U2($){return $===q?["year","day"]:[]}function D2($){if($!==void 0)return J0($)}function O2($){if($!==void 0)return W1($)}function M7($){if($!==void 0)return N3($)}function W1($){return H2(N3($))}function N3($){return M2(JF($))}function H7($){if($==null)throw TypeError("Cannot be null or undefined");return $}function L2($,Z){if(Z==null)throw RangeError(qJ($));return Z}function y1($){if(!L0($))throw TypeError(cz);return $}function h6($,Z,J=$){if(typeof Z!==$)throw TypeError(S3(J,Z));return Z}function M2($,Z="number"){if(!Number.isInteger($))throw RangeError(AV(Z,$));return $||0}function H2($,Z="number"){if($<=0)throw RangeError(SV(Z,$));return $}function P7($){if(typeof $=="symbol")throw TypeError(fV);return String($)}function E6($,Z){return L0($)?String($):J0($,Z)}function p6($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(RV($));return $}function P2($,Z="number"){if(typeof $=="bigint")throw TypeError(bV(Z));if($=Number($),!Number.isFinite($))throw RangeError(EV(Z,$));return $}function A0($,Z){return Math.trunc(P2($,Z))||0}function T2($,Z){return M2(P2($,Z),Z)}function ij($,Z){return H2(A0($,Z),Z)}function T7($,Z){let[J,W]=Q$(Z,l),Y=$+J,j=Math.sign(Y);return j&&j===-Math.sign(W)&&(Y-=j,W+=j*l),[Y,W]}function PZ($,Z,J=1){return T7($[0]+Z[0]*J,$[1]+Z[1]*J)}function TZ($,Z){return T7($[0],$[1]+Z)}function i0($,Z){return PZ(Z,$,-1)}function E0($,Z){return j$($[0],Z[0])||j$($[1],Z[1])}function N2($,Z,J){return E0($,Z)===-1||E0($,J)===1}function c6($,Z=1){let J=BigInt(l/Z);return[Number($/J),Number($%J)*Z]}function NZ($,Z=1){let J=l/Z,[W,Y]=Q$($,J);return[W,Y*Z]}function _2($,Z=1){let[J,W]=$,Y=Math.floor(W/Z),j=l/Z;return BigInt(J)*BigInt(j)+BigInt(Y)}function s0($,Z=1,J){let[W,Y]=$,[j,z]=Q$(Y,Z);return W*(l/Z)+(j+(J?z/Z:0))}function N7($,Z,J=w1){let[W,Y]=$,[j,z]=J(Y,Z);return[W*(l/Z)+j,z]}function _7($,Z){let J=$.formatToParts(Z),W={};for(let Y of J)W[Y.type]=Y.value;return W}function I7($){return y0($,"isoYear",H3,M3,1),$.isoYear===H3?y0($,"isoMonth",4,12,1):$.isoYear===M3&&y0($,"isoMonth",1,9,1),$}function z$($){return v1({...$,...Z1,isoHour:12}),$}function v1($){let Z=y0($,"isoYear",H3,M3,1),J=Z===H3?1:Z===M3?-1:0;return J&&n0(S0({...$,isoDay:$.isoDay+J,isoNanosecond:$.isoNanosecond-J})),$}function n0($){if(!$||N2($,GF,QF))throw RangeError(D4);return $}function G$($){return B2($,5,X1)[1]}function d6($){let[Z,J]=w1($,l);return[m6(J,5,X1),Z]}function I2($){return x2($)[0]}function x2($){return N7($,$1)}function b0($){return CZ($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function S0($){let Z=b0($);if(Z!==void 0){let[J,W]=Q$(Z,g0);return[J,W*O1+($.isoMicrosecond||0)*i$+($.isoNanosecond||0)]}}function x7($,Z){let[J,W]=d6(G$($)-Z);return n0(S0({...$,isoDay:$.isoDay+W,...J}))}function b6(...$){return CZ(...$)/$X}function CZ(...$){let[Z,J]=C2(...$),W=Z.valueOf();if(!isNaN(W))return W-J*g0}function C2($,Z=1,J=1,W=0,Y=0,j=0,z=0){let X=$===H3?1:$===M3?-1:0,Q=new Date;return Q.setUTCHours(W,Y,j,z),Q.setUTCFullYear($,Z-1,J+X),[Q,X]}function B$($,Z){let[J,W]=TZ($,Z);W<0&&(W+=l,J-=1);let[Y,j]=w1(W,O1),[z,X]=w1(j,i$);return u6(J*g0+Y,z,X)}function u6($,Z=0,J=0){let W=Math.ceil(Math.max(0,Math.abs($)-XF)/g0)*Math.sign($),Y=new Date($-W*g0);return xZ(T4,[Y.getUTCFullYear(),Y.getUTCMonth()+1,Y.getUTCDate()+W,Y.getUTCHours(),Y.getUTCMinutes(),Y.getUTCSeconds(),Y.getUTCMilliseconds(),Z,J])}function A2($){return[$.isoYear,$.isoMonth,$.isoDay]}function S2(){return k1}function C7($,Z){switch(Z){case 2:return A7($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function E2($){return A7($)?366:365}function A7($){return $%4==0&&($%100!=0||$%400==0)}function b2($){let[Z,J]=C2($.isoYear,$.isoMonth,$.isoDay);return F3(Z.getUTCDay()-J,7)||7}function R2({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function VV($){let Z=b0($);if(Z<BF)return R2($);let J=_7(eJ(_Z),Z),{era:W,eraYear:Y}=c9(J,_Z);return[W,Y]}function l6($){return g$($),i6($,1),$}function g$($){return f2($,1),$}function sj($){return G2(lJ,$,f2($))}function f2($,Z){let{isoYear:J}=$,W=y0($,"isoMonth",1,S2(),Z);return{isoYear:J,isoMonth:W,isoDay:y0($,"isoDay",1,C7(J,W),Z)}}function i6($,Z){return xZ(X1,[y0($,"isoHour",0,23,Z),y0($,"isoMinute",0,59,Z),y0($,"isoSecond",0,59,Z),y0($,"isoMillisecond",0,999,Z),y0($,"isoMicrosecond",0,999,Z),y0($,"isoNanosecond",0,999,Z)])}function g($){return $===void 0?0:LX(y1($))}function _3($,Z=0){$=Y1($);let J=MX($),W=TF($,Z);return[LX($),W,J]}function S7($){return MX(Y1($))}function k2($){return $=Y1($),nJ($,9,6,1)}function AZ($,Z,J,W=9,Y=0,j=4){Z=Y1(Z);let z=nJ(Z,W,Y),X=R7(Z),Q=k3(Z,j),G=f3(Z,W,Y,1);return z==null?z=Math.max(J,G):v2(z,G),X=f7(X,G,1),$&&(Q=((B)=>B<4?(B+2)%4:B)(Q)),[z,G,X,Q]}function s6($,Z=6,J){let W=R7($=k7($,y6)),Y=k3($,7),j=f3($,Z);return j=L2(y6,j),W=f7(W,j,void 0,J),[j,W,Y]}function E7($){return oJ(Y1($))}function w2($,Z){return b7(Y1($),Z)}function b7($,Z=4){let J=y2($);return[k3($,4),...q2(f3($,Z),J)]}function q2($,Z){return $!=null?[D1[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function R7($){let Z=$[U3];return Z===void 0?1:A0(Z,U3)}function f7($,Z,J,W){let Y=W?l:D1[Z+1];if(Y){let j=D1[Z];if(Y%(($=t0(U3,$,1,Y/j-(W?0:1),1))*j))throw RangeError(S3(U3,$))}else $=t0(U3,$,1,J?1e9:1,1);return $}function y2($){let Z=$[j7];if(Z!==void 0){if(typeof Z!="number"){if(P7(Z)==="auto")return;throw RangeError(S3(j7,Z))}Z=t0(j7,Math.floor(Z),0,9,1)}return Z}function Y1($){return $===void 0?{}:y1($)}function k7($,Z){return typeof $=="string"?{[Z]:$}:y1($)}function Q0($){if($!==void 0){if(L0($))return Object.assign(Object.create(null),$);throw TypeError(cz)}}function n6($,Z){return $&&Object.assign(Object.create(null),$,{overflow:FF[Z]})}function w7($,Z,J=9,W=0,Y){let j=Z[$];if(j===void 0)return Y?W:void 0;if(j=P7(j),j==="auto")return Y?W:null;let z=K7[j];if(z===void 0&&(z=jF[j]),z===void 0)throw RangeError(iz($,j,K7));return t0($,z,W,J,1,b3),z}function m$($,Z,J,W=0){let Y=J[$];if(Y===void 0)return W;let j=P7(Y),z=Z[j];if(z===void 0)throw RangeError(iz($,j,Z));return z}function v2($,Z){if(Z>$)throw RangeError(rV)}function M0($){return{branding:_4,epochNanoseconds:$}}function N0($,Z,J){return{branding:p1,calendar:J,timeZone:Z,epochNanoseconds:$}}function G0($,Z=$.calendar){return{branding:n$,calendar:Z,...p0(FX,$)}}function K0($,Z=$.calendar){return{branding:s$,calendar:Z,...p0(iJ,$)}}function q$($,Z=$.calendar){return{branding:qZ,calendar:Z,...p0(iJ,$)}}function R6($,Z=$.calendar){return{branding:yZ,calendar:Z,...p0(iJ,$)}}function j1($){return{branding:N4,...p0(VX,$)}}function e($){return{branding:I4,sign:V$($),...p0(cJ,$)}}function g2($){return I2($.epochNanoseconds)}function o6($){return N7($.epochNanoseconds,O1)[0]}function m2($){return _2($.epochNanoseconds,i$)}function h2($){return _2($.epochNanoseconds)}function p2($){return $.epochNanoseconds}function P0($){return typeof $=="string"?$:J0($.id)}function SZ($,Z){return $===Z||P0($)===P0(Z)}function c2($,Z,J,W,Y){let j=y$(W),[z,X]=((O,L)=>{let P=L((O=k7(O,F7))[DX]),H=PF(O);return H=L2(F7,H),[H,P]})(Y,$);if(O3(Math.max(z,j),X))return nj(W,z);if(!X)throw RangeError(O4);let[Q,G,B]=Z4(Z,J,X),V=YJ(B),K=J4(B),F=jJ(B),D=K(G,Q,W),U=F(G,Q,D,z);return O3(z,X)?nj(U,z):((O,L,P,H,I,E,S)=>{let R=V$(O),[k,N]=q7(H,uJ(P,O),P,R,I,E,S),v=y7(L,k,N);return O[h[P]]+v*R})(U,V(D),z,G,Q,V,K)}function nj($,Z){return s0(O0($),D1[Z],1)}function q7($,Z,J,W,Y,j,z){let X=h[J],Q={...Z,[X]:Z[X]+W},G=z($,Y,Z),B=z($,Y,Q);return[j(G),j(B)]}function y7($,Z,J){let W=s0(i0(Z,J));if(!W)throw RangeError(E3);return s0(i0(Z,$))/W}function d2($,Z){let[J,W,Y]=s6(Z,5,1);return M0(r6($.epochNanoseconds,J,W,Y,1))}function u2($,Z,J){let{epochNanoseconds:W,timeZone:Y,calendar:j}=Z,[z,X,Q]=s6(J);if(z===0&&X===1)return Z;let G=$(Y);if(z===6)W=((B,V,K,F)=>{let D=R0(K,V),[U,O]=B(D),L=K.epochNanoseconds,P=h0(V,U),H=h0(V,O);if(N2(L,P,H))throw RangeError(E3);return e2(y7(L,P,H),F)?H:P})(r2,G,Z,Q);else{let B=G.getOffsetNanosecondsFor(W);W=p$(G,o2(B$(W,B),z,X,Q),B,2,0,1)}return N0(W,Y,j)}function l2($,Z){return G0(o2($,...s6(Z)),$.calendar)}function i2($,Z){let[J,W,Y]=s6(Z,5);var j;return j1((j=Y,v7($,I3(J,W),j)[0]))}function s2($,Z){let J=$(Z.timeZone),W=R0(Z,J),[Y,j]=r2(W),z=s0(i0(h0(J,Y),h0(J,j)),M4,1);if(z<=0)throw RangeError(E3);return z}function n2($,Z){let{timeZone:J,calendar:W}=Z,Y=((j,z,X)=>h0(z,j(R0(X,z))))(t2,$(J),Z);return N0(Y,J,W)}function o2($,Z,J,W){return a2($,I3(Z,J),W)}function a2($,Z,J){let[W,Y]=v7($,Z,J);return v1({...c$($,Y),...W})}function v7($,Z,J){return d6(K$(G$($),Z,J))}function f6($){return K$($,L4,7)}function I3($,Z){return D1[$]*Z}function r2($){let Z=t2($);return[Z,c$(Z,1)]}function t2($){return zF(6,$)}function FV($,Z,J){let W=Math.min(y$($),6);return bZ(t6(O0($,W),Z,J),W)}function a6($,Z,J,W,Y,j,z,X,Q,G){if(W===0&&Y===1)return $;let B=O3(W,X)?W4(X)&&W<6&&J>=6?DV:UV:OV,[V,K,F]=B($,Z,J,W,Y,j,z,X,Q,G);return F&&W!==7&&(V=((D,U,O,L,P,H,I,E)=>{let S=V$(D);for(let R=L+1;R<=O;R++){if(R===7&&O!==7)continue;let k=uJ(R,D);k[h[R]]+=S;let N=s0(i0(I(E(P,H,k)),U));if(N&&Math.sign(N)!==S)break;D=k}return D})(V,K,J,Math.max(6,W),z,X,Q,G)),V}function r6($,Z,J,W,Y){if(Z===6){let j=((z)=>z[0]+z[1]/l)($);return[K$(j,J,W),0]}return t6($,I3(Z,J),W,Y)}function t6($,Z,J,W){let[Y,j]=$;W&&j<0&&(j+=l,Y-=1);let[z,X]=w1(K$(j,Z,J),l);return T7(Y+z,X)}function K$($,Z,J){return e2($/Z,J)*Z}function e2($,Z){return IF[Z]($)}function UV($,Z,J,W,Y,j){let z=V$($),X=O0($),Q=r6(X,W,Y,j),G=i0(X,Q),B=Math.sign(Q[0]-X[0])===z,V=bZ(Q,Math.min(J,6));return[{...$,...V},PZ(Z,G),B]}function DV($,Z,J,W,Y,j,z,X,Q,G){let B=V$($),V=s0(O0($,5)),K=I3(W,Y),F=K$(V,K,j),[D,U]=q7(z,{...$,...dJ},6,B,X,Q,G),O=F-s0(i0(D,U)),L=0;O&&Math.sign(O)!==B?Z=TZ(D,F):(L+=B,F=K$(O,K,j),Z=TZ(U,F));let P=j4(F);return[{...$,...P,days:$.days+L},Z,Boolean(L)]}function OV($,Z,J,W,Y,j,z,X,Q,G){let B=V$($),V=h[W],K=uJ(W,$);W===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let F=g6($[V],Y)*Y;K[V]=F;let[D,U]=q7(z,K,W,Y*B,X,Q,G),O=F+y7(Z,D,U)*B*Y,L=K$(O,Y,j),P=Math.sign(L-O)===B;return K[V]=L,[K,P?U:D,P]}function g7($,Z,J,W){let[Y,j,z,X]=((G)=>{let B=b7(G=Y1(G));return[G.timeZone,...B]})(W),Q=Y!==void 0;return((G,B,V,K,F,D)=>{V=t6(V,F,K,1);let U=B.getOffsetNanosecondsFor(V);return l7(B$(V,U),D)+(G?h$(f6(U)):"Z")})(Q,Z(Q?$(Y):o$),J.epochNanoseconds,j,z,X)}function m7($,Z,J){let[W,Y,j,z,X,Q]=((G)=>{G=Y1(G);let B=oJ(G),V=y2(G),K=_F(G),F=k3(G,4),D=f3(G,4);return[B,NF(G),K,F,...q2(D,V)]})(J);return((G,B,V,K,F,D,U,O,L,P)=>{K=t6(K,L,O,1);let H=G(V).getOffsetNanosecondsFor(K);return l7(B$(K,H),P)+h$(f6(H),U)+((I,E)=>E!==1?"["+(E===2?"!":"")+P0(I)+"]":"")(V,D)+i7(B,F)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,W,Y,j,z,X,Q)}function h7($,Z){let[J,W,Y,j]=((G)=>(G=Y1(G),[oJ(G),...b7(G)]))(Z);return z=$.calendar,X=J,Q=j,l7(a2($,Y,W),Q)+i7(z,X);var z,X,Q}function p7($,Z){return J=$.calendar,W=$,Y=E7(Z),k6(W)+i7(J,Y);var J,W,Y}function c7($,Z){return $9($.calendar,Z9,$,E7(Z))}function d7($,Z){return $9($.calendar,LV,$,E7(Z))}function u7($,Z){let[J,W,Y]=w2(Z);return j=Y,J9(v7($,W,J)[0],j);var j}function e6($,Z){let[J,W,Y]=w2(Z,3);return W>1&&($={...$,...FV($,W,J)}),((j,z)=>{let{sign:X}=j,Q=X===-1?f0(j):j,{hours:G,minutes:B}=Q,[V,K]=N7(O0(Q,3),$1,Q$);K9(V);let F=s7(K,z),D=z>=0||!X||F;return(X<0?"-":"")+"P"+oj({Y:w$(Q.years),M:w$(Q.months),W:w$(Q.weeks),D:w$(Q.days)})+(G||B||V||D?"T"+oj({H:w$(G),M:w$(B),S:w$(V,D)+F}):"")})($,Y)}function $9($,Z,J,W){let Y=P0($),j=W>1||W===0&&Y!==q;return W===1?Y===q?Z(J):k6(J):j?k6(J)+W9(Y,W===2):Z(J)}function oj($){let Z=[];for(let J in $){let W=$[J];W&&Z.push(W,J)}return Z.join("")}function l7($,Z){return k6($)+"T"+J9($,Z)}function k6($){return Z9($)+"-"+e0($.isoDay)}function Z9($){let{isoYear:Z}=$;return(Z<0||Z>9999?Y9(Z)+S6(6,Math.abs(Z)):S6(4,Z))+"-"+e0($.isoMonth)}function LV($){return e0($.isoMonth)+"-"+e0($.isoDay)}function J9($,Z){let J=[e0($.isoHour),e0($.isoMinute)];return Z!==-1&&J.push(e0($.isoSecond)+((W,Y,j,z)=>s7(W*O1+Y*i$+j,z))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),J.join(":")}function h$($,Z=0){if(Z===1)return"";let[J,W]=w1(Math.abs($),M4),[Y,j]=w1(W,L4),[z,X]=w1(j,$1);return Y9($)+e0(J)+":"+e0(Y)+(z||X?":"+e0(z)+s7(X):"")}function i7($,Z){if(Z!==1){let J=P0($);if(Z>1||Z===0&&J!==q)return W9(J,Z===2)}return""}function W9($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function s7($,Z){let J=S6(9,$);return J=Z===void 0?J.replace(AF,""):J.slice(0,Z),J?"."+J:""}function Y9($){return $<0?"-":"+"}function w$($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function MV($,Z){let{epochNanoseconds:J}=$,W=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(J),Y=B$(J,W);return{calendar:$.calendar,...Y,offsetNanoseconds:W}}function j9($,Z){let J=R0(Z,$);return{calendar:Z.calendar,...p0(FX,J),offset:h$(J.offsetNanoseconds),timeZone:Z.timeZone}}function p$($,Z,J,W=0,Y=0,j,z){if(J!==void 0&&W===1&&(W===1||z))return x7(Z,J);let X=$.getPossibleInstantsFor(Z);if(J!==void 0&&W!==3){let Q=((G,B,V,K)=>{let F=S0(B);K&&(V=f6(V));for(let D of G){let U=s0(i0(D,F));if(K&&(U=f6(U)),U===V)return D}})(X,Z,J,j);if(Q!==void 0)return Q;if(W===0)throw RangeError(lV)}return z?S0(Z):h0($,Z,Y,X)}function h0($,Z,J=0,W=$.getPossibleInstantsFor(Z)){if(W.length===1)return W[0];if(J===1)throw RangeError(iV);if(W.length)return W[J===3?1:0];let Y=S0(Z),j=((X,Q)=>{let G=X.getOffsetNanosecondsFor(TZ(Q,-l));return o7(X.getOffsetNanosecondsFor(TZ(Q,l))-G)})($,Y),z=j*(J===2?-1:1);return(W=$.getPossibleInstantsFor(B$(Y,z)))[J===2?0:W.length-1]}function n7($){if(Math.abs($)>=l)throw RangeError(dV);return $}function o7($){if($>l)throw RangeError(uV);return $}function a7($,Z,J){return M0(n0(PZ(Z.epochNanoseconds,((W)=>{if(B9(W))throw RangeError(oV);return O0(W,5)})($?f0(J):J))))}function r7($,Z,J,W,Y,j=Object.create(null)){let z=Z(W.timeZone),X=$(W.calendar);return{...W,...JJ(z,X,W,J?f0(Y):Y,j)}}function t7($,Z,J,W,Y=Object.create(null)){let{calendar:j}=J;return G0(WJ($(j),J,Z?f0(W):W,Y),j)}function e7($,Z,J,W,Y){let{calendar:j}=J;return K0($4($(j),J,Z?f0(W):W,Y),j)}function $J($,Z,J,W,Y=Object.create(null)){let j=J.calendar,z=$(j),X=D3(z,J);Z&&(W=Y4(W)),W.sign<0&&(X=z.dateAdd(X,{...T0,months:1}),X=c$(X,-1));let Q=z.dateAdd(X,W,Y);return q$(D3(z,Q),j)}function ZJ($,Z,J){return j1(z9(Z,$?f0(J):J)[0])}function JJ($,Z,J,W,Y){let j=O0(W,5),z=J.epochNanoseconds;if(B9(W)){let X=R0(J,$);z=PZ(h0($,{...$4(Z,X,{...W,...dJ},Y),...p0(X1,X)}),j)}else z=PZ(z,j),g(Y);return{epochNanoseconds:n0(z)}}function WJ($,Z,J,W){let[Y,j]=z9(Z,J);return v1({...$4($,Z,{...J,...dJ,days:J.days+j},W),...Y})}function $4($,Z,J,W){if(J.years||J.months||J.weeks)return $.dateAdd(Z,J,W);g(W);let Y=J.days+O0(J,5)[0];return Y?z$(c$(Z,Y)):Z}function D3($,Z,J=1){return c$(Z,J-$.day(Z))}function z9($,Z){let[J,W]=O0(Z,5),[Y,j]=d6(G$($)+W);return[Y,J+j]}function c$($,Z){return Z?{...$,...u6(b0($)+Z*g0)}:$}function Z4($,Z,J){let W=$(J.calendar);return W4(J)?[J,W,Z(J.timeZone)]:[{...J,...Z1},W]}function YJ($){return $?p2:S0}function J4($){return $?w(JJ,$):WJ}function jJ($){return $?w(PV,$):TV}function W4($){return $&&$.epochNanoseconds}function O3($,Z){return $<=6-(W4(Z)?1:0)}function zJ($,Z,J,W,Y,j,z){let X=$(Y1(z).relativeTo),Q=Math.max(y$(Y),y$(j));if(O3(Q,X))return e(EZ(((U,O,L,P)=>{let H=PZ(O0(U),O0(O),P?-1:1);if(!Number.isFinite(H[0]))throw RangeError(D4);return{...T0,...bZ(H,L)}})(Y,j,Q,W)));if(!X)throw RangeError(O4);W&&(j=f0(j));let[G,B,V]=Z4(Z,J,X),K=J4(V),F=jJ(V),D=K(B,G,Y);return e(F(B,G,K(B,D,j),Q))}function X9($,Z,J,W,Y){let j=y$(W),[z,X,Q,G,B]=((S,R,k)=>{S=k7(S,y6);let N=nJ(S),v=k(S[DX]),_=R7(S),f=k3(S,7),H0=f3(S);if(N===void 0&&H0===void 0)throw RangeError(aV);return H0==null&&(H0=0),N==null&&(N=Math.max(H0,R)),v2(N,H0),_=f7(_,H0,1),[N,H0,_,f,v]})(Y,j,$),V=Math.max(j,z);if(!W4(B)&&V<=6)return e(EZ(((S,R,k,N,v)=>{let _=r6(O0(S),k,N,v);return{...T0,...bZ(_,R)}})(W,z,X,Q,G)));if(!B)throw RangeError(O4);let[K,F,D]=Z4(Z,J,B),U=YJ(D),O=J4(D),L=jJ(D),P=O(F,K,W),H=L(F,K,P,z),I=W.sign,E=V$(H);if(I&&E&&I!==E)throw RangeError(E3);return E&&(H=a6(H,U(P),z,X,Q,G,F,K,U,O)),e(H)}function Q9($){return $.sign===-1?Y4($):$}function Y4($){return e(f0($))}function f0($){let Z={};for(let J of h)Z[J]=-1*$[J]||0;return Z}function G9($){return!$.sign}function V$($,Z=h){let J=0;for(let W of Z){let Y=Math.sign($[W]);if(Y){if(J&&J!==Y)throw RangeError(nV);J=Y}}return J}function EZ($){for(let Z of YF)t0(Z,$[Z],-J2,J2,1);return K9(s0(O0($),$1)),$}function K9($){if(!Number.isSafeInteger($))throw RangeError(sV)}function O0($,Z=6){return B2($,Z,h)}function bZ($,Z=6){let[J,W]=$,Y=m6(W,Z,h);if(Y[h[Z]]+=J*(l/D1[Z]),!Number.isFinite(Y[h[Z]]))throw RangeError(D4);return Y}function j4($,Z=5){return m6($,Z,h)}function B9($){return Boolean(V$($,BX))}function y$($){let Z=9;for(;Z>0&&!$[h[Z]];Z--);return Z}function HV($,Z){return[$,Z]}function aj($){let Z=Math.floor($/C6)*C6;return[Z,Z+C6]}function V9($){let Z=F$($=E6($));if(!Z)throw RangeError(v0($));let J;if(Z.m)J=0;else{if(!Z.offset)throw RangeError(v0($));J=RZ(Z.offset)}return Z.timeZone&&KJ(Z.timeZone,1),M0(x7(l6(Z),J))}function F9($){let Z=F$(J0($));if(!Z)throw RangeError(v0($));if(Z.timeZone)return N9(Z,Z.offset?RZ(Z.offset):void 0);if(Z.m)throw RangeError(v0($));return I9(Z)}function U9($,Z){let J=F$(J0($));if(!J||!J.timeZone)throw RangeError(v0($));let{offset:W}=J,Y=W?RZ(W):void 0,[,j,z]=_3(Z);return N9(J,Y,j,z)}function RZ($){let Z=KJ($);if(Z===void 0)throw RangeError(v0($));return Z}function D9($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(v0($));return G0(_9(Z))}function z4($){let Z=F$(J0($));if(!Z||Z.m)throw RangeError(v0($));return K0(Z.p?_9(Z):I9(Z))}function O9($,Z){let J=QJ(J0(Z));if(J)return XJ(J),q$(I7(g$(J)));let W=z4(Z);return q$(D3($(W.calendar),W))}function XJ($){if($.calendar!==q)throw RangeError(q1($.calendar))}function L9($,Z){let J=GJ(J0(Z));if(J)return XJ(J),R6(g$(J));let W=z4(Z),{calendar:Y}=W,j=$(Y),[z,X,Q]=j.h(W),[G,B]=j.I(z,X),[V,K]=j.N(G,B,Q);return R6(z$(j.P(V,K,Q)),Y)}function M9($){let Z,J=((W)=>{let Y=fF.exec(W);return Y?(X4(Y[10]),A9(Y)):void 0})(J0($));if(!J){if(J=F$($),!J)throw RangeError(v0($));if(!J.p)throw RangeError(v0($));if(J.m)throw RangeError(q1("Z"));XJ(J)}if((Z=QJ($))&&sj(Z))throw RangeError(v0($));if((Z=GJ($))&&sj(Z))throw RangeError(v0($));return j1(i6(J,1))}function H9($){let Z=((J)=>{let W=qF.exec(J);return W?((Y)=>{function j(B,V,K){let F=0,D=0;if(K&&([F,Q]=w1(Q,D1[K])),B!==void 0){if(X)throw RangeError(q1(B));D=((U)=>{let O=parseInt(U);if(!Number.isFinite(O))throw RangeError(q1(U));return O})(B),z=1,V&&(Q=BJ(V)*(D1[K]/$1),X=1)}return F+D}let z=0,X=0,Q=0,G={...xZ(h,[j(Y[2]),j(Y[3]),j(Y[4]),j(Y[5]),j(Y[6],Y[7],5),j(Y[8],Y[9],4),j(Y[10],Y[11],3)]),...m6(Q,2,h)};if(!z)throw RangeError(uz(h));return VJ(Y[1])<0&&(G=f0(G)),G})(W):void 0})(J0($));if(!Z)throw RangeError(v0($));return e(EZ(Z))}function P9($){let Z=F$($)||QJ($)||GJ($);return Z?Z.calendar:$}function T9($){let Z=F$($);return Z&&(Z.timeZone||Z.m&&o$||Z.offset)||$}function N9($,Z,J=0,W=0){let Y=Q4($.timeZone),j=x4(Y);return N0(p$(j,l6($),Z,J,W,!j.v,$.m),Y,x3($.calendar))}function _9($){return x9(v1(l6($)))}function I9($){return x9(z$(g$($)))}function x9($){return{...$,calendar:x3($.calendar)}}function F$($){let Z=RF.exec($);return Z?((J)=>{let W=J[10],Y=(W||"").toUpperCase()==="Z";return{isoYear:C9(J),isoMonth:parseInt(J[4]),isoDay:parseInt(J[5]),...A9(J.slice(5)),...X4(J[16]),p:Boolean(J[6]),m:Y,offset:Y?void 0:W}})(Z):void 0}function QJ($){let Z=EF.exec($);return Z?((J)=>({isoYear:C9(J),isoMonth:parseInt(J[4]),isoDay:1,...X4(J[5])}))(Z):void 0}function GJ($){let Z=bF.exec($);return Z?((J)=>({isoYear:IZ,isoMonth:parseInt(J[1]),isoDay:parseInt(J[2]),...X4(J[3])}))(Z):void 0}function KJ($,Z){let J=kF.exec($);return J?((W,Y)=>{let j=W[4]||W[5];if(Y&&j)throw RangeError(q1(j));return n7((HZ(W[2])*M4+HZ(W[3])*L4+HZ(W[4])*$1+BJ(W[5]||""))*VJ(W[1]))})(J,Z):void 0}function C9($){let Z=VJ($[1]),J=parseInt($[2]||$[3]);if(Z<0&&!J)throw RangeError(q1(-0));return Z*J}function A9($){let Z=HZ($[3]);return{...d6(BJ($[4]||""))[0],isoHour:HZ($[1]),isoMinute:HZ($[2]),isoSecond:Z===60?59:Z}}function X4($){let Z,J,W=[];if($.replace(wF,(Y,j,z)=>{let X=Boolean(j),[Q,G]=z.split("=").reverse();if(G){if(G==="u-ca")W.push(Q),Z||(Z=X);else if(X||/[A-Z]/.test(G))throw RangeError(q1(Y))}else{if(J)throw RangeError(q1(Y));J=Q}return""}),W.length>1&&Z)throw RangeError(q1($));return{timeZone:J,calendar:W[0]||q}}function BJ($){return parseInt($.padEnd(9,"0"))}function fZ($){return new RegExp(`^${$}$`,"i")}function VJ($){return $&&$!=="+"?-1:1}function HZ($){return $===void 0?0:parseInt($)}function S9($){return Q4(J0($))}function Q4($){let Z=FJ($);return typeof Z=="number"?h$(Z):Z?((J)=>{if(vF.test(J))throw RangeError(cV);return J.toLowerCase().split("/").map((W,Y)=>(W.length<=3||/\d/.test(W))&&!/etc|yap/.test(W)?W.toUpperCase():W.replace(/baja|dumont|[a-z]+/g,(j,z)=>j.length<=2&&!Y||j==="in"||j==="chat"?j.toUpperCase():j.length>2||!z?lj(j).replace(/island|noronha|murdo|rivadavia|urville/,lj):j)).join("/")})($):o$}function rj($){let Z=FJ($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:o$}function FJ($){let Z=KJ($=$.toUpperCase(),1);return Z!==void 0?Z:$!==o$?yF($):void 0}function UJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function DJ($,Z){return E0($.epochNanoseconds,Z.epochNanoseconds)}function E9($,Z,J,W,Y,j){let z=$(Y1(j).relativeTo),X=Math.max(y$(W),y$(Y));if(G2(h,W,Y))return 0;if(O3(X,z))return E0(O0(W),O0(Y));if(!z)throw RangeError(O4);let[Q,G,B]=Z4(Z,J,z),V=YJ(B),K=J4(B);return E0(V(K(G,Q,W)),V(K(G,Q,Y)))}function OJ($,Z){return d$($,Z)||G4($,Z)}function d$($,Z){return j$(b0($),b0(Z))}function G4($,Z){return j$(G$($),G$(Z))}function b9($,Z){return!UJ($,Z)}function R9($,Z){return!DJ($,Z)&&!!K4($.timeZone,Z.timeZone)&&SZ($.calendar,Z.calendar)}function f9($,Z){return!OJ($,Z)&&SZ($.calendar,Z.calendar)}function k9($,Z){return!d$($,Z)&&SZ($.calendar,Z.calendar)}function w9($,Z){return!d$($,Z)&&SZ($.calendar,Z.calendar)}function q9($,Z){return!d$($,Z)&&SZ($.calendar,Z.calendar)}function y9($,Z){return!G4($,Z)}function K4($,Z){if($===Z)return 1;let J=P0($),W=P0(Z);if(J===W)return 1;try{return rj(J)===rj(W)}catch(Y){}}function LJ($,Z,J,W){let Y=AZ($,Q0(W),3,5),j=B4(Z.epochNanoseconds,J.epochNanoseconds,...Y);return e($?f0(j):j)}function MJ($,Z,J,W,Y,j){let z=F4(W.calendar,Y.calendar),X=Q0(j),[Q,G,B,V]=AZ(J,X,5),K=W.epochNanoseconds,F=Y.epochNanoseconds,D=E0(F,K),U;if(D)if(Q<6)U=B4(K,F,Q,G,B,V);else{let O=Z(((P,H)=>{if(!K4(P,H))throw RangeError(az);return P})(W.timeZone,Y.timeZone)),L=$(z);U=g9(L,O,W,Y,D,Q,X),U=a6(U,F,Q,G,B,V,L,W,p2,w(JJ,O))}else U=T0;return e(J?f0(U):U)}function HJ($,Z,J,W,Y){let j=F4(J.calendar,W.calendar),z=Q0(Y),[X,Q,G,B]=AZ(Z,z,6),V=S0(J),K=S0(W),F=E0(K,V),D;if(F)if(X<=6)D=B4(V,K,X,Q,G,B);else{let U=$(j);D=m9(U,J,W,F,X,z),D=a6(D,K,X,Q,G,B,U,J,S0,WJ)}else D=T0;return e(Z?f0(D):D)}function PJ($,Z,J,W,Y){let j=F4(J.calendar,W.calendar),z=Q0(Y);return v9(Z,()=>$(j),J,W,...AZ(Z,z,6,9,6),z)}function TJ($,Z,J,W,Y){let j=F4(J.calendar,W.calendar),z=Q0(Y),X=AZ(Z,z,9,9,8),Q=$(j);return v9(Z,()=>Q,D3(Q,J),D3(Q,W),...X,z)}function v9($,Z,J,W,Y,j,z,X,Q){let G=S0(J),B=S0(W),V;if(E0(B,G))if(Y===6)V=B4(G,B,Y,j,z,X);else{let K=Z();V=K.dateUntil(J,W,Y,Q),j===6&&z===1||(V=a6(V,B,Y,j,z,X,K,J,S0,$4))}else V=T0;return e($?f0(V):V)}function NJ($,Z,J,W){let Y=Q0(W),[j,z,X,Q]=AZ($,Y,5,5),G=K$(_J(Z,J),I3(z,X),Q),B={...T0,...j4(G,j)};return e($?f0(B):B)}function PV($,Z,J,W,Y,j){let z=E0(W.epochNanoseconds,J.epochNanoseconds);return z?Y<6?h9(J.epochNanoseconds,W.epochNanoseconds,Y):g9(Z,$,J,W,z,Y,j):T0}function TV($,Z,J,W,Y){let j=S0(Z),z=S0(J),X=E0(z,j);return X?W<=6?h9(j,z,W):m9($,Z,J,X,W,Y):T0}function g9($,Z,J,W,Y,j,z){let[X,Q,G]=((K,F,D,U)=>{function O(){return R={...c$(H,E++*-U),...P},k=h0(K,R),E0(I,k)===-U}let L=R0(F,K),P=p0(X1,L),H=R0(D,K),I=D.epochNanoseconds,E=0,S=_J(L,H),R,k;if(Math.sign(S)===-U&&E++,O()&&(U===-1||O()))throw RangeError(E3);let N=s0(i0(k,I));return[L,R,N]})(Z,J,W,Y);var B,V;return{...j===6?(B=X,V=Q,{...T0,days:p9(B,V)}):$.dateUntil(X,Q,j,z),...j4(G)}}function m9($,Z,J,W,Y,j){let[z,X,Q]=((G,B,V)=>{let K=B,F=_J(G,B);return Math.sign(F)===-V&&(K=c$(B,-V),F+=l*V),[G,K,F]})(Z,J,W);return{...$.dateUntil(z,X,Y,j),...j4(Q)}}function B4($,Z,J,W,Y,j){return{...T0,...bZ(r6(i0($,Z),W,Y,j),J)}}function h9($,Z,J){return{...T0,...bZ(i0($,Z),J)}}function p9($,Z){return V4(b0($),b0(Z))}function V4($,Z){return Math.trunc((Z-$)/g0)}function _J($,Z){return G$(Z)-G$($)}function F4($,Z){if(!SZ($,Z))throw RangeError(gJ);return $}function NV($){function Z(Y){return((j,z)=>({...c9(j,z),F:j.month,day:parseInt(j.day)}))(_7(J,Y),W)}let J=eJ($),W=w6($);return{id:$,O:_V(Z),B:IV(Z)}}function _V($){return m0((Z)=>{let J=b0(Z);return $(J)},WeakMap)}function IV($){let Z=$(0).year-KF;return m0((J)=>{let W,Y=CZ(J-Z),j=[],z=[];do Y+=400*g0;while((W=$(Y)).year<=J);do Y+=(1-W.day)*g0,W.year===J&&(j.push(Y),z.push(W.F)),Y-=g0;while((W=$(Y)).year>=J);return{k:j.reverse(),C:ez(z.reverse())}})}function c9($,Z){let J,W,Y=d9($);if($.era){let j=QX[Z];j!==void 0&&(J=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),J==="bc"||J==="b"?J="bce":J!=="ad"&&J!=="a"||(J="ce"),W=Y,Y=n9(W,j[J]||0))}return{era:J,eraYear:W,year:Y}}function d9($){return parseInt($.relatedYear||$.year)}function X7($){let{year:Z,F:J,day:W}=this.O($),{C:Y}=this.B(Z);return[Z,Y[J]+1,W]}function L3($,Z=1,J=1){return this.B($).k[Z-1]+(J-1)*g0}function _6($){let Z=ej(this,$),J=ej(this,$-1),W=Z.length;if(W>J.length){let Y=o9(this);if(Y<0)return-Y;for(let j=0;j<W;j++)if(Z[j]!==J[j])return j+1}}function I6($){return V4(L3.call(this,$),L3.call(this,$+1))}function tj($,Z){let{k:J}=this.B($),W=Z+1,Y=J;return W>J.length&&(W=1,Y=this.B($+1).k),V4(J[Z-1],Y[W-1])}function x6($){return this.B($).k.length}function ej($,Z){return Object.keys($.B(Z).C)}function u9($){return x3(J0($))}function x3($){if(($=$.toLowerCase())!==q&&$!==P4&&w6($)!==w6(eJ($).resolvedOptions().calendar))throw RangeError(pV($));return $}function w6($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function l9($){return this.R($)[0]}function i9($){return this.R($)[1]}function IJ($){let[Z]=this.h($);return V4(this.q(Z),b0($))+1}function s9($){let Z=mF.exec($);if(!Z)throw RangeError(mV($));return[parseInt(Z[1]),Boolean(Z[2])]}function q6($,Z,J){return $+(Z||J&&$>=J?1:0)}function Q7($,Z){return $-(Z&&$>=Z?1:0)}function n9($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function G7($){return QX[a9($)]}function o9($){return ZF[a9($)]}function a9($){return w6($.id||q)}function r9($,Z,J,W){let Y=U$(J,W,z1,[],YX);if(Y.timeZone!==void 0){let j=J.dateFromFields(Y),z=u$(Y),X=$(Y.timeZone);return{epochNanoseconds:p$(Z(X),{...j,...z},Y.offset!==void 0?RZ(Y.offset):void 0),timeZone:X}}return{...J.dateFromFields(Y),...Z1}}function t9($,Z,J,W,Y,j){let z=U$(J,Y,z1,JX,YX),X=$(z.timeZone),[Q,G,B]=_3(j),V=J.dateFromFields(z,n6(j,Q)),K=u$(z,Q);return N0(p$(Z(X),{...V,...K},z.offset!==void 0?RZ(z.offset):void 0,G,B),X,W)}function e9($,Z,J){let W=U$($,Z,z1,[],h1),Y=g(J);return G0(v1({...$.dateFromFields(W,n6(J,Y)),...u$(W,Y)}))}function xJ($,Z,J,W=[]){let Y=U$($,Z,z1,W);return $.dateFromFields(Y,J)}function CJ($,Z,J,W){let Y=U$($,Z,pJ,W);return $.yearMonthFromFields(Y,J)}function AJ($,Z,J,W,Y=[]){let j=U$($,J,z1,Y);return Z&&j.month!==void 0&&j.monthCode===void 0&&j.year===void 0&&(j.year=IZ),$.monthDayFromFields(j,W)}function $z($,Z){let J=g(Z);return j1(u$(U1($,B7,[],1),J))}function Zz($){let Z=U1($,cJ);return e(EZ({...T0,...Z}))}function U$($,Z,J,W=[],Y=[]){return U1(Z,[...$.fields(J),...Y].sort(),W)}function U1($,Z,J,W=!J){let Y={},j,z=0;for(let X of Z){if(X===j)throw RangeError(kV(X));if(X==="constructor"||X==="__proto__")throw RangeError(yJ(X));let Q=$[X];if(Q!==void 0)z=1,W2[X]&&(Q=W2[X](Q,X)),Y[X]=Q;else if(J){if(J.includes(X))throw TypeError(qJ(X));Y[X]=XX[X]}j=X}if(W&&!z)throw TypeError(uz(Z));return Y}function u$($,Z){return i6(dF({...XX,...$}),Z)}function Jz($,Z,J,W,Y,j){let z=Q0(j),{calendar:X,timeZone:Q}=J;return N0(((G,B,V,K,F)=>{let D=C3(G,V,K,z1,WX,ZX),[U,O,L]=_3(F,2);return p$(B,{...G.dateFromFields(D,n6(F,U)),...u$(D,U)},RZ(D.offset),O,L)})($(X),Z(Q),W,Y,z),Q,X)}function Wz($,Z,J,W,Y){let j=Q0(Y);return G0(((z,X,Q,G)=>{let B=C3(z,X,Q,z1,h1),V=g(G);return v1({...z.dateFromFields(B,n6(G,V)),...u$(B,V)})})($(Z.calendar),J,W,j))}function Yz($,Z,J,W,Y){let j=Q0(Y);return((z,X,Q,G)=>{let B=C3(z,X,Q,z1);return z.dateFromFields(B,G)})($(Z.calendar),J,W,j)}function jz($,Z,J,W,Y){let j=Q0(Y);return q$(((z,X,Q,G)=>{let B=C3(z,X,Q,pJ);return z.yearMonthFromFields(B,G)})($(Z.calendar),J,W,j))}function zz($,Z,J,W,Y){let j=Q0(Y);return((z,X,Q,G)=>{let B=C3(z,X,Q,z1);return z.monthDayFromFields(B,G)})($(Z.calendar),J,W,j)}function Xz($,Z,J){return j1(((W,Y,j)=>{let z=g(j);return u$({...p0(B7,W),...U1(Y,B7)},z)})($,Z,J))}function Qz($,Z){return e((J=$,W=Z,EZ({...J,...U1(W,cJ)})));var J,W}function C3($,Z,J,W,Y=[],j=[]){let z=[...$.fields(W),...Y].sort(),X=U1(Z,z,j),Q=U1(J,z);return X=$.mergeFields(X,Q),U1(X,z,[])}function SJ($,Z){let J=U$($,Z,zX);return $.monthDayFromFields(J)}function EJ($,Z,J){let W=U$($,Z,jX);return $.yearMonthFromFields(W,J)}function Gz($,Z,J,W,Y){Z=p0(J=$.fields(J),Z),W=U1(W,Y=$.fields(Y),[]);let j=$.mergeFields(Z,W);return j=U1(j,[...J,...Y].sort(),[]),$.dateFromFields(j)}function J7($,Z){let{era:J,eraYear:W,year:Y}=Z,j=G7($);if(J!==void 0||W!==void 0){if(J===void 0||W===void 0)throw TypeError(qV);if(!j)throw RangeError(wV);let z=j[J];if(z===void 0)throw RangeError(vV(J));let X=n9(W,z);if(Y!==void 0&&Y!==X)throw RangeError(yV);Y=X}else if(Y===void 0)throw TypeError(gV(j));return Y}function W7($,Z,J,W){let{month:Y,monthCode:j}=Z;if(j!==void 0){let z=((X,Q,G,B)=>{let V=X.U(G),[K,F]=s9(Q),D=q6(K,F,V);if(F){let U=o9(X);if(U===void 0)throw RangeError(V3);if(U>0){if(D>U)throw RangeError(V3);if(V===void 0){if(B===1)throw RangeError(V3);D--}}else{if(D!==-U)throw RangeError(V3);if(V===void 0&&B===1)throw RangeError(V3)}}return D})($,j,J,W);if(Y!==void 0&&Y!==z)throw RangeError(nz);Y=z,W=1}else if(Y===void 0)throw TypeError(hV);return t0("month",Y,1,$.L(J),W)}function $2($,Z,J,W,Y){return y0(Z,"day",1,$.j(W,J),Y)}function Y7($,Z,J,W){let Y=0,j=[];for(let z of J)Z[z]!==void 0?Y=1:j.push(z);if(Object.assign($,Z),Y)for(let z of W||j)delete $[z]}function Kz($){return M0(n0(c6(p6($))))}function Bz($,Z,J,W,Y=q){return N0(n0(c6(p6(J))),Z(W),$(Y))}function Vz($,Z,J,W,Y=0,j=0,z=0,X=0,Q=0,G=0,B=q){return G0(v1(l6(J1(A0,xZ(T4,[Z,J,W,Y,j,z,X,Q,G])))),$(B))}function Fz($,Z,J,W,Y=q){return K0(z$(g$(J1(A0,{isoYear:Z,isoMonth:J,isoDay:W}))),$(Y))}function Uz($,Z,J,W=q,Y=1){let j=A0(Z),z=A0(J),X=$(W);return q$(I7(g$({isoYear:j,isoMonth:z,isoDay:A0(Y)})),X)}function Dz($,Z,J,W=q,Y=IZ){let j=A0(Z),z=A0(J),X=$(W);return R6(z$(g$({isoYear:A0(Y),isoMonth:j,isoDay:z})),X)}function Oz($=0,Z=0,J=0,W=0,Y=0,j=0){return j1(i6(J1(A0,xZ(X1,[$,Z,J,W,Y,j])),1))}function Lz($=0,Z=0,J=0,W=0,Y=0,j=0,z=0,X=0,Q=0,G=0){return e(EZ(J1(T2,xZ(h,[$,Z,J,W,Y,j,z,X,Q,G]))))}function bJ($,Z,J=q){return N0($.epochNanoseconds,Z,J)}function Mz($){return M0($.epochNanoseconds)}function RJ($,Z){return G0(R0(Z,$))}function fJ($,Z){return K0(R0(Z,$))}function Hz($,Z,J){return EJ($(Z.calendar),J)}function Pz($,Z,J){return SJ($(Z.calendar),J)}function kJ($,Z){return j1(R0(Z,$))}function Tz($,Z,J,W){let Y=((j,z,X,Q)=>{let G=S7(Q);return h0(j(z),X,G)})($,J,Z,W);return N0(n0(Y),J,Z.calendar)}function Nz($,Z,J){let W=$(Z.calendar);return q$({...Z,...EJ(W,J)})}function _z($,Z,J){return SJ($(Z.calendar),J)}function Iz($,Z,J,W,Y){let j=$(Y.timeZone),z=Y.plainTime,X=z!==void 0?Z(z):Z1;return N0(h0(J(j),{...W,...X}),j,W.calendar)}function xz($,Z=Z1){return G0(v1({...$,...Z}))}function Cz($,Z,J){return EJ($(Z.calendar),J)}function Az($,Z,J){return SJ($(Z.calendar),J)}function Sz($,Z,J,W){return((Y,j,z)=>Gz(Y,j,jX,y1(z),R3))($(Z.calendar),J,W)}function Ez($,Z,J,W){return((Y,j,z)=>Gz(Y,j,zX,y1(z),H4))($(Z.calendar),J,W)}function bz($,Z,J,W,Y){let j=y1(Y),z=Z(j.plainDate),X=$(j.timeZone);return N0(h0(J(X),{...z,...W}),X,z.calendar)}function Rz($,Z){return G0(v1({...$,...Z}))}function fz($){return M0(n0(NZ($,$1)))}function kz($){return M0(n0(NZ($,O1)))}function wz($){return M0(n0(c6(p6($),i$)))}function qz($){return M0(n0(c6(p6($))))}function yz($,Z,J=Z1){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J};return N0(p$(Y,j,j.offsetNanoseconds,2),W,Z.calendar)}function vz($,Z,J){let W=Z.timeZone,Y=$(W),j={...R0(Z,Y),...J},z=pz(Z.calendar,J.calendar);return N0(p$(Y,j,j.offsetNanoseconds,2),W,z)}function gz($,Z=Z1){return G0({...$,...Z})}function mz($,Z){return G0({...$,...Z},pz($.calendar,Z.calendar))}function U4($,Z){return{...$,calendar:Z}}function hz($,Z){return{...$,timeZone:Z}}function pz($,Z){if($===Z)return $;let J=P0($),W=P0(Z);if(J===W||J===q)return Z;if(W===q)return $;throw RangeError(gJ)}function xV($,Z){return(J)=>J===q?$:J===P4||J===_Z?Object.assign(Object.create($),{id:J}):Object.assign(Object.create(Z),gF(J))}function l$($,Z,J){let W=new Set(J);return(Y)=>(((j,z)=>{for(let X of z)if(X in j)return 1;return 0})(Y=D7(W,Y),$)||Object.assign(Y,Z),J&&(Y.timeZone=o$,["full","long"].includes(Y.timeStyle)&&(Y.timeStyle="medium")),Y)}function g1($,Z=wJ){let[J,,,W]=$;return(Y,j=jU,...z)=>{let X=Z(W&&W(...z),Y,j,J),Q=X.resolvedOptions();return[X,...CV($,Q,z)]}}function wJ($,Z,J,W){if(J=W(J),$){if(J.timeZone!==void 0)throw TypeError(tV);J.timeZone=$}return new D$(Z,J)}function CV($,Z,J){let[,W,Y]=$;return J.map((j)=>(j.calendar&&((z,X,Q)=>{if((Q||z!==q)&&z!==X)throw RangeError(gJ)})(P0(j.calendar),Z.calendar,Y),W(j,Z)))}function kZ($){let Z=A3();return B$(Z,$.getOffsetNanosecondsFor(Z))}function A3(){return NZ(Date.now(),O1)}function m1(){return j2||(j2=new D$().resolvedOptions().timeZone)}var AV=($,Z)=>`Non-integer ${$}: ${Z}`,SV=($,Z)=>`Non-positive ${$}: ${Z}`,EV=($,Z)=>`Non-finite ${$}: ${Z}`,bV=($)=>`Cannot convert bigint to ${$}`,RV=($)=>`Invalid bigint: ${$}`,fV="Cannot convert Symbol to string",cz="Invalid object",dz=($,Z,J,W,Y)=>Y?dz($,Y[Z],Y[J],Y[W]):S3($,Z)+`; must be between ${J}-${W}`,S3=($,Z)=>`Invalid ${$}: ${Z}`,qJ=($)=>`Missing ${$}`,yJ=($)=>`Invalid field ${$}`,kV=($)=>`Duplicate field ${$}`,uz=($)=>"No valid fields: "+$.join(),lz="Invalid bag",iz=($,Z,J)=>S3($,Z)+"; must be "+Object.keys(J).join(),sz="Cannot use valueOf",vJ="Invalid calling context",wV="Forbidden era/eraYear",qV="Mismatching era/eraYear",yV="Mismatching year/eraYear",vV=($)=>`Invalid era: ${$}`,gV=($)=>"Missing year"+($?"/era/eraYear":""),mV=($)=>`Invalid monthCode: ${$}`,nz="Mismatching month/monthCode",hV="Missing month/monthCode",Z2="Cannot guess year",V3="Invalid leap month",oz="Invalid protocol",E3="Invalid protocol results",gJ="Mismatching Calendars",pV=($)=>`Invalid Calendar: ${$}`,az="Mismatching TimeZones",cV="Forbidden ICU TimeZone",dV="Out-of-bounds offset",uV="Out-of-bounds TimeZone gap",lV="Invalid TimeZone offset",iV="Ambiguous offset",D4="Out-of-bounds date",sV="Out-of-bounds duration",nV="Cannot mix duration signs",O4="Missing relativeTo",oV="Cannot use large units",aV="Required smallestUnit or largestUnit",rV="smallestUnit > largestUnit",v0=($)=>`Cannot parse: ${$}`,q1=($)=>`Invalid substring: ${$}`,rz=($)=>`Cannot format ${$}`,tz="Mismatching types for formatting",tV="Cannot specify TimeZone",ez=w(P3,($,Z)=>Z),wZ=w(P3,($,Z,J)=>J),e0=w(S6,2),K7={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},b3=Object.keys(K7),g0=86400000,$X=1000,i$=1000,O1=1e6,$1=1e9,L4=60000000000,M4=3600000000000,l=86400000000000,D1=[1,i$,O1,$1,L4,M4,l],h1=b3.slice(0,6),B7=T3(h1),ZX=["offset"],JX=["timeZone"],WX=h1.concat(ZX),YX=WX.concat(JX),V7=["era","eraYear"],eV=V7.concat(["year"]),H4=["year"],mJ=["monthCode"],hJ=["month"].concat(mJ),R3=["day"],pJ=hJ.concat(H4),jX=mJ.concat(H4),z1=R3.concat(pJ),$F=R3.concat(hJ),zX=R3.concat(mJ),XX=wZ(h1,0),q="iso8601",P4="gregory",_Z="japanese",QX={[P4]:{bce:-1,ce:0},[_Z]:{bce:-1,ce:0,meiji:1867,taisho:1911,showa:1925,heisei:1988,reiwa:2018},ethioaa:{era0:0},ethiopic:{era0:0,era1:5500},coptic:{era0:-1,era1:0},roc:{beforeroc:-1,minguo:0},buddhist:{be:0},islamic:{ah:0},indian:{saka:0},persian:{ap:0}},ZF={chinese:13,dangi:13,hebrew:-6},J0=w(h6,"string"),GX=w(h6,"boolean"),JF=w(h6,"number"),KX=w(h6,"function"),h=b3.map(($)=>$+"s"),cJ=T3(h),WF=h.slice(0,6),BX=h.slice(6),YF=BX.slice(1),jF=ez(h),T0=wZ(h,0),dJ=wZ(WF,0),uJ=w(K2,h),X1=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],lJ=["isoDay","isoMonth","isoYear"],T4=X1.concat(lJ),iJ=T3(lJ),VX=T3(X1),FX=T3(T4),Z1=wZ(VX,0),zF=w(K2,T4),D$=Intl.DateTimeFormat,UX="en-GB",sJ=1e8,XF=sJ*g0,QF=[sJ,0],GF=[-sJ,0],M3=275760,H3=-271821,KF=1970,IZ=1972,k1=12,BF=CZ(1868,9,8),VF=m0(VV,WeakMap),y6="smallestUnit",F7="unit",U3="roundingIncrement",j7="fractionalSecondDigits",DX="relativeTo",OX={constrain:0,reject:1},FF=Object.keys(OX),UF={compatible:0,reject:1,earlier:2,later:3},DF={reject:0,use:1,prefer:2,ignore:3},OF={auto:0,never:1,critical:2,always:3},LF={auto:0,never:1,critical:2},MF={auto:0,never:1},HF={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},f3=w(w7,y6),nJ=w(w7,"largestUnit"),PF=w(w7,F7),LX=w(m$,"overflow",OX),MX=w(m$,"disambiguation",UF),TF=w(m$,"offset",DF),oJ=w(m$,"calendarName",OF),NF=w(m$,"timeZoneName",LF),_F=w(m$,"offset",MF),k3=w(m$,"roundingMode",HF),qZ="PlainYearMonth",yZ="PlainMonthDay",s$="PlainDate",n$="PlainDateTime",N4="PlainTime",p1="ZonedDateTime",_4="Instant",I4="Duration",IF=[Math.floor,($)=>N6($)?Math.floor($):Math.round($),Math.ceil,($)=>N6($)?Math.ceil($):Math.round($),Math.trunc,($)=>N6($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>N6($)?($=Math.trunc($)||0)+$%2:Math.round($)],o$="UTC",C6=5184000,xF=b6(1847),CF=b6(new Date().getUTCFullYear()+10),AF=/0+$/,R0=m0(MV,WeakMap),J2=4294967295,x4=m0(($)=>{let Z=FJ($);return typeof Z=="object"?new PX(Z):new HX(Z||0)});class HX{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[x7($,this.v)]}l(){}}class PX{constructor($){this.$=((Z)=>{function J(Q){let G=z7(Q,z,X),[B,V]=aj(G),K=Y(B),F=Y(V);return K===F?K:W(j(B,V),K,F,Q)}function W(Q,G,B,V){let K,F;for(;(V===void 0||(K=V<Q[0]?G:V>=Q[1]?B:void 0)===void 0)&&(F=Q[1]-Q[0]);){let D=Q[0]+Math.floor(F/2);Z(D)===B?Q[1]=D:Q[0]=D+1}return K}let Y=m0(Z),j=m0(HV),z=xF,X=CF;return{G(Q){let G=J(Q-86400),B=J(Q+86400),V=Q-G,K=Q-B;if(G===B)return[V];let F=J(V);return F===J(K)?[Q-F]:G>B?[V,K]:[]},V:J,l(Q,G){let B=z7(Q,z,X),[V,K]=aj(B),F=C6*G,D=G<0?()=>K>z||(z=B,0):()=>V<X||(X=B,0);for(;D();){let U=Y(V),O=Y(K);if(U!==O){let L=j(V,K);W(L,U,O);let P=L[0];if((j$(P,Q)||1)===G)return P}V+=F,K+=F}}}})(((Z)=>(J)=>{let W=_7(Z,J*$X);return b6(d9(W),parseInt(W.month),parseInt(W.day),parseInt(W.hour),parseInt(W.minute),parseInt(W.second))-J})($))}getOffsetNanosecondsFor($){return this.$.V(I2($))*$1}getPossibleInstantsFor($){let[Z,J]=[b6((W=$).isoYear,W.isoMonth,W.isoDay,W.isoHour,W.isoMinute,W.isoSecond),W.isoMillisecond*O1+W.isoMicrosecond*i$+W.isoNanosecond];var W;return this.$.G(Z).map((Y)=>n0(TZ(NZ(Y,$1),J)))}l($,Z){let[J,W]=x2($),Y=this.$.l(J+(Z>0||W?1:0),Z);if(Y!==void 0)return NZ(Y,$1)}}var aJ="([+\u2212-])",A6="(?:[.,](\\d{1,9}))?",TX=`(?:(?:${aJ}(\\d{6}))|(\\d{4}))-?(\\d{2})`,rJ="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+A6+")?)?",tJ=aJ+rJ,SF=TX+"-?(\\d{2})(?:[T ]"+rJ+"(Z|"+tJ+")?)?",NX="\\[(!?)([^\\]]*)\\]",C4=`((?:${NX}){0,9})`,EF=fZ(TX+C4),bF=fZ("(?:--)?(\\d{2})-?(\\d{2})"+C4),RF=fZ(SF+C4),fF=fZ("T?"+rJ+"(?:"+tJ+")?"+C4),kF=fZ(tJ),wF=new RegExp(NX,"g"),qF=fZ(`${aJ}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${A6}H)?(?:(\\d+)${A6}M)?(?:(\\d+)${A6}S)?)?`),yF=m0(($)=>new D$(UX,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),vF=/^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/,gF=m0(NV),eJ=m0(($)=>new D$(UX,{calendar:$,timeZone:o$,era:"short",year:"numeric",month:"short",day:"numeric"})),mF=/^M(\d{2})(L?)$/,hF={era:E6,eraYear:A0,year:A0,month:ij,monthCode:E6,day:ij},pF=wZ(h1,A0),cF=wZ(h,T2),W2=Object.assign({},hF,pF,cF,{offset:E6}),dF=w(BV,h1,X1),Y2={dateAdd($,Z,J){let W=g(J),Y,{years:j,months:z,weeks:X,days:Q}=Z;if(Q+=O0(Z,5)[0],j||z)Y=((G,B,V,K,F)=>{let[D,U,O]=G.h(B);if(V){let[L,P]=G.I(D,U);D+=V,U=q6(L,P,G.U(D)),U=t0("month",U,1,G.L(D),F)}return K&&([D,U]=G._(D,U,K)),O=t0("day",O,1,G.j(D,U),F),G.q(D,U,O)})(this,$,j,z,W);else{if(!X&&!Q)return $;Y=b0($)}return Y+=(7*X+Q)*g0,z$(u6(Y))},dateUntil($,Z,J){if(J<=7){let Q=0,G=p9({...$,...Z1},{...Z,...Z1});return J===7&&([Q,G]=Q$(G,7)),{...T0,weeks:Q,days:G}}let W=this.h($),Y=this.h(Z),[j,z,X]=((Q,G,B,V,K,F,D)=>{let U=K-G,O=F-B,L=D-V;if(U||O){let P=Math.sign(U||O),H=Q.j(K,F),I=0;if(Math.sign(L)===-P){let E=H;[K,F]=Q._(K,F,-P),U=K-G,O=F-B,H=Q.j(K,F),I=P<0?-E:H}if(L=D-Math.min(V,H)+I,U){let[E,S]=Q.I(G,B),[R,k]=Q.I(K,F);if(O=R-E||Number(k)-Number(S),Math.sign(O)===-P){let N=P<0&&-Q.L(K);U=(K-=P)-G,O=F-q6(E,S,Q.U(K))+(N||Q.L(K))}}}return[U,O,L]})(this,...W,...Y);return J===8&&(z+=this.J(j,W[0]),j=0),{...T0,years:j,months:z,days:X}},dateFromFields($,Z){let J=g(Z),W=J7(this,$),Y=W7(this,$,W,J),j=$2(this,$,Y,W,J);return K0(z$(this.P(W,Y,j)),this.id||q)},yearMonthFromFields($,Z){let J=g(Z),W=J7(this,$),Y=W7(this,$,W,J);return q$(I7(this.P(W,Y,1)),this.id||q)},monthDayFromFields($,Z){let J=g(Z),W=!this.id,{monthCode:Y,year:j,month:z}=$,X,Q,G,B,V;if(Y!==void 0){[X,Q]=s9(Y),V=z2($,"day");let K=this.N(X,Q,V);if(!K)throw RangeError(Z2);if([G,B]=K,z!==void 0&&z!==B)throw RangeError(nz);W&&(B=t0("month",B,1,k1,1),V=t0("day",V,1,C7(j!==void 0?j:G,B),J))}else{G=j===void 0&&W?IZ:J7(this,$),B=W7(this,$,G,J),V=$2(this,$,B,G,J);let K=this.U(G);Q=B===K,X=Q7(B,K);let F=this.N(X,Q,V);if(!F)throw RangeError(Z2);[G,B]=F}return R6(z$(this.P(G,B,V)),this.id||q)},fields($){return G7(this)&&$.includes("year")?[...$,...V7]:$},mergeFields($,Z){let J=Object.assign(Object.create(null),$);return Y7(J,Z,hJ),G7(this)&&(Y7(J,Z,eV),this.id===_Z&&Y7(J,Z,$F,V7)),J},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,J]=this.h($);return this.j(Z,J)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:IJ,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,J]=this.h($),[W,Y]=this.I(Z,J);return((j,z)=>"M"+e0(j)+(z?"L":""))(W,Y)},dayOfWeek:b2,daysInWeek(){return 7}},uF={dayOfYear:IJ,h:A2,q:CZ},lF=Object.assign({},uF,{weekOfYear:l9,yearOfWeek:i9,R($){function Z(F){return(7-F<W?7:0)-F}function J(F){let D=E2(K+F),U=F||1,O=Z(F3(Q+D*U,7));return B=(D+(O-G)*U)/7}let W=this.id?1:4,Y=b2($),j=this.dayOfYear($),z=F3(Y-1,7),X=j-1,Q=F3(z-X,7),G=Z(Q),B,V=Math.floor((X-G)/7)+1,K=$.isoYear;return V?V>J(0)&&(V=1,K++):(V=J(-1),K--),[V,K,B]}}),iF={dayOfYear:IJ,h:X7,q:L3,weekOfYear:l9,yearOfWeek:i9,R(){return[]}},vZ=xV(Object.assign({},Y2,lF,{h:A2,ee($){return this.id===P4?R2($):this.id===_Z?VF($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[IZ,$]},K:A7,U(){},L:S2,J:($)=>$*k1,j:C7,X:E2,P:($,Z,J)=>({isoYear:$,isoMonth:Z,isoDay:J}),q:CZ,_:($,Z,J)=>($+=g6(J,k1),(Z+=L7(J,k1))<1?($--,Z+=k1):Z>k1&&($++,Z-=k1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},Y2,iF,{h:X7,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let J=_6.call(this,$);return[Q7(Z,J),J===Z]},N($,Z,J){let[W,Y,j]=X7.call(this,{isoYear:IZ,isoMonth:k1,isoDay:31}),z=_6.call(this,W),X=Y===z;(j$($,Q7(Y,z))||j$(Number(Z),Number(X))||j$(J,j))===1&&W--;for(let Q=0;Q<100;Q++){let G=W-Q,B=_6.call(this,G),V=q6($,Z,B);if(Z===(V===B)&&J<=tj.call(this,G,V))return[G,V]}},K($){let Z=I6.call(this,$);return Z>I6.call(this,$-1)&&Z>I6.call(this,$+1)},U:_6,L:x6,J($,Z){let J=Z+$,W=Math.sign($),Y=W<0?-1:0,j=0;for(let z=Z;z!==J;z+=W)j+=x6.call(this,z+Y);return j},j:tj,X:I6,P($,Z,J){return u6(L3.call(this,$,Z,J))},q:L3,_($,Z,J){if(J){if(Z+=J,!Number.isSafeInteger(Z))throw RangeError(D4);if(J<0)for(;Z<1;)Z+=x6.call(this,--$);else{let W;for(;Z>(W=x6.call(this,$));)Z-=W,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:J}=this.O($),{C:W}=this.B(Z);return W[J]+1},day($){return this.O($).day}})),X$="numeric",gZ=["timeZoneName"],_X={month:X$,day:X$},$W={year:X$,month:X$},ZW=Object.assign({},$W,{day:X$}),JW={hour:X$,minute:X$,second:X$},WW=Object.assign({},ZW,JW),sF=Object.assign({},WW,{timeZoneName:"short"}),nF=Object.keys($W),oF=Object.keys(_X),aF=Object.keys(ZW),rF=Object.keys(JW),YW=["dateStyle"],tF=nF.concat(YW),eF=oF.concat(YW),jW=aF.concat(YW,["weekday"]),w3=rF.concat(["dayPeriod","timeStyle"]),zW=jW.concat(w3),$U=zW.concat(gZ),ZU=gZ.concat(w3),JU=gZ.concat(jW),WU=gZ.concat(["day","weekday"],w3),YU=gZ.concat(["year","weekday"],w3),jU={},XW=[l$(zW,WW),o6],IX=[l$($U,sF),o6,0,($,Z)=>{let J=P0($.timeZone);if(Z&&P0(Z.timeZone)!==J)throw RangeError(az);return J}],QW=[l$(zW,WW,gZ),b0],GW=[l$(jW,ZW,ZU),b0],KW=[l$(w3,JW,JU),($)=>G$($)/O1],BW=[l$(tF,$W,WU),b0,1],VW=[l$(eF,_X,YU),b0,1],j2;function H1($,Z,J,W,Y){function j(...Q){if(!(this instanceof j))throw TypeError(vJ);SX(this,Z(...Q))}function z(Q,G){return Object.defineProperties(function(...B){return Q.call(this,X(this),...B)},U7(G))}function X(Q){let G=x0(Q);if(!G||G.branding!==$)throw TypeError(vJ);return G}return Object.defineProperties(j.prototype,{...X2(J1(z,J)),...v$(J1(z,W)),...v6("Temporal."+$)}),Object.defineProperties(j,{...v$(Y),...U7($)}),[j,(Q)=>{let G=Object.create(j.prototype);return SX(G,Q),G},X]}function RX($){return $=$.concat("id").sort(),(Z)=>{if(!Q2(Z,$))throw TypeError(oz);return Z}}function cZ($){if(x0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(lz);return $}function A4($,Z){let J={};for(let W in $)J[W]=({o:Y},j)=>{let z=x0(j)||{},{branding:X}=z,Q=X===s$||Z.includes(X)?z:w0(j);return Y[W](Q)};return J}function DW($){let Z={};for(let J in $)Z[J]=(W)=>{let{calendar:Y}=W;return(j=Y,typeof j=="string"?vZ(j):(z=j,Object.assign(Object.create(TU),{i:z})))[J](W);var j,z};return Z}function P$(){throw TypeError(sz)}function y3({calendar:$}){return typeof $=="string"?new IW($):$}function xX($,Z){if(Z=Q0(Z),L0($)){let W=x0($);if(W&&W.branding===yZ)return g(Z),W;let Y=wX($);return AJ(w4(Y||q),!Y,$,Z)}let J=L9(vZ,$);return g(Z),J}function fX($,Z,J){return W=Z.call($,k0(M0(J))),n7(N3(W));var W}function S4($,Z=gX){let J=Object.keys(Z).sort(),W={};for(let Y of J)W[Y]=w(Z[Y],$,KX($[Y]));return W}function s($,Z){return typeof $=="string"?x4($):S4($,Z)}function V0($){return s($,UW)}function L1($){if(L0($)){let Z=x0($);if(Z)switch(Z.branding){case _4:return Z;case p1:return M0(Z.epochNanoseconds)}}return V9($)}function CX($,Z,J){let W=Z.l(L1(J).epochNanoseconds,$);return W?k0(M0(W)):null}function a($){return L0($)?(x0($)||{}).timeZone||AU($):((Z)=>Q4(T9(J0(Z))))($)}function O$($,Z){if(L0($)){let J=x0($)||{};switch(J.branding){case N4:return g(Z),J;case n$:return g(Z),j1(J);case p1:return g(Z),kJ(V0,J)}return $z($,Z)}return g(Z),M9($)}function OW($){return $===void 0?void 0:O$($)}function mZ($,Z){if(Z=Q0(Z),L0($)){let W=x0($);return W&&W.branding===qZ?(g(Z),W):CJ(f4(v3($)),$,Z)}let J=O9(vZ,$);return g(Z),J}function L$($,Z){if(Z=Q0(Z),L0($)){let W=x0($)||{};switch(W.branding){case n$:return g(Z),W;case s$:return g(Z),G0({...W,...Z1});case p1:return g(Z),RJ(V0,W)}return e9(k4(v3($)),$,Z)}let J=D9($);return g(Z),J}function w0($,Z){if(Z=Q0(Z),L0($)){let W=x0($)||{};switch(W.branding){case s$:return g(Z),W;case n$:return g(Z),K0(W);case p1:return g(Z),fJ(V0,W)}return xJ(k4(v3($)),$,Z)}let J=z4($);return g(Z),J}function kX($,Z,J){return W1(Z.call($,Y0(K0(J,$))))}function P1($){return(Z)=>typeof Z=="string"?vZ(Z):((J,W)=>{let Y=Object.keys(W).sort(),j={};for(let z of Y)j[z]=w(W[z],J,J[z]);return j})(Z,$)}function W0($){if(L0($)){let Z=x0($);return Z&&Z.branding===I4?Z:Zz($)}return H9($)}function q3($){if($!==void 0){if(L0($)){let Z=x0($)||{};switch(Z.branding){case p1:case s$:return Z;case n$:return K0(Z)}let J=v3($);return{...r9(a,s,k4(J),$),calendar:J}}return F9($)}}function v3($){return wX($)||q}function wX($){let{calendar:Z}=$;if(Z!==void 0)return I0(Z)}function I0($){return L0($)?(x0($)||{}).calendar||cU($):((Z)=>x3(P9(J0(Z))))($)}function hZ($,Z){if(Z=Q0(Z),L0($)){let J=x0($);if(J&&J.branding===p1)return _3(Z),J;let W=v3($);return t9(a,s,k4(W),W,$,Z)}return U9($,Z)}function AX($){return J1((Z)=>(J)=>Z(FW(J)),$)}function FW($){return R0($,V0)}function zU(){let $=D$.prototype,Z=Object.getOwnPropertyDescriptors($),J=Object.getOwnPropertyDescriptors(D$),W=function(Y,j={}){if(!(this instanceof W))return new W(Y,j);xW.set(this,((z,X={})=>{let Q=new D$(z,X),G=Q.resolvedOptions(),B=G.locale,V=p0(Object.keys(X),G),K=m0(GU),F=(...D)=>{let U,O=D.map((L,P)=>{let H=x0(L),I=(H||{}).branding;if(P&&U&&U!==I)throw TypeError(tz);return U=I,H});return U?K(U)(B,V,...O):[Q,...D]};return F.u=Q,F})(Y,j))};for(let Y in Z){let j=Z[Y],z=Y.startsWith("format")&&XU(Y);typeof j.value=="function"?j.value=Y==="constructor"?W:z||QU(Y):z&&(j.get=function(){return z.bind(this)})}return J.prototype.value=Object.create($,Z),Object.defineProperties(W,J),W}function XU($){return function(...Z){let J=xW.get(this),[W,...Y]=J(...Z);return W[$](...Y)}}function QU($){return function(...Z){return xW.get(this).u[$](...Z)}}function GU($){let Z=KU[$];if(!Z)throw TypeError(rz($));return g1(Z,m0(wJ))}var KU={Instant:XW,PlainDateTime:QW,PlainDate:GW,PlainTime:KW,PlainYearMonth:BW,PlainMonthDay:VW},BU=g1(XW),VU=g1(IX),FU=g1(QW),UU=g1(GW),DU=g1(KW),OU=g1(BW),LU=g1(VW),LW={era:D2,eraYear:M7,year:N3,month:W1,daysInMonth:W1,daysInYear:W1,inLeapYear:GX,monthsInYear:W1},b4={monthCode:J0},MW={day:W1},qX={dayOfWeek:W1,dayOfYear:W1,weekOfYear:O2,yearOfWeek:M7,daysInWeek:W1},yX=Object.assign({},LW,b4,MW,qX),E4=new WeakMap,x0=E4.get.bind(E4),SX=E4.set.bind(E4),MU={...A4(LW,[qZ]),...A4(qX,[]),...A4(b4,[qZ,yZ]),...A4(MW,[yZ])},HW=DW(yX),HU=DW({...LW,...b4}),PU=DW({...b4,...MW}),g3={calendarId:($)=>P0($.calendar)},TU=J1(($,Z)=>function(J){let{i:W}=this;return $(W[Z](Y0(K0(J,W))))},yX),NU=P3(($)=>(Z)=>Z[$],h.concat("sign")),PW=P3(($,Z)=>(J)=>J[X1[Z]],h1),vX={epochSeconds:g2,epochMilliseconds:o6,epochMicroseconds:m2,epochNanoseconds:h2},m3=w(D7,new Set(["branding"])),[_U,pZ,IU]=H1(yZ,w(Dz,I0),{...g3,...PU},{getISOFields:m3,getCalendar:y3,with($,Z,J){return pZ(zz(mU,$,this,cZ(Z),J))},equals:($,Z)=>q9($,xX(Z)),toPlainDate($,Z){return Y0(Ez(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=LU(Z,J,$);return W.format(Y)},toString:d7,toJSON:($)=>d7($),valueOf:P$},{from:($,Z)=>pZ(xX($,Z))}),gX={getOffsetNanosecondsFor:fX,getPossibleInstantsFor($,Z,J){let W=[...Z.call($,_0(G0(J,q)))].map((j)=>CU(j).epochNanoseconds),Y=W.length;return Y>1&&(W.sort(E0),o7(s0(i0(W[0],W[Y-1])))),W}},UW={getOffsetNanosecondsFor:fX},[xU,k0,CU]=H1(_4,Kz,vX,{add:($,Z)=>k0(a7(0,$,W0(Z))),subtract:($,Z)=>k0(a7(1,$,W0(Z))),until:($,Z,J)=>n(LJ(0,$,L1(Z),J)),since:($,Z,J)=>n(LJ(1,$,L1(Z),J)),round:($,Z)=>k0(d2($,Z)),equals:($,Z)=>b9($,L1(Z)),toZonedDateTime($,Z){let J=y1(Z);return B0(bJ($,a(J.timeZone),I0(J.calendar)))},toZonedDateTimeISO:($,Z)=>B0(bJ($,a(Z))),toLocaleString($,Z,J){let[W,Y]=BU(Z,J,$);return W.format(Y)},toString:($,Z)=>g7(a,V0,$,Z),toJSON:($)=>g7(a,V0,$),valueOf:P$},{from:($)=>k0(L1($)),fromEpochSeconds:($)=>k0(fz($)),fromEpochMilliseconds:($)=>k0(kz($)),fromEpochMicroseconds:($)=>k0(wz($)),fromEpochNanoseconds:($)=>k0(qz($)),compare:($,Z)=>UJ(L1($),L1(Z))}),[R4,YT]=H1("TimeZone",($)=>{let Z=S9($);return{branding:"TimeZone",id:Z,o:x4(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(L$(Z)).map((J)=>k0(M0(J))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor(L1(Z).epochNanoseconds),getOffsetStringFor($,Z){let J=L1(Z).epochNanoseconds,W=S4(this,UW).getOffsetNanosecondsFor(J);return h$(W)},getPlainDateTimeFor($,Z,J=q){let W=L1(Z).epochNanoseconds,Y=S4(this,UW).getOffsetNanosecondsFor(W);return _0(G0(B$(W,Y),I0(J)))},getInstantFor($,Z,J){let W=L$(Z),Y=S7(J),j=S4(this);return k0(M0(h0(j,W,Y)))},getNextTransition:({o:$},Z)=>CX(1,$,Z),getPreviousTransition:({o:$},Z)=>CX(-1,$,Z),equals($,Z){return!!K4(this,a(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=a($);return typeof Z=="string"?new R4(Z):Z}}),AU=RX(Object.keys(gX)),[SU,M$]=H1(N4,Oz,PW,{getISOFields:m3,with($,Z,J){return M$(Xz(this,cZ(Z),J))},add:($,Z)=>M$(ZJ(0,$,W0(Z))),subtract:($,Z)=>M$(ZJ(1,$,W0(Z))),until:($,Z,J)=>n(NJ(0,$,O$(Z),J)),since:($,Z,J)=>n(NJ(1,$,O$(Z),J)),round:($,Z)=>M$(i2($,Z)),equals:($,Z)=>y9($,O$(Z)),toZonedDateTime:($,Z)=>B0(bz(a,w0,s,$,Z)),toPlainDateTime:($,Z)=>_0(Rz($,w0(Z))),toLocaleString($,Z,J){let[W,Y]=DU(Z,J,$);return W.format(Y)},toString:u7,toJSON:($)=>u7($),valueOf:P$},{from:($,Z)=>M$(O$($,Z)),compare:($,Z)=>G4(O$($),O$(Z))}),[EU,H$,bU]=H1(qZ,w(Uz,I0),{...g3,...HU},{getISOFields:m3,getCalendar:y3,with($,Z,J){return H$(jz(gU,$,this,cZ(Z),J))},add:($,Z,J)=>H$($J(EX,0,$,W0(Z),J)),subtract:($,Z,J)=>H$($J(EX,1,$,W0(Z),J)),until:($,Z,J)=>n(TJ(bX,0,$,mZ(Z),J)),since:($,Z,J)=>n(TJ(bX,1,$,mZ(Z),J)),equals:($,Z)=>w9($,mZ(Z)),toPlainDate($,Z){return Y0(Sz(h3,$,this,Z))},toLocaleString($,Z,J){let[W,Y]=OU(Z,J,$);return W.format(Y)},toString:c7,toJSON:($)=>c7($),valueOf:P$},{from:($,Z)=>H$(mZ($,Z)),compare:($,Z)=>d$(mZ($),mZ(Z))}),[RU,_0]=H1(n$,w(Vz,I0),{...g3,...HW,...PW},{getISOFields:m3,getCalendar:y3,with($,Z,J){return _0(Wz(h3,$,this,cZ(Z),J))},withCalendar:($,Z)=>_0(U4($,I0(Z))),withPlainDate:($,Z)=>_0(mz($,w0(Z))),withPlainTime:($,Z)=>_0(gz($,OW(Z))),add:($,Z,J)=>_0(t7(a$,0,$,W0(Z),J)),subtract:($,Z,J)=>_0(t7(a$,1,$,W0(Z),J)),until:($,Z,J)=>n(HJ(M1,0,$,L$(Z),J)),since:($,Z,J)=>n(HJ(M1,1,$,L$(Z),J)),round:($,Z)=>_0(l2($,Z)),equals:($,Z)=>f9($,L$(Z)),toZonedDateTime:($,Z,J)=>B0(Tz(s,$,a(Z),J)),toPlainDate:($)=>Y0(K0($)),toPlainTime:($)=>M$(j1($)),toPlainYearMonth($){return H$(Nz(f4,$,this))},toPlainMonthDay($){return pZ(_z(w4,$,this))},toLocaleString($,Z,J){let[W,Y]=FU(Z,J,$);return W.format(Y)},toString:h7,toJSON:($)=>h7($),valueOf:P$},{from:($,Z)=>_0(L$($,Z)),compare:($,Z)=>OJ(L$($),L$(Z))}),[fU,Y0,mX]=H1(s$,w(Fz,I0),{...g3,...HW},{getISOFields:m3,getCalendar:y3,with($,Z,J){return Y0(Yz(h3,$,this,cZ(Z),J))},withCalendar:($,Z)=>Y0(U4($,I0(Z))),add:($,Z,J)=>Y0(e7(a$,0,$,W0(Z),J)),subtract:($,Z,J)=>Y0(e7(a$,1,$,W0(Z),J)),until:($,Z,J)=>n(PJ(M1,0,$,w0(Z),J)),since:($,Z,J)=>n(PJ(M1,1,$,w0(Z),J)),equals:($,Z)=>k9($,w0(Z)),toZonedDateTime($,Z){let J=!L0(Z)||Z instanceof R4?{timeZone:Z}:Z;return B0(Iz(a,O$,s,$,J))},toPlainDateTime:($,Z)=>_0(xz($,OW(Z))),toPlainYearMonth($){return H$(Cz(f4,$,this))},toPlainMonthDay($){return pZ(Az(w4,$,this))},toLocaleString($,Z,J){let[W,Y]=UU(Z,J,$);return W.format(Y)},toString:p7,toJSON:($)=>p7($),valueOf:P$},{from:($,Z)=>Y0(w0($,Z)),compare:($,Z)=>d$(w0($),w0(Z))}),TW={fields($,Z,J){return[...Z.call($,J)]}},hX=Object.assign({dateFromFields($,Z,J,W){return mX(Z.call($,Object.assign(Object.create(null),J),W))}},TW),pX=Object.assign({yearMonthFromFields($,Z,J,W){return bU(Z.call($,Object.assign(Object.create(null),J),W))}},TW),cX=Object.assign({monthDayFromFields($,Z,J,W){return IU(Z.call($,Object.assign(Object.create(null),J),W))}},TW),NW={mergeFields($,Z,J,W){return y1(Z.call($,Object.assign(Object.create(null),J),Object.assign(Object.create(null),W)))}},kU=Object.assign({},hX,NW),wU=Object.assign({},pX,NW),qU=Object.assign({},cX,NW),_W={dateAdd($,Z,J,W,Y){return mX(Z.call($,Y0(K0(J,$)),n(e(W)),Y))}},dX=Object.assign({},_W,{dateUntil($,Z,J,W,Y,j){return pU(Z.call($,Y0(K0(J,$)),Y0(K0(W,$)),Object.assign(Object.create(null),j,{largestUnit:b3[Y]})))}}),yU=Object.assign({},_W,{day:kX}),vU=Object.assign({},dX,{day:kX}),f4=P1(pX),k4=P1(hX),w4=P1(cX),gU=P1(wU),h3=P1(kU),mU=P1(qU),a$=P1(_W),M1=P1(dX),EX=P1(yU),bX=P1(vU),[hU,n,pU]=H1(I4,Lz,{...NU,blank:G9},{with:($,Z)=>n(Qz($,Z)),negated:($)=>n(Y4($)),abs:($)=>n(Q9($)),add:($,Z,J)=>n(zJ(q3,M1,s,0,$,W0(Z),J)),subtract:($,Z,J)=>n(zJ(q3,M1,s,1,$,W0(Z),J)),round:($,Z)=>n(X9(q3,M1,s,$,Z)),total:($,Z)=>c2(q3,M1,s,$,Z),toLocaleString($,Z,J){return Intl.DurationFormat?new Intl.DurationFormat(Z,J).format(this):e6($)},toString:e6,toJSON:($)=>e6($),valueOf:P$},{from:($)=>n(W0($)),compare:($,Z,J)=>E9(q3,a$,s,W0($),W0(Z),J)}),uX={toString:($)=>$.id,toJSON:($)=>$.id,...MU,dateAdd:({id:$,o:Z},J,W,Y)=>Y0(K0(Z.dateAdd(w0(J),W0(W),Y),$)),dateUntil:({o:$},Z,J,W)=>n(e($.dateUntil(w0(Z),w0(J),k2(W)))),dateFromFields:({id:$,o:Z},J,W)=>Y0(xJ(Z,J,W,U2($))),yearMonthFromFields:({id:$,o:Z},J,W)=>H$(CJ(Z,J,W,V2($))),monthDayFromFields:({id:$,o:Z},J,W)=>pZ(AJ(Z,0,J,W,F2($))),fields({o:$},Z){let J=new Set(z1),W=[];for(let Y of Z){if(J0(Y),!J.has(Y))throw RangeError(yJ(Y));J.delete(Y),W.push(Y)}return $.fields(W)},mergeFields:({o:$},Z,J)=>$.mergeFields(O7(H7(Z)),O7(H7(J)))},[IW]=H1("Calendar",($)=>{let Z=u9($);return{branding:"Calendar",id:Z,o:vZ(Z)}},{id:($)=>$.id},uX,{from($){let Z=I0($);return typeof Z=="string"?new IW(Z):Z}}),cU=RX(Object.keys(uX).slice(4)),[dU,B0]=H1(p1,w(Bz,I0,a),{...vX,...g3,...AX(HW),...AX(PW),offset:($)=>h$(FW($).offsetNanoseconds),offsetNanoseconds:($)=>FW($).offsetNanoseconds,timeZoneId:($)=>P0($.timeZone),hoursInDay:($)=>s2(s,$)},{getISOFields:($)=>j9(V0,$),getCalendar:y3,getTimeZone:({timeZone:$})=>typeof $=="string"?new R4($):$,with($,Z,J){return B0(Jz(h3,s,$,this,cZ(Z),J))},withCalendar:($,Z)=>B0(U4($,I0(Z))),withTimeZone:($,Z)=>B0(hz($,a(Z))),withPlainDate:($,Z)=>B0(vz(s,$,w0(Z))),withPlainTime:($,Z)=>B0(yz(s,$,OW(Z))),add:($,Z,J)=>B0(r7(a$,s,0,$,W0(Z),J)),subtract:($,Z,J)=>B0(r7(a$,s,1,$,W0(Z),J)),until:($,Z,J)=>n(e(MJ(M1,s,0,$,hZ(Z),J))),since:($,Z,J)=>n(e(MJ(M1,s,1,$,hZ(Z),J))),round:($,Z)=>B0(u2(s,$,Z)),startOfDay:($)=>B0(n2(s,$)),equals:($,Z)=>R9($,hZ(Z)),toInstant:($)=>k0(Mz($)),toPlainDateTime:($)=>_0(RJ(V0,$)),toPlainDate:($)=>Y0(fJ(V0,$)),toPlainTime:($)=>M$(kJ(V0,$)),toPlainYearMonth($){return H$(Hz(f4,$,this))},toPlainMonthDay($){return pZ(Pz(w4,$,this))},toLocaleString($,Z,J={}){let[W,Y]=VU(Z,J,$);return W.format(Y)},toString:($,Z)=>m7(V0,$,Z),toJSON:($)=>m7(V0,$),valueOf:P$},{from:($,Z)=>B0(hZ($,Z)),compare:($,Z)=>DJ(hZ($),hZ(Z))}),uU=Object.defineProperties({},{...v6("Temporal.Now"),...v$({timeZoneId:()=>m1(),instant:()=>k0(M0(A3())),zonedDateTime:($,Z=m1())=>B0(N0(A3(),a(Z),I0($))),zonedDateTimeISO:($=m1())=>B0(N0(A3(),a($),q)),plainDateTime:($,Z=m1())=>_0(G0(kZ(V0(a(Z))),I0($))),plainDateTimeISO:($=m1())=>_0(G0(kZ(V0(a($))),q)),plainDate:($,Z=m1())=>Y0(K0(kZ(V0(a(Z))),I0($))),plainDateISO:($=m1())=>Y0(K0(kZ(V0(a($))),q)),plainTimeISO:($=m1())=>M$(j1(kZ(V0(a($)))))})}),dZ=Object.defineProperties({},{...v6("Temporal"),...v$({PlainYearMonth:EU,PlainMonthDay:_U,PlainDate:fU,PlainTime:SU,PlainDateTime:RU,ZonedDateTime:dU,Instant:xU,Calendar:IW,TimeZone:R4,Duration:hU,Now:uU})}),lU=zU(),xW=new WeakMap,iU=Object.defineProperties(Object.create(Intl),v$({DateTimeFormat:lU}));var q4="x-gemi-socket";var KT="gemi.v1",lX="/__gemi/socket",BT=/^[A-Za-z0-9_-]{1,32}$/,VT={Normal:1000,UnsupportedData:1003,PolicyViolation:1008,Restart:1012,TryAgainLater:1013,Revoked:4001};function OT($){return $}function iX(){return{driver:"memory",redis:{},maxEventBytes:16384,warnEventBytes:4096,path:lX,allowedOrigins:[],maxConnectionsPerProcess:1e4,maxConnectionsPerIp:100,maxConnectionsPerUser:50,maxChannelsPerSocket:50,maxInboundMessageBytes:16384,backpressureLimit:1048576,idleTimeout:120,heartbeatMs:25000,subscribeRate:{limit:300,windowMs:60000}}}import{hkdfSync as sU,randomBytes as nU}from"crypto";function oU($=process.env.SECRET){if(!$)return"gemi:bc:";return`gemi:bc:${Buffer.from(sU("sha256",$,"gemi","gemi.broadcast.prefix",4)).toString("hex")}:`}var aU="__control",CW=250,rU=1e4,tU=15000;class AW{config;prefix;controlChannel;instanceId=nU(9).toString("base64url");subscribeTimeoutMs;healthCheckMs;publisher=null;subscriber=null;ready=null;deliver=null;hooks;wanted=new Set;active=new Set;chains=new Map;connectedOnce=!1;reconnectAttempt=0;reconnectTimer=null;healthTimer=null;closed=!1;constructor($={}){this.config=$;this.prefix=$.prefix??oU(),this.controlChannel=this.prefix+aU,this.subscribeTimeoutMs=$.subscribeTimeoutMs??5000,this.healthCheckMs=$.healthCheckMs??30000}get connected(){return this.subscriber!==null&&this.ready===null}publish($,Z){return this.send(this.prefix+$,Z)}async revoke($){this.hooks?.onRevoke?.($);let Z={op:"revoke",from:this.instanceId,r:$};try{await this.send(this.controlChannel,JSON.stringify(Z))}catch(J){throw Error(`The broadcast revocation ${JSON.stringify($)} could not reach the other instances.`,{cause:J})}}async start($,Z){this.closed=!1,this.deliver=$,this.hooks=Z,this.connectSubscriber(),this.startHealthCheck();try{await this.whenReady()}catch{console.warn("[gemi] Broadcast: Redis is not reachable yet; sockets get events once it is.")}}topicAdded($){return this.wanted.add($),this.sync($,!0)}topicRemoved($){return this.wanted.delete($),this.sync($,!1)}async close(){if(this.closed=!0,this.deliver=null,this.hooks=void 0,this.reconnectTimer)clearTimeout(this.reconnectTimer);if(this.reconnectTimer=null,this.healthTimer)clearInterval(this.healthTimer);this.healthTimer=null;let $=[this.subscriber,this.publisher];this.subscriber=null,this.publisher=null,this.ready=null,this.wanted.clear(),this.active.clear(),this.chains.clear();for(let Z of $){if(!Z)continue;Z.onclose=null;try{Z.close()}catch{}}}async send($,Z){let J=this.publisherClient();try{await J.publish($,Z)}catch{if(this.closed)throw Error("The broadcast driver is closed.");this.dropPublisher(J),await this.publisherClient().publish($,Z)}}dropPublisher($){if(this.publisher!==$)return;this.publisher=null,$.onclose=null;try{$.close()}catch{}}publisherClient(){if(this.publisher)return this.publisher;let $=this.createClient("publisher");return $.onclose=()=>{if(this.publisher===$)this.publisher=null},this.publisher=$,$}createClient($){if(this.config.createClient)return this.config.createClient($);let Z=globalThis.Bun?.RedisClient;if(typeof Z!=="function")throw Error("The redis broadcast driver needs Bun's built-in Redis client. Run the app under Bun.");let J=$==="subscriber"?{...this.config.options,autoReconnect:!1}:{...this.config.options};return new Z(this.config.url,J)}connectSubscriber(){if(this.closed||this.ready)return;let $;try{$=this.createClient("subscriber")}catch(J){console.error("[gemi] Broadcast: the Redis subscriber could not be created.",J),this.scheduleReconnect();return}this.subscriber=$,this.active.clear(),$.onclose=()=>this.lost($);let Z=p3((async()=>{await $.connect(),await $.subscribe(this.controlChannel,this.onMessage);let J=[...this.wanted];if(await Promise.all(J.map((W)=>$.subscribe(this.prefix+W,this.onMessage))),this.subscriber!==$)throw Error("Replaced.");for(let W of J)this.active.add(W);return $})(),tU,"connect");this.ready=Z,Z.then(()=>{if(this.subscriber!==$)return;this.ready=null,this.reconnectAttempt=0;for(let J of this.active)if(!this.wanted.has(J))this.sync(J,!1).catch(()=>{});if(this.connectedOnce)this.hooks?.onGap?.();this.connectedOnce=!0},(J)=>{if(this.subscriber!==$||this.closed)return;console.warn(`[gemi] Broadcast: the Redis subscriber could not connect (${sX(J)}); retrying.`),this.drop($)})}lost($){if(this.subscriber!==$||this.closed)return;if(this.ready===null)console.warn("[gemi] Broadcast: the Redis subscriber connection dropped; reconnecting.");this.drop($)}drop($){if(this.subscriber!==$)return;this.subscriber=null,this.ready=null,this.active.clear(),$.onclose=null;try{$.close()}catch{}this.scheduleReconnect()}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;let $=Math.min(rU,CW*2**this.reconnectAttempt);this.reconnectAttempt=Math.min(this.reconnectAttempt+1,16);let Z=Math.max(CW,Math.floor(Math.random()*$));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connectSubscriber()},Z),this.reconnectTimer.unref?.()}startHealthCheck(){if(this.healthCheckMs<=0||this.healthTimer)return;this.healthTimer=setInterval(()=>{let $=this.subscriber;if(!$||this.ready)return;p3($.ping(),this.subscribeTimeoutMs,"ping").catch((Z)=>{if(this.subscriber!==$)return;console.warn(`[gemi] Broadcast: the Redis subscriber did not answer a ping (${sX(Z)}); reconnecting.`),this.drop($)})},this.healthCheckMs),this.healthTimer.unref?.()}async whenReady(){if(this.closed)throw Error("The broadcast driver is closed.");let $=Date.now()+this.subscribeTimeoutMs;for(;;){if(this.subscriber&&!this.ready)return this.subscriber;let Z=$-Date.now();if(Z<=0)throw Error("Redis did not answer in time.");let J=this.ready??eU(Math.min(Z,CW));await p3(J,Z,"subscribe").catch((W)=>{if(Date.now()>=$)throw W})}}sync($,Z){let W=(this.chains.get($)??Promise.resolve()).catch(()=>{}).then(()=>this.reconcile($,Z));this.chains.set($,W);let Y=()=>{if(this.chains.get($)===W)this.chains.delete($)};return W.then(Y,Y),W}async reconcile($,Z){if(!this.wanted.has($)){if(!this.active.has($)||!this.connected)return;let Y=this.subscriber;this.active.delete($);try{await p3(Y.unsubscribe(this.prefix+$),this.subscribeTimeoutMs,"unsubscribe")}catch(j){if(this.subscriber===Y)this.drop(Y);throw j}return}if(!Z)return;let W=await this.whenReady();if(!this.wanted.has($)||this.active.has($))return;try{await p3(W.subscribe(this.prefix+$,this.onMessage),this.subscribeTimeoutMs,"subscribe")}catch(Y){if(this.subscriber===W)this.drop(W);throw Y}if(this.subscriber===W)this.active.add($)}onMessage=($,Z)=>{if(Z===this.controlChannel){this.onControl($);return}if(!Z.startsWith(this.prefix))return;this.deliver?.(Z.slice(this.prefix.length),$)};onControl($){let Z;try{Z=JSON.parse($)}catch{return}if(Z?.op!=="revoke"||Z.from===this.instanceId)return;let J=Z.r;if(J&&typeof J.user==="string")this.hooks?.onRevoke?.({user:J.user});else if(J&&typeof J.topic==="string")this.hooks?.onRevoke?.({topic:J.topic})}}function p3($,Z,J){let W;return Promise.race([$,new Promise((Y,j)=>{W=setTimeout(()=>j(Error(`Redis ${J} timed out after ${Z} ms.`)),Z)})]).finally(()=>clearTimeout(W))}function eU($){return new Promise((Z)=>setTimeout(Z,$))}function sX($){return $ instanceof Error?$.message:String($)}import{createHmac as $D,hkdfSync as ZD,randomBytes as nX}from"crypto";function oX($){return $D("sha256",JD()).update($).digest("base64url").slice(0,22)}var y4=null;function JD(){let $=process.env.SECRET||void 0;if(y4&&y4.secret===$)return y4.key;let Z=$?Buffer.from(ZD("sha256",$,"gemi","gemi.broadcast.socket-tag",32)):nX(32);return y4={secret:$,key:Z},Z}function TT(){return nX(16).toString("base64url")}var WD=/^[A-Za-z0-9_-]{8,64}$/;function SW($){return typeof $==="string"&&WD.test($)}function aX($,Z,J,W){let Y={op:"ev",t:$,ev:Z};if(J!==void 0)Y.d=J;if(W)Y.x=W;return JSON.stringify(Y)}class tX extends Error{bytes;limit;constructor($,Z,J){super(`The broadcast "${J}" is ${$} bytes, over the limit of ${Z}. Send ids and a change hint, and let the client fetch the data over HTTP; or raise maxEventBytes in app/config/broadcast.ts.`);this.bytes=$;this.limit=Z;this.name="BroadcastPayloadTooLargeError"}}class c0{options;static token="broadcast";config;driver;warnedAboutSize=new Set;started=!1;hooks;channelRouter;constructor($={},Z={}){this.options=Z;this.config=T1(iX(),$),this.driver=zD(this.config,Z.application)}get channels(){if(this.channelRouter===void 0)this.channelRouter=this.options.channels?new this.options.channels:null;return this.channelRouter}to($,...Z){return new c3(this,v4($,Z[0]),null)}toUser($){return new c3(this,{topic:KZ($),pattern:U0},null)}toOthers($){return new eX(this,jD($))}broadcastEvent($){let Z=$.broadcastOn(),J=Array.isArray(Z)?Z:[Z],W=$.broadcastAs(),Y=$.broadcastWith(),j=J.map((z)=>this.prepare(v4(z,void 0),W,Y,null));for(let{sent:z,frame:X}of j)this.hand(z,X)}send($,Z,J,W){let{sent:Y,frame:j}=this.prepare($,Z,J,W);this.hand(Y,j)}prepare($,Z,J,W){N5(Z);let Y;try{Y=aX($.topic,Z,J,W?oX(W):null)}catch(z){throw TypeError(`The broadcast "${Z}" could not be encoded. Payloads must be JSON.`,{cause:z})}return this.checkSize(Z,Y),{sent:{topic:$.topic,...$.pattern?{pattern:$.pattern}:{},event:Z,data:JSON.parse(Y).d,...W?{except:W}:{}},frame:Y}}hand($,Z){uZ(()=>this.publish($,Z))}publish($,Z){let J=(W)=>console.error(`[gemi] The broadcast "${$.event}" on "${$.topic}" could not be published.`,W);try{let W=this.driver.publish($.topic,Z);if(W&&typeof W.catch==="function")W.catch(J)}catch(W){J(W)}}get isStarted(){return this.started}async start($,Z){if(this.started)throw Error("The broadcast driver was already started in this process.");this.started=!0,this.hooks=Z;try{await this.driver.start($,Z)}catch(J){throw this.started=!1,this.hooks=void 0,J}}topicAdded($){return this.driver.topicAdded?.($)}topicRemoved($){return this.driver.topicRemoved?.($)}async close(){this.started=!1,this.hooks=void 0,await this.driver.close()}revoke($){let Z=YD($);uZ(()=>this.sendRevocation(Z))}sendRevocation($){let Z=(J)=>console.error("[gemi] A broadcast revocation could not be sent.",J);try{if(typeof this.driver.revoke==="function"){let J=this.driver.revoke($);if(J&&typeof J.catch==="function")J.catch(Z);return}this.hooks?.onRevoke?.($)}catch(J){Z(J)}}checkSize($,Z){let J=Buffer.byteLength(Z,"utf8");if(J>this.config.maxEventBytes)throw new tX(J,this.config.maxEventBytes,$);let W=this.config.warnEventBytes;if(W!==!1&&J>W&&!this.warnedAboutSize.has($))this.warnedAboutSize.add($),console.warn(`[gemi] The broadcast "${$}" is ${J} bytes, over ${W}. Broadcasts are change hints: send ids and let the client fetch the data over HTTP. Warned once per event name.`)}}class c3{manager;target;except;constructor($,Z,J){this.manager=$;this.target=Z;this.except=J}emit($,...Z){this.manager.send(this.target,$,Z[0],this.except)}}class eX{manager;except;constructor($,Z){this.manager=$;this.except=Z}to($,...Z){return new c3(this.manager,v4($,Z[0]),this.except)}toUser($){return new c3(this.manager,{topic:KZ($),pattern:U0},this.except)}}function v4($,Z){if(T5($))return{topic:_8($.topic),...$.pattern?{pattern:$.pattern}:{}};if(Z!==void 0||$.includes(":"))return{topic:X3($,Z??{}),pattern:$};if($===U0)throw new u('"user" is not a topic: the "user" channel resolves to user.<id> per subscriber. Emit with Broadcast.toUser(user).');return{topic:_8($)}}function YD($){if($&&typeof $==="object"&&"user"in $)return{user:KZ($.user).slice(U0.length+1)};if($&&typeof $==="object"&&"channel"in $)return{topic:v4($.channel,$.params).topic};throw new u("Broadcast.revoke takes { user } or { channel }.")}function jD($){if($===null||$===void 0)return null;if(typeof $==="string")return SW($)?$:null;let J=($ instanceof Request?$.headers:("rawRequest"in $)?$.rawRequest.headers:$.headers)?.get(q4);return SW(J)?J:null}function zD($,Z){let J=$.driver;if(J===void 0||J==="memory")return new rX;if(J==="redis"){let W=Z?.config.get("redis",{})??{},Y=$.redis??{};return new AW({url:Y.url??W.url??process.env.REDIS_URL,options:Y.options??W.options,prefix:Y.prefix,subscribeTimeoutMs:Y.subscribeTimeoutMs,healthCheckMs:Y.healthCheckMs})}if(typeof J==="function"){if(!Z)throw Error("A broadcast driver factory needs the application to be called with.");return J(Z)}if(typeof J==="object"&&J!==null&&typeof J.publish==="function")return J;throw Error(`Unknown broadcast driver "${String(J)}" in app/config/broadcast.ts. Use "memory" or "redis", or pass a BroadcastDriver.`)}class EW extends Error{code;constructor($,Z=`OAuth callback failed: ${$}`){super(Z);this.name="OAuthCallbackError",this.code=$}}class XD{linkByEmail=!0;createUsers=!0;createUsersWithoutEmail=!1}import{createHash as bW,createHmac as QD,randomBytes as $Q,timingSafeEqual as WQ}from"crypto";var u3=600,g4="gemi_oauth",GD=`__Host-${g4}`;function lZ($,Z=g4){if(Z===g4)return $?GD:g4;return $?`__Host-${Z}`:Z}function d3($){return $.toString("base64url")}function YQ($){return QD("sha256",DZ()).update(`gemi-oauth-state:${$}`).digest()}function ZQ($,Z){let J=bW("sha256").update($).digest(),W=bW("sha256").update(Z).digest();return WQ(J,W)&&$.length===Z.length}function m4($,Z=Date.now(),J={}){let W=d3($Q(32)),Y=d3($Q(32)),j=KD(Y),z={provider:$,state:W,codeVerifier:Y,expiresAt:Z+u3*1000,...J.subject!==void 0?{subject:J.subject}:{},...J.returnTo!==void 0?{returnTo:J.returnTo}:{}};return{state:W,codeVerifier:Y,codeChallenge:j,cookieValue:BD(z)}}function KD($){return d3(bW("sha256").update($).digest())}function BD($){let Z=d3(Buffer.from(JSON.stringify($)));return`${Z}.${d3(YQ(Z))}`}function VD($){if(typeof $!=="string"||$==="")return null;let Z=$.indexOf(".");if(Z<=0||Z!==$.lastIndexOf("."))return null;let J=$.slice(0,Z),W=Buffer.from($.slice(Z+1),"base64url"),Y=YQ(J);if(W.length!==Y.length||!WQ(W,Y))return null;try{let j=JSON.parse(Buffer.from(J,"base64url").toString("utf8"));if(typeof j?.provider!=="string"||typeof j?.state!=="string"||typeof j?.codeVerifier!=="string"||typeof j?.expiresAt!=="number"||j.subject!==void 0&&typeof j.subject!=="string"||j.returnTo!==void 0&&typeof j.returnTo!=="string")return null;return j}catch{return null}}var T$=new Map,JQ=1e4;function FD($,Z,J){if(T$.size>=JQ){for(let[W,Y]of T$)if(Y<=J)T$.delete(W);while(T$.size>=JQ){let W=T$.keys().next().value;if(W===void 0)break;T$.delete(W)}}T$.set($,Z)}function h4($){let Z=$.now??Date.now();if(!$.cookieValue||!$.returnedState)return{ok:!1,reason:"missing_state"};let J=VD($.cookieValue);if(!J)return{ok:!1,reason:"invalid_state"};let W=ZQ(J.state,$.returnedState),Y=ZQ(J.provider,$.provider);if(!W||!Y)return{ok:!1,reason:"invalid_state"};if(J.expiresAt<=Z)return{ok:!1,reason:"expired_state"};if(T$.has(J.state))return{ok:!1,reason:"invalid_state"};return FD(J.state,J.expiresAt,Z),{ok:!0,payload:J}}var RW=new WeakMap;function DD($){let Z=RW.get($);if(!Z)Z=$(UD(32).toString("hex")),RW.set($,Z),Z.catch(()=>RW.delete($));return Z}async function fW($,Z,J){if(typeof J==="string"&&J!=="")return await $.verifyPassword(Z,J);try{await $.verifyPassword(Z,await DD($.hashPassword))}catch{}return!1}async function r$($,Z){let J=Z.user??Z.session?.user;if(!J||!$.onAuthenticated)return;let{password:W,...Y}=J;await $.onAuthenticated({...Z,user:Y})}class wW extends Error{}function kW($){return typeof $==="string"&&$!==""?$:null}function jQ($){return K3($)}var OD=256;function zQ($){return typeof $==="string"&&$!==""&&$.length<=OD?$:null}function XQ($){let{password:Z,code:J,...W}=$;return W}var p4="intended_url";function GQ($){if($.cookies.get(p4))$.ctx().setCookie(p4,"",{maxAge:-1})}function QQ($){let Z=$.cookies.get(p4);if(!Z)return null;GQ($);try{return V1(decodeURIComponent(Z),"")||null}catch{return null}}class qW extends C{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class KQ extends C{schema={email:{required:"Email is required",email:"Invalid email"}}}class BQ extends C{schema={password:{required:"Password is required",password:"Invalid password"}}}function c1($){if(M(b).config[$]===!1)throw new z0("Not found",{status:404})}class $0 extends G3{async me(){let $=await q0.user();if(!$)throw new p8;return $}async verifyEmail($=new C){c1("password");let Z=await $.input(),{userProvider:J}=M(b),W=kW(Z.get("token"));if(!W)return{email:null};let Y=await J.findUserByVerificationToken(W);if(!Y)return{email:null};return await J.verifyUser(Y.email),{email:Y.email}}async signInWithMagicLink($=new C){let Z=M(b),{userProvider:J}=Z,W=kW($.search.get("token")),Y=null;try{Y=K3(decodeURIComponent($.search.get("email")??""))}catch{}if(await LZ("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!Y||!W||!await Z.verifyMagicLinkToken(Y,W))return{error:"Invalid token"};await J.verifyUser(Y);let j=await Z.createOrUpdateSession({email:Y});return $.ctx().setCookie("access_token",j.token,M(b).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await r$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async verifyPinRequest($){c1("magicLink");let Z=M(b),J=await $.input(),{email:W,pin:Y}=J.toJSON(),j=K3(W),z=zQ(Y);if(await LZ("verify",j,$,Z.config.emailCode.verifyLimit),!j||!z)throw new d({pin:["Invalid pin"]});let X=await Z.verifyOneTimeCode(j,z);if(X.status==="too_many_attempts")throw new d({pin:["Too many attempts"]});if(X.status!=="ok")throw new d({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(j),j}async signInWithPinV2($=new C){let Z=M(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSessionV2({email:J});return $.ctx().setCookie("access_token",W.token,M(b).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await r$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),W}async signInWithPin($=new C){let Z=M(b),J=await this.verifyPinRequest($),W=await Z.createOrUpdateSession({email:J});return $.ctx().setCookie("access_token",W.token,M(b).accessTokenCookieOptions($,W.expiresAt)),await Z.config.onSignIn(W,$.search.toJSON()),await r$(Z.config,{session:W,isNewUser:!1,method:"magic-link",req:$}),{session:W}}async signInV2($=new qW){c1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(b),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await fW(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSessionV2({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(b).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await r$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signIn($=new qW){c1("password");let Z=await $.input(),{email:J,password:W}=Z.toJSON(),Y=J.toLowerCase().trim(),j=M(b),z=await j.userProvider.findUserByEmailAddress(Y,j.config.verifyEmail),X=typeof W==="string"&&await fW(j.config,W,z?.password);if(!z||!X)throw new d({invalid_credentials:["Invalid credentials"]});let Q=await j.createOrUpdateSession({email:z.email,id:z.id});$.ctx().setCookie("access_token",Q.token,M(b).accessTokenCookieOptions($,Q.expiresAt)),await j.config.onSignIn(z,$.search.toJSON()),await r$(j.config,{session:Q,user:z,isNewUser:!1,method:"password",req:$});let{password:G,...B}=z;return B}async signUp(){c1("password");let $=M(b),{userProvider:Z,config:J}=$,W=new J.signUpRequest,Y=await W.input(),{email:j,password:z,name:X,invitationId:Q}=Y.toJSON(),G={method:"password",input:XQ(Y.toJSON())},B=jQ(j);if(!B)throw new d({email:["Invalid email"]});if(z!=null&&typeof z!=="string")throw new d({password:["Invalid password"]});if(Q!=null&&typeof Q!=="string")throw new d({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(B,!1))throw new d({email:["Email address already exists"]});let K=await J.hashPassword(z),F=M(c).detectLocale(W),D;if(Q)D=await Z.findInvitation(Q,B);let U,O="";if(D)U=await Z.transaction(async()=>{await Z.deleteInvitationById(Q);let L=await Z.createUser({email:B,name:X,password:K,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:D.organizationId,userId:L.id,organizationRole:D.role}),await J.onUserCreated(L,G),L});else O=await J.generateEmailVerificationToken(B),U=await Z.transaction(async()=>{let L=await Z.createUser({email:B,name:X,password:K,verificationToken:O,locale:F});return await J.onUserCreated(L,G),L});return await J.onSignUp(U,O,W.search.toJSON()),U}async signOut($=new C){let Z=S$($),J=M(b),{config:W}=J,Y=await J.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",M(b).accessTokenCookieOptions($,new Date(0))),M(b).cookieDomain($))$.ctx().setCookie("access_token","",{...M(b).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(Y?.user)LD(Y.user),Y.user.extension=await W.extendSession(Y.user),await W.onSignOut(Y.user);return{}}async forgotPassword($=new KQ){c1("password");let Z=await $.input(),J=jQ(Z.get("email"));if(!J)return{};let{userProvider:W,config:Y}=M(b),j=await W.findUserByEmailAddress(J,Y.verifyEmail);if(!j)return{};let z=await Y.generateForgotPasswordToken(j);return await W.createPasswordResetToken({user:j,token:z}),await Y.onForgotPassword(j,z),{}}async resetPassword($=new BQ){c1("password");let{userProvider:Z,config:J}=M(b),W=await $.input(),{password:Y,token:j}=W.toJSON(),z=kW(j),X=z?await Z.findPasswordResetToken({token:z}):null;if(!X)throw new d({token:["Invalid token"]});if(dZ.Instant.from(X.createdAt.toISOString()).add({hours:24}).until(dZ.Now.instant()).sign>=0)throw new d({token:["Token expired"]});await Z.deletePasswordResetToken({token:z});let G=await Z.findUserByEmailAddress(X.user.email,J.verifyEmail);if(!G)throw new d({email:["User not found"]});let B=await J.hashPassword(Y);return await Z.updateUserPassword({id:G.id,password:B}),await Z.deleteAllUserSessions(G.id),await J.onResetPassword(G),{}}async changePassword($=new C){c1("password");let{userProvider:Z,config:J}=M(b),W=await q0.user(),Y=await $.input(),{oldPassword:j,newPassword:z}=Y.toJSON();if(typeof z!=="string")throw new d({newPassword:["Invalid password"]});let X=await Z.findUserByEmailAddress(W.email,J.verifyEmail);if(!(typeof j==="string"&&await fW(J,j,X?.password)))throw new d({oldPassword:["Incorrect password"]});let G=await J.hashPassword(z);return await Z.updateUserPassword({id:W.id,password:G}),await Z.deleteAllUserSessions(W.id),{}}async oauthRedirect($=new C){let{provider:Z}=$.params,J=M(b).config.oauthProviders,W=Object.hasOwn(J,Z),Y=await MZ(J,Z);if(!Y){if(W)throw new z0("Not found",{status:404});throw Error(`Invalid provider: ${Z}`)}let j=BZ($.rawRequest),z=V1($.search.get(B1),"");if(z)$.ctx().setCookie(p4,encodeURIComponent(z),{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:600});else GQ($);let{state:X,codeChallenge:Q,cookieValue:G}=m4(Z);return $.ctx().setCookie(lZ(j),G,{httpOnly:!0,sameSite:"Lax",secure:j,maxAge:u3}),{destination:await Y.getRedirectUrl($,{state:X,codeChallenge:Q,codeChallengeMethod:"S256"})}}async oauthCallback($=new C){let{provider:Z}=$.params,J=M(b),{userProvider:W,config:Y}=J,j=Object.hasOwn(Y.oauthProviders,Z),z=await MZ(Y.oauthProviders,Z);if(j&&!z)throw new z0("Not found",{status:404});let X=BZ($.rawRequest),Q=lZ(X),G=$.cookies.get(Q);if(G!==void 0&&G!==null)$.ctx().setCookie(Q,"",{httpOnly:!0,sameSite:"Lax",secure:X,maxAge:-1});if(!z)return this.oauthFailure($,"unknown_provider");let B=$.search.get("error");if(B)return this.oauthFailure($,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");let V=h4({provider:Z,cookieValue:G,returnedState:$.search.get("state")});if("reason"in V)return console.error(`Authentication error: OAuth callback refused (${V.reason})`),this.oauthFailure($,V.reason);if(!$.search.get("code"))return this.oauthFailure($,"missing_code");let K;try{K=await z.onCallback($,{state:V.payload.state,codeVerifier:V.payload.codeVerifier})}catch(N){if(N instanceof EW)return this.oauthFailure($,N.code);return console.error("Authentication error: OAuth provider callback failed",N),this.oauthFailure($,"provider_error")}let{name:F,username:D,providerId:U,emailVerified:O}=K??{},L=typeof K?.email==="string"?K.email:void 0,P=L?H6(L):null,H=U?await W.findUserBySocialAccount(Z,U):null,I="signin",E=!H&&!P&&!L&&!!U&&z.createUsersWithoutEmail===!0;if(!H&&E){if(z.createUsers===!1)return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");try{H=await this.createOAuthUserWithoutEmail({provider:Z,providerId:U,name:F,username:D,locale:M(c).detectLocale($)}),I="signup"}catch(N){let v=await W.findUserBySocialAccount(Z,U);if(!v)throw N;H=v}}if(!H){if(!P)return console.error("Authentication error: No usable email returned from OAuth provider callback"),this.oauthFailure($,L?"invalid_email":U?"missing_email":"no_identity");if(O===!1)return console.error("Authentication error: OAuth provider returned an unverified email"),this.oauthFailure($,"email_not_verified");let N=M(c).detectLocale($);try{let v=await this.linkOAuthAccount({provider:Z,providerId:U,email:P,rawEmail:L,name:F,username:D,locale:N,linkExisting:z.linkByEmail!==!1,createUser:z.createUsers!==!1});if(v==="account_exists")return console.error(`Authentication error: a ${Z} sign-in matched an existing user by email, and ${Z} does not link by email`),this.oauthFailure($,"account_exists");if(v==="signup_disabled")return console.error(`Authentication error: a ${Z} sign-in is not linked to a user, and ${Z} does not create users`),this.oauthFailure($,"signup_disabled");if(v)H=v.user,I=v.action}catch(v){let _=U?await W.findUserBySocialAccount(Z,U):null;if(!_)throw v;H=_}if(!H)return this.oauthFailure($,"account_conflict")}let S=await J.createOrUpdateSessionV2({email:H.email,id:H.id});if($.ctx().setCookie("access_token",S.token,M(b).accessTokenCookieOptions($,S.expiresAt)),I==="signup")await Y.onSignUp(H,"",$.search.toJSON());else await Y.onSignIn(H,$.search.toJSON());await r$(J.config,{session:S,user:H,isNewUser:I==="signup",method:"oauth",req:$});let R=QQ($)??Y.redirectPath,k=Y.oauthCompleteProfilePath?V1(Y.oauthCompleteProfilePath,""):"";if(k&&!H.email){let N=new URL(k,"http://gemi.invalid");N.searchParams.set(B1,R),R=`${N.pathname}${N.search}${N.hash}`}return{session:S,redirectTo:R}}async createOAuthUserWithoutEmail($){let{userProvider:Z,config:J}=M(b);return await Z.transaction(async()=>{let W=await Z.createUser({email:null,name:$.name??$.username??"",locale:$.locale});return await Z.createSocialAccount({provider:$.provider,providerId:$.providerId,userId:W.id,username:$.username,expiresAt:new Date,accessToken:"",refreshToken:""}),await J.onUserCreated(W,{method:"oauth",input:{}}),W})}oauthFailure($,Z){let J=QQ($),W=M(b).config.oauthFailurePath;if(W){let Y=V1(W,"");if(Y){let j=new URL(Y,"http://gemi.invalid");if(j.searchParams.set("error",Z),J)j.searchParams.set(B1,J);S1.external(`${j.pathname}${j.search}${j.hash}`)}else console.error(`auth.oauthFailurePath must be a same-origin path, got ${JSON.stringify(W)}`)}return{session:null,error:Z,redirectTo:J}}async linkOAuthAccount($){let{provider:Z,providerId:J,email:W,rawEmail:Y,name:j,username:z,locale:X}=$,{userProvider:Q,config:G}=M(b),B=(D)=>({provider:Z,userId:D,email:W,username:z,providerId:J,expiresAt:new Date,accessToken:"",refreshToken:""}),V=await Q.findUserByEmailAddress(W,!1),K=Y?.trim();if(!V&&K&&K!==W)V=await Q.findUserByEmailAddress(K,!1);if(V){if($.linkExisting===!1)return"account_exists";if(!J)return{user:V,action:"signin"};let D=await Q.findSocialAccounts(V.id,Z);if(D.some((O)=>O.providerId===J))return{user:V,action:"signin"};if(D.some((O)=>O.providerId))return console.error(`Authentication error: user ${V.id} is already linked to a different ${Z} account`),null;let U=D[0];if(U){if(!await Q.claimSocialAccount(U,J))throw Error(`${Z} account link changed concurrently`)}else await Q.createSocialAccount(B(V.id));return{user:V,action:"signin"}}if($.createUser===!1)return"signup_disabled";return{user:await Q.transaction(async()=>{let D=await Q.createUser({email:W,name:j,locale:X,emailVerifiedAt:new Date});if(J)await Q.createSocialAccount(B(D.id));return await G.onUserCreated(D,{method:"oauth",input:{}}),D}),action:"signup"}}async createMagicLinkToken($=new C){c1("magicLink");let Z=await $.input(),J=K3(Z.get("email")),W=M(b),{uniformMagicLinkResponse:Y,requestLimit:j}=W.config.emailCode;if(await LZ("request",J,$,j),!J)return{email:null};let{user:z,pin:X,token:Q}=await W.createMagicLinkToken(J);if(z)return await W.config.onMagicLinkCreated(z,{email:J,pin:X,token:Q}),{email:J};return{email:Y?J:null}}async requestEmailCode($=new C){let Z=M(b),J=Z.config.emailCode;if(!J.enabled)throw new z0("Not found",{status:404});let W=await $.input(),Y=H6(W.get("email"));if(await LZ("request",Y,$,J.requestLimit),!Y)throw new d({email:["Invalid email"]});let j=await Z.userProvider.findUserByEmailAddress(Y,!1);if(j||J.createUser){let{pin:z,token:X}=await Z.issueOneTimeCode(Y,J.length);await J.send({email:Y,code:z,token:X,isNewUser:!j,req:$})}return{ok:!0}}async verifyEmailCode($=new C){let Z=M(b),{userProvider:J,config:W}=Z;if(!W.emailCode.enabled)throw new z0("Not found",{status:404});let Y=await $.input(),{email:j,code:z,name:X}=Y.toJSON(),Q=H6(j),G=zQ(z);if(await LZ("verify",Q,$,W.emailCode.verifyLimit),!Q||!G)throw new d({code:["invalid_code"]});let B=await Z.verifyOneTimeCode(Q,G,{claim:!1});if(B.status==="too_many_attempts")throw new d({code:["too_many_attempts"]});if(B.status!=="ok")throw new d({code:["invalid_code"]});let V=B.row,K=await J.findUserByEmailAddress(Q,!1),F=!1;if(K){if(!await Z.claimOneTimeCode(Q,V.id))throw new d({code:["invalid_code"]});await J.verifyUser(Q)}else if(W.emailCode.createUser){let U=M(c).detectLocale($);try{K=await J.transaction(async()=>{if(!await Z.claimOneTimeCode(Q,V.id))throw new wW;let O=await J.createUser({email:Q,name:typeof X==="string"?X.trim():"",emailVerifiedAt:new Date,locale:U});return await W.onUserCreated(O,{method:"email-code",input:XQ(Y.toJSON())}),O}),F=!0}catch(O){if(O instanceof wW)throw new d({code:["invalid_code"]});throw O}}else throw await Z.claimOneTimeCode(Q,V.id),new d({code:["invalid_code"]});let D=await Z.createOrUpdateSessionV2({email:Q,id:K.id});return $.ctx().setCookie("access_token",D.token,M(b).accessTokenCookieOptions($,D.expiresAt)),await W.onSignIn(D,$.search.toJSON()),await r$(Z.config,{session:D,isNewUser:F,method:"email-code",req:$}),{session:D,isNewUser:F}}}function LD($){try{let Z=$?.id;if(Z===void 0||Z===null)return;let J=M();if(typeof J?.bound!=="function"||!J.bound(c0))return;J.make(c0).revoke({user:{id:Z}})}catch(Z){console.error("[gemi] Revoking the signed-out user's sockets failed:",Z)}}var VQ="gemi_oauth_connection";class c4 extends G3{async connect($=new C){let Z=String($.params.provider??""),W=M(l3).providers[Z],Y=await q0.user(),j=V1($.search.get(B1),"");if(!W)return this.finish(j,Z,"unknown_provider");let z=BZ($.rawRequest),{state:X,codeChallenge:Q,cookieValue:G}=m4(FQ(Z),Date.now(),{subject:String(Y.id),...j?{returnTo:j}:{}});return $.ctx().setCookie(lZ(z,VQ),G,{httpOnly:!0,sameSite:"Lax",secure:z,maxAge:u3}),S1.external(W.authorizationUrl({state:X,codeChallenge:Q,redirectUri:UQ($,Z,W.config.redirectUri)})),{destination:"/"}}async callback($=new C){let Z=String($.params.provider??""),J=M(l3),W=await q0.user(),Y=BZ($.rawRequest),j=lZ(Y,VQ),z=$.cookies.get(j);if(z!==void 0&&z!==null)$.ctx().setCookie(j,"",{httpOnly:!0,sameSite:"Lax",secure:Y,maxAge:-1});let X=h4({provider:FQ(Z),cookieValue:z,returnedState:$.search.get("state")}),Q="payload"in X?X.payload.returnTo??"":"",G=J.providers[Z];if(!G)return this.finish(Q,Z,"unknown_provider");let B=$.search.get("error");if(B)return this.finish(Q,Z,/^[a-z0-9_]{1,64}$/.test(B)?B:"provider_error");if("reason"in X)return console.error(`OAuth connection refused (${X.reason})`),this.finish(Q,Z,X.reason);if(X.payload.subject!==String(W.id))return this.finish(Q,Z,"user_mismatch");let V=$.search.get("code");if(!V)return this.finish(Q,Z,"missing_code");try{let K=await G.exchangeCode({code:V,codeVerifier:X.payload.codeVerifier,redirectUri:UQ($,Z,G.config.redirectUri)}),F=await J.save(W,Z,K);await M(b).config.onConnected({user:W,provider:Z,connection:F,profile:K.profile??null,req:$})}catch(K){if(K instanceof DQ)return console.error(`OAuth connection to ${Z} failed: ${K.message}`),this.finish(Q,Z,K.providerError??K.code);throw K}return this.finish(Q,Z)}finish($,Z,J){let W=$||V1(M(b).config.redirectPath,"/"),Y=new URL(W,"http://gemi.invalid");if(Y.searchParams.set("connection",Z),J)Y.searchParams.set("connection_error",J);throw S1.external(`${Y.pathname}${Y.search}${Y.hash}`),Error("unreachable: Redirect.external throws")}}function FQ($){return`connection:${$}`}function UQ($,Z,J){if(J)return J;return`${t$()??new URL($.rawRequest.url).origin}/auth/connections/${encodeURIComponent(Z)}/callback`}function OQ($){return $.magicLink!==!1||$.emailCode?.enabled===!0}function LQ($){return Object.keys($.oauthProviders??{}).length>0}function MQ($={}){let Z=[];if(OQ($))Z.push({view:"auth/MagicLinkSignIn",requiredBy:$.emailCode?.enabled===!0&&$.magicLink===!1?"auth.emailCode.enabled":`auth.magicLink${$.magicLink===void 0?" (on by default; set `magicLink: false` to turn it off)":""}`});if(LQ($)){let W=`auth.oauthProviders (${Object.keys($.oauthProviders??{}).join(", ")})`;Z.push({view:"_Redirect",requiredBy:W},{view:"auth/OauthCallback",requiredBy:W})}return Z}class HQ extends E1{middlewares=["cache:private"];routes={"/:provider":this.redirect([c4,"connect"]).middleware(["auth"]),"/:provider/callback":this.redirect([c4,"callback"]).middleware([K6,"auth"])}}function PQ($={}){let Z=OQ($),J=LQ($);class W extends E1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[$0,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[$0,"oauthCallback"])}}return class extends E1{middlewares=["cache:private"];routes={...Z?{"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[$0,"signInWithMagicLink"])}:{},...J?{"/oauth":W}:{},"/connections":HQ}}}class yW extends C0{middlewares=["cache:private"];routes={"/sign-in":this.post($0,"signIn"),"/sign-in-v2":this.post($0,"signInV2"),"/sign-up":this.post($0,"signUp"),"/sign-out":this.post($0,"signOut"),"/forgot-password":this.post($0,"forgotPassword"),"/reset-password":this.post($0,"resetPassword"),"/change-password":this.post($0,"changePassword"),"/verify-email":this.post($0,"verifyEmail"),"/me":this.get($0,"me").middleware(["auth"]),"/magic-link":this.post($0,"createMagicLinkToken"),"/sign-in-with-pin":this.post($0,"signInWithPin"),"/sign-in-with-pin-v2":this.post($0,"signInWithPinV2"),"/email-code":this.post($0,"requestEmailCode"),"/email-code/verify":this.post($0,"verifyEmailCode")}}class vW extends C0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new C().params.locale;return await M(c).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new C,Z=`/${$.params.scope??""}`,J=$.params.locale,W=M(c),Y=J??W.detectLocale($),j=W.getPageTranslations(Y,Z);return $.ctx().setCookie("i18n-locale",Y,{expires:new Date(Date.now()+31536000000)}),{[Y]:j}})}}class gW{}class mW extends gW{async resize($,Z){let{height:J,width:W,quality:Y,fit:j}=Z;return await(await d4("The Sharp image optimization driver"))($).resize(W>0?W:void 0,J>0?J:void 0,{fit:j}).webp({quality:Y>0?Y:80,force:!0}).toBuffer()}}function RN($){return $}function TQ(){return{driver:new mW,allowedHosts:[],maxSize:10485760,timeout:1e4}}class F0 extends Error{status;constructor($,Z,J){super(Z,J);this.status=$;this.name="ImageSourceError"}}var MD=new Set([301,302,303,307,308]),HD="/api/__gemi__/services/image/";async function _Q($,Z){let J=Z.maxRedirects??5,W=AbortSignal.timeout(Z.timeout),Y=Z.ownOrigins[0]??Z.localOrigin,j=NQ($,Y);try{for(let z=0;;z++){let X=await PD(j,Z,W),Q=X.headers.get("location");if(MD.has(X.status)&&Q){if(await X.body?.cancel().catch(()=>{}),z>=J)throw new F0(502,"The image redirects too many times");j=NQ(Q,j.href);continue}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new F0(404,"Image not found");if(!X.headers.get("content-type")?.split(";")[0].trim().toLowerCase()?.startsWith("image/"))throw await X.body?.cancel().catch(()=>{}),new F0(415,"The source is not an image");return{bytes:Buffer.from(await X.arrayBuffer()),cacheControl:X.headers.get("cache-control")}}}catch(z){if(z instanceof TypeError&&z.message.startsWith("safeFetch:"))throw z;throw ND(z,W)}}function NQ($,Z){let J;try{J=new URL($,Z)}catch{throw new F0(400,"The url parameter is not a URL")}if(J.protocol!=="http:"&&J.protocol!=="https:")throw new F0(400,"Only http(s) images can be resized");return J}async function PD($,Z,J){let W={method:"GET",redirect:"manual",signal:J,timeout:Z.timeout,maxSize:Z.maxSize,headers:{accept:"image/*"}},Y=$;if(Z.ownOrigins.includes($.origin)){if($.pathname.startsWith(HD))throw new F0(403,"This image source is not allowed");if(TD($.pathname))throw new F0(403,"This image source is not allowed");let j=new URL(Z.localOrigin).origin,z=new URL(`${$.pathname}${$.search}`,j);if(z.origin===j)return b1(z,{...W,allowPrivate:!0,ports:"any"});Y=z}if(Z.allowedHosts.length===0)throw new F0(403,"This image source is not allowed");return b1(Y,{...Z.external,...W,allow:Z.allowedHosts})}function TD($){let Z=$;for(let J=0;J<5;J++){if(/^[/\\][/\\]/.test(Z))return!0;let W;try{W=decodeURIComponent(Z)}catch{return!0}if(W===Z)return!1;Z=W}return!0}function ND($,Z){if($ instanceof F0)return $;if(Z.aborted)return new F0(504,"The image took too long to load",{cause:$});if($ instanceof V6)switch($.code){case"blocked-host":case"blocked-address":case"invalid-url":return new F0(403,"This image source is not allowed",{cause:$});case"too-large":return new F0(413,"The image is too large",{cause:$});case"timeout":return new F0(504,"The image took too long to load",{cause:$})}return new F0(502,"The image could not be loaded",{cause:$})}class hW extends C0{routes={"/resize":this.file(async()=>{let $=new C,Z=new URL($.rawRequest.url),J=Z.searchParams.get("url"),W=Number(Z.searchParams.get("w")),Y=Number(Z.searchParams.get("h")),j=Z.searchParams.get("fit")??"cover",z=Number(Z.searchParams.get("q"));if(!J)return IQ(400,"url query parameter is required");let X=M(xQ),Q=[Z.origin,`${Z.protocol==="https:"?"http":"https"}://${Z.host}`],G=t$();if(G&&URL.canParse(G))Q.push(new URL(G).origin);let B;try{B=await _Q(J,{ownOrigins:Q,localOrigin:`http://localhost:${process.env.PORT||5173}`,allowedHosts:X.allowedHosts,maxSize:X.maxSize,timeout:X.timeout})}catch(F){if(F instanceof F0)return IQ(F.status,F.message);throw F}let V=await X.resize(B.bytes,{height:Y,width:W,fit:j,quality:z}),K=new Headers({"Content-Type":"image/webp","Content-Length":`${V.byteLength}`});if(B.cacheControl)K.set("Cache-Control",B.cacheControl);return new Response(new Uint8Array(V),{headers:K})})}}function IQ($,Z){return Response.json({error:Z},{status:$})}class xQ{static token="image";driver;allowedHosts;maxSize;timeout;constructor($={}){let Z=TQ();this.driver=$.driver??Z.driver,this.allowedHosts=$.allowedHosts??Z.allowedHosts,this.maxSize=$.maxSize??Z.maxSize,this.timeout=$.timeout??Z.timeout}resize($,Z){return this.driver.resize($,Z)}}class pW extends C0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(M(CQ).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function iN($){return $}function AQ(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function SQ(){return{partialRendering:!0,localeRouting:"prefix",theme:{},publicFiles:!0,assetRoutes:!1,onNotFound:()=>{},onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function _D($){return"run"in $}function ID($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function xD($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function CD($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function AD($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function EQ($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function SD($){let Z=$.replace(/(?<!:\w*)\([\w-]+\)/g,"");if(Z===$)return $;let J=`/${Z}`.replace(/\/{2,}/g,"/");return J.length>1?J.replace(/\/$/,""):J}function cW($,Z="",J=[]){let W={};function Y(j,z,X,Q,G){let B=j==="/"?"":j,V=Z==="/"?"":Z,K=SD((`${V}${B}`===""?"/":`${V}${B}`).replaceAll("//","/"));if(!W[K])W[K]={};W[K][z.toUpperCase()]={exec:X,middleware:[...J,...Q],...G?{source:G}:{}},W[K].OPTIONS={exec:()=>{let D=new C().ctx().headers;return new Response(null,{headers:D,status:204})},middleware:[]}}for(let[j,z]of Object.entries($)){if(AD(z)){let X=z;for(let Q of["GET","POST","PUT","DELETE"])Y(j,Q,X.run.bind(X),X.middlewares);continue}if(_D(z)){let X=z,Q=X.method,G=X.middlewares,B=X.run.bind(X);if(Y(j,Q,B,G,X.source),EQ(z))Y(j,"HEAD",B,G,X.source)}if(ID(z))for(let[X,Q]of Object.entries(z)){let G=Q,B=G.middlewares,V=G.run.bind(G);if(Y(j,X,V,B,G.source),X==="get"&&EQ(G))Y(j,"HEAD",V,B,G.source)}if(CD(z)){let X=new z,Q=cW(X.routes,`${Z}${j}`,[...J,...X.middlewares]);for(let[G,B]of Object.entries(Q)){let V=G.replaceAll("//","/");W[V]={...W[V],...B}}}if(xD(z)){let{first:X,second:Q}=z;for(let[G,B]of Object.entries(X)){let V=B.middlewares,K=B.run.bind(B),[F,...D]=j.split("/").reverse();if(!F.startsWith(":"))throw Error("Resource route must end with a dynamic segment");Y(D.reverse().join("/"),G,K,V,B.source)}for(let[G,B]of Object.entries(Q)){let V=B.middlewares,K=B.run.bind(B);Y(j,G,K,V,B.source)}}}return Object.fromEntries(Object.entries(W).sort(([j],[z])=>{let X=j.split("/").length+j.split(":").length,Q=z.split("/").length+z.split(":").length;return X-Q}))}function u4($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function dW($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function uW($){let Z=u4($);return Z.length>1?Z.replace(/\/$/,""):Z}function bQ($,Z){return Z.map((J)=>({...J,path:uW(dW($,J.path))}))}function l4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W;if("children"in Y){let j=new Y.children,z=l4(j.routes);for(let[X,{exec:Q,middleware:G,segments:B,features:V,static:K}]of Object.entries(z)){let F=dW(J,X),D=(U)=>Y.run.call(Y,U,J);Z[u4(F)]={exec:[D,...Q],middleware:[...Y.middlewares,...G],features:[...Y.featureGates,...V],viewPath:Y.viewPath,segments:[{path:uW(J),viewPath:Y.viewPath,...Y.alwaysRuns?{alwaysRun:!0}:{}},...bQ(J,B)],...K?{static:K}:{}}}}else{let j=(z)=>Y.run.call(Y,z,J);Z[u4(J)]={exec:[j],middleware:Y.middlewares,features:Y.featureGates,viewPath:Y.viewPath,segments:[{path:uW(J),viewPath:Y.viewPath}],..."staticOptions"in Y&&Y.staticOptions?{static:Y.staticOptions}:{}}}}else{let Y=new W,j=l4(Y.routes);for(let[z,{exec:X,middleware:Q,viewPath:G,segments:B,features:V,static:K}]of Object.entries(j)){let F=dW(J,z);Z[u4(F)]={exec:X,middleware:[...Y.middlewares,...Q],features:[...Y.featureGates,...V],viewPath:G,segments:bQ(J,B),...K?{static:K}:{}}}}return Object.fromEntries(Object.entries(Z).sort(([J],[W])=>{let Y=J.split("/").length+J.split(":").length,j=W.split("/").length+W.split(":").length;return Y-j}))}var lW="theme";function RQ($){return $==="light"||$==="dark"||$==="system"}function fQ($){return`!function(o){try{var e=null,d=document.documentElement,c=d.classList,k=document.cookie.split(';'),i,j,v;
|
|
14
14
|
for(i=0;i<k.length;i++){j=k[i].indexOf('=');if(j>0&&k[i].slice(0,j).trim()===o.cookie){v=decodeURIComponent(k[i].slice(j+1).trim());break}}
|
|
15
15
|
if(v!=='light'&&v!=='dark'&&v!=='system'){try{v=localStorage.getItem('theme')}catch(x){}}
|
|
16
16
|
if(v==='light'||v==='dark'||v==='system')e=v;else e=o.default;
|
|
17
17
|
if(!e)return;
|
|
18
18
|
if(e==='system')e=window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
|
|
19
|
-
c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}var ED=Object.defineProperty,x=($,Z)=>ED($,"name",{value:Z,configurable:!0}),nZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};x(nZ,"Part");var bD=/[$_\p{ID_Start}]/u,RD=/[$_\u200C\u200D\p{ID_Continue}]/u,sW=".*";function fQ($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}x(fQ,"isASCII");function aW($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=x(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let Q=$.substr(X,1);if(X===W+1&&bD.test(Q)||X!==W+1&&RD.test(Q)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",Q=W+1,G=!1;if($[Q]==="?"){j(`Pattern cannot start with "?" at ${Q}`);continue}for(;Q<$.length;){if(!fQ($[Q],!1)){j(`Invalid character '${$[Q]}' at ${Q}.`),G=!0;break}if($[Q]==="\\"){X+=$[Q++]+$[Q++];continue}if($[Q]===")"){if(z--,z===0){Q++;break}}else if($[Q]==="("&&(z++,$[Q+1]!=="?")){j(`Capturing groups are not allowed at ${Q}`),G=!0;break}X+=$[Q++]}if(G)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=Q;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}x(aW,"lexer");function rW($,Z={}){let J=aW($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${d0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",Q=new Set,G=x((H)=>{if(z<J.length&&J[z].type===H)return J[z++].value},"tryConsume"),B=x(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),V=x((H)=>{let I=G(H);if(I!==void 0)return I;let{type:S,index:A}=J[z];throw TypeError(`Unexpected ${S} at ${A}, expected ${H}`)},"mustConsume"),K=x(()=>{let H="",I;for(;I=G("CHAR")??G("ESCAPED_CHAR");)H+=I;return H},"consumeText"),F=x((H)=>H,"DefaultEncodePart"),D=Z.encodePart||F,U="",O=x((H)=>{U+=H},"appendToPendingFixedValue"),L=x(()=>{U.length&&(Y.push(new nZ(3,"","",D(U),"",3)),U="")},"maybeAddPartFromPendingFixedValue"),P=x((H,I,S,A,b)=>{let k=3;switch(b){case"?":k=1;break;case"*":k=0;break;case"+":k=2;break}if(!I&&!S&&k===3){O(H);return}if(L(),!I&&!S){if(!H)return;Y.push(new nZ(3,"","",D(H),"",k));return}let N;S?S==="*"?N=sW:N=S:N=W;let v=2;N===W?(v=1,N=""):N===sW&&(v=0,N="");let _;if(I?_=I:S&&(_=j++),Q.has(_))throw TypeError(`Duplicate name '${_}'.`);Q.add(_),Y.push(new nZ(v,_,D(H),N,D(A),k))},"addPart");for(;z<J.length;){let H=G("CHAR"),I=G("NAME"),S=G("REGEX");if(!I&&!S&&(S=G("ASTERISK")),I||S){let b=H??"";Z.prefixes.indexOf(b)===-1&&(O(b),b=""),L();let k=B();P(b,I,S,"",k);continue}let A=H??G("ESCAPED_CHAR");if(A){O(A);continue}if(G("OPEN")){let b=K(),k=G("NAME"),N=G("REGEX");!k&&!N&&(N=G("ASTERISK"));let v=K();V("CLOSE");let _=B();P(b,k,N,v,_);continue}L(),V("END")}return Y}x(rW,"parse");function d0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(d0,"escapeString");function nW($){return $&&$.ignoreCase?"ui":"u"}x(nW,"flags");function kQ($,Z,J){return tW(rW($,J),Z,J)}x(kQ,"stringToRegexp");function e$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}x(e$,"modifierToString");function tW($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=d0(X.value):W+=`(?:${d0(X.value)})${e$(X.modifier)}`;continue}Z&&Z.push(X.name);let Q=`[^${d0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=Q:X.type===0&&(G=sW),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${G})${e$(X.modifier)}`:W+=`((?:${G})${e$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${d0(X.prefix)}(${G})${d0(X.suffix)})`,W+=e$(X.modifier);continue}W+=`(?:${d0(X.prefix)}`,W+=`((?:${G})(?:`,W+=d0(X.suffix),W+=d0(X.prefix),W+=`(?:${G}))*)${d0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${d0(J.endsWith)}]|$`,j=`[${d0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,nW(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,nW(J))}x(tW,"partsToRegexp");var _$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},fD={delimiter:".",prefixes:"",sensitive:!0,strict:!0},kD={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function wQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}x(wQ,"isAbsolutePathname");function eW($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}x(eW,"maybeStripPrefix");function qQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}x(qQ,"maybeStripSuffix");function $Y($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}x($Y,"treatAsIPv6Hostname");var yQ=["ftp","file","http","https","ws","wss"];function ZY($){if(!$)return!0;for(let Z of yQ)if($.test(Z))return!0;return!1}x(ZY,"isSpecialScheme");function vQ($,Z){if($=eW($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}x(vQ,"canonicalizeHash");function gQ($,Z){if($=eW($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}x(gQ,"canonicalizeSearch");function mQ($,Z){return Z||$===""?$:$Y($)?YY($):WY($)}x(mQ,"canonicalizeHostname");function hQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}x(hQ,"canonicalizePassword");function pQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}x(pQ,"canonicalizeUsername");function cQ($,Z,J){if(J||$==="")return $;if(Z&&!yQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}x(cQ,"canonicalizePathname");function dQ($,Z,J){return JY(Z)===$&&($=""),J||$===""?$:jY($)}x(dQ,"canonicalizePort");function uQ($,Z){return $=qQ($,":"),Z||$===""?$:i4($)}x(uQ,"canonicalizeProtocol");function JY($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}x(JY,"defaultPortForProtocol");function i4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}x(i4,"protocolEncodeCallback");function lQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}x(lQ,"usernameEncodeCallback");function iQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}x(iQ,"passwordEncodeCallback");function WY($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}x(WY,"hostnameEncodeCallback");function YY($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}x(YY,"ipv6HostnameEncodeCallback");function jY($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}x(jY,"portEncodeCallback");function sQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}x(sQ,"standardURLPathnameEncodeCallback");function nQ($){return $===""?$:new URL(`data:${$}`).pathname}x(nQ,"pathURLPathnameEncodeCallback");function oQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}x(oQ,"searchEncodeCallback");function aQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}x(aQ,"hashEncodeCallback");var rQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#G=0;#X=0;#F=0;#U=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=aW(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#H(),this.#K()?this.#J(9,1):this.#B()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#V(5);continue}this.#J(10,0);break}if(this.#F>0)if(this.#C())this.#F-=1;else continue;if(this.#x()){this.#F+=1;continue}switch(this.#X){case 0:this.#P()&&this.#V(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#N()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#L()?this.#V(3):(this.#M()||this.#B()||this.#K())&&this.#V(5);break;case 3:this.#_()?this.#J(4,1):this.#L()&&this.#J(5,1);break;case 4:this.#L()&&this.#J(5,1);break;case 5:this.#A()?this.#U+=1:this.#S()&&(this.#U-=1),this.#I()&&!this.#U?this.#J(6,1):this.#M()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#M()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 8:this.#K()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#Q();break;case 2:break;case 3:this.#Z.username=this.#Q();break;case 4:this.#Z.password=this.#Q();break;case 5:this.#Z.hostname=this.#Q();break;case 6:this.#Z.port=this.#Q();break;case 7:this.#Z.pathname=this.#Q();break;case 8:this.#Z.search=this.#Q();break;case 9:this.#Z.hash=this.#Q();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#T($,Z)}#T($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#H(){this.#$=this.#G,this.#Y=0}#V($){this.#H(),this.#X=$}#O($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#O($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#N(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#L(){return this.#z(this.#$,"@")}#_(){return this.#z(this.#$,":")}#I(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#B(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#O(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#Q(){let $=this.#W[this.#$],Z=this.#O(this.#G).index;return this.#j.substring(Z,$.index)}#E(){let $={};Object.assign($,_$),$.encodePart=i4;let Z=kQ(this.#Q(),void 0,$);this.#D=ZY(Z)}};x(rQ,"Parser");var iW=["protocol","username","password","hostname","port","pathname","search","hash"],N$="*";function oW($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}x(oW,"extractValues");function T1($,Z){return Z?sZ($):$}x(T1,"processBaseURLString");function iZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=T1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=T1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=T1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=T1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=T1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=T1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=T1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=T1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=uQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=pQ(Z.username,J)),typeof Z.password=="string"&&($.password=hQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=mQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=dQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!wQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=T1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=cQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=gQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=vQ(Z.hash,J)),$}x(iZ,"applyInit");function sZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}x(sZ,"escapePatternString");function tQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(tQ,"escapeRegexpString");function eQ($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${tQ(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=sZ(X.value);continue}j+=`{${sZ(X.value)}}${e$(X.modifier)}`;continue}let Q=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),B=z>0?$[z-1]:null,V=z<$.length-1?$[z+1]:null;if(!G&&Q&&X.type===1&&X.modifier===3&&V&&!V.prefix.length&&!V.suffix.length)if(V.type===3){let K=V.value.length>0?V.value[0]:"";G=Y.test(K)}else G=!V.hasCustomName();if(!G&&!X.prefix.length&&B&&B.type===3){let K=B.value[B.value.length-1];G=Z.prefixes.includes(K)}G&&(j+="{"),j+=sZ(X.prefix),Q&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?Q||(j+=`(${W})`):X.type===0&&(!Q&&(!B||B.type===3||B.modifier!==3||G||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&Q&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=sZ(X.suffix),G&&(j+="}"),X.modifier!==3&&(j+=e$(X.modifier))}return j}x(eQ,"partsToPattern");var zY=class{#j;#W={};#Z={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new rQ($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},j={pathname:N$,protocol:N$,username:N$,password:N$,hostname:N$,port:N$,search:N$,hash:N$};this.#j=iZ(j,$,!0),JY(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of iW){if(!(z in this.#j))continue;let X={},Q=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,_$),X.encodePart=i4;break;case"username":Object.assign(X,_$),X.encodePart=lQ;break;case"password":Object.assign(X,_$),X.encodePart=iQ;break;case"hostname":Object.assign(X,fD),$Y(Q)?X.encodePart=YY:X.encodePart=WY;break;case"port":Object.assign(X,_$),X.encodePart=jY;break;case"pathname":ZY(this.#W.protocol)?(Object.assign(X,kD,Y),X.encodePart=sQ):(Object.assign(X,_$,Y),X.encodePart=nQ);break;case"search":Object.assign(X,_$,Y),X.encodePart=oQ;break;case"hash":Object.assign(X,_$,Y),X.encodePart=aQ;break}try{this.#Y[z]=rW(Q,X),this.#W[z]=tW(this.#Y[z],this.#Z[z],X),this.#$[z]=eQ(this.#Y[z],X),this.#G=this.#G||this.#Y[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=iZ(J,$,!1):J=iZ(J,oW($,Z),!1)}catch{return!1}let W;for(W of iW)if(!this.#W[W].exec(J[W]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=iZ(J,$,!1):J=iZ(J,oW($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of iW){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,Q]of this.#Z[Y].entries())if(typeof Q=="string"||typeof Q=="number"){let G=j[X+1];z[Q]=G}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=x((X,Q)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<Q[G])return-1;if(X[G]===Q[G])continue;return 1}return 0},"comparePart"),Y=new nZ(3,"","","","",3),j=new nZ(0,"","","","",3),z=x((X,Q)=>{let G=0;for(;G<Math.min(X.length,Q.length);++G){let B=W(X[G],Q[G]);if(B)return B}return X.length===Q.length?0:W(X[G]??Y,Q[G]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};x(zY,"URLPattern");function l3($,Z){for(let[J,W]of Object.entries($)){let Y=new zY({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var $Z={startIndex:0,carriedViews:[]};function $G($,Z){let J=D0($.path,Z);return J.includes("*")?null:J}function wD($,Z){if(!$)return $Z;if($.search!==Z.search)return $Z;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=$G(Y,$.params),X=$G(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return $Z;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function qD($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function ZG($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return $Z;let z;try{z=new URL(W,Y)}catch{return $Z}if(z.origin!==Y)return $Z;let X=l3(Z,qD(z.pathname,J));if(!X)return $Z;return wD({segments:X.route.segments,params:X.params,search:z.search},j)}var XY="x-gemi-from";import{createElement as c1,Fragment as NG}from"react";function yD($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function s4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=s4(j.routes);for(let[X,Q]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,B=X==="/"&&J!=="/"?J:G;Z[B]=[Y,...Q]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=s4(Y.routes);for(let[z,X]of Object.entries(j)){let Q=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:Q;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[yD(J),W]))}function n4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)n4(Y[1],j)}function o4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=o4(j.routes);n4(Z,[Y,z])}else n4(Z,[Y,[]])}else{let Y=new W,j=o4(Y.routes);for(let z of j)n4(Z,z)}return Z}function QY($){let Z=[];for(let[J,W]of $)Z.push(J,...QY(W).flat());return Array.from(new Set(Z))}function JG($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class I$ extends m{static getFacadeAccessor(){return c}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=T.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(T.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??I$.locale(),$.timeZone??I$.timeZone())}static setLocale($=I$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=T.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class GY{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function WG($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var vD=50;class oZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let W=Z.params??{},Y=new URLSearchParams(WG(Z.search??{}));Y.delete("json"),Y.sort();let j=D0($,W),z=Y.toString(),X=this.keyFor(j,z),Q=this.entries.get(X);if(Q)return Q;let G;if(J==="render"&&this.renderStartedAt!==null){let F=Math.round(performance.now()-this.renderStartedAt);if(F>vD)G=F}let B,V=new Promise((F)=>{B=F}),K={path:j,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:V,source:J,startedAt:this.elapsed()};return this.entries.set(X,K),this.fetcher($,W,Y).then((F)=>{K.status="resolved",K.data=F},(F)=>{K.status="rejected",K.error=F}).then(()=>{if(K.settledAt=this.elapsed(),this.maybeLogLateDiscovery(K),K.status==="rejected"&&this.failListener)this.failListener(K);if(this.settleListener)this.settleListener(K);else this.settledBacklog.push(K);B()}),K}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class p1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=Y;this.name="QueryError"}}function aZ(){let $=JSON.stringify({error:J$("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function KY(){return{status:403,error:{message:"Forbidden"}}}function i3($){let Z=rZ.getStore(),J=T.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[D0(W,Y),j.toString()].filter((V)=>V.length>0).join("?"),Q=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),G=a4($);if(G)tZ(Q,G);let B=new C(Q,Y);return rZ.run(Z,()=>T.run(B,async()=>{let V=J?.locale;if(V&&M(c).isLocaleAware)T.getStore().setLocale(V);try{let K=M(X1).dispatchers(G).api,F=await K.runRouteMiddleware(W,B)??await K.getRouteData(W);if(r1(F)){if(!F.ok)throw new p1(D0(W,Y),j.toString(),F.status,F.body);return F.body}if(F instanceof Response){let D=await F.json().catch(()=>null);if(!F.ok)throw new p1(D0(W,Y),j.toString(),F.status,D);return D}return F}catch(K){if(K instanceof p1)throw K;let F=new p1(D0(W,Y),j.toString(),500,{message:K instanceof Error?K.message:String(K)});throw F.cause=K,F}}))}}var gD=new Set(["script","style","template","title"]),mD=/\shidden([\s=/]|$)/i,hD=/"[^"]*"|'[^']*'/g;function pD($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let V=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=V;else Z+=V}if(j===-1)break;if($.startsWith("<!--",j)){let V=$.indexOf("-->",j+4);Y=V===-1?$.length:V+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let Q=$.slice(j+1,X);Y=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(Q)?.[1]?.toLowerCase();if(!G)continue;let B=Q.startsWith("/");if(!B&&gD.has(G)&&!Q.endsWith("/")){let V=$.indexOf(`</${G}`,Y);Y=V===-1?$.length:V;continue}if(G!=="div")continue;if(B){if(W>0)W-=1}else if(W>0)W+=1;else if(mD.test(Q.replace(hD,'""')))W=1}return{shellChars:Z,deferredChars:J}}var cD=1000,dD=64;function uD($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function lD($,Z){if(Z.deferredChars<cD)return null;if(Z.shellChars>=dD)return null;return`[gemi] GET ${$} streams ${uD(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function YG($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=lD(J,W);if(!Y)return;Z.add(J),$(Y)}}}function jG(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),pD(Z)}}}function zG($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,Q=(B)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}W?.({aborted:B})};j=Q,z.enqueue(Y.encode(`${JSON.stringify($)}
|
|
19
|
+
c.remove(e==='dark'?'light':'dark');c.add(e);d.style.colorScheme=e}catch(x){}}(${$})`}var ED=Object.defineProperty,x=($,Z)=>ED($,"name",{value:Z,configurable:!0}),nZ=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,J,W,Y,j){this.type=$,this.name=Z,this.prefix=J,this.value=W,this.suffix=Y,this.modifier=j}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};x(nZ,"Part");var bD=/[$_\p{ID_Start}]/u,RD=/[$_\u200C\u200D\p{ID_Continue}]/u,sW=".*";function kQ($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}x(kQ,"isASCII");function aW($,Z=!1){let J=[],W=0;for(;W<$.length;){let Y=$[W],j=x(function(z){if(!Z)throw TypeError(z);J.push({type:"INVALID_CHAR",index:W,value:$[W++]})},"ErrorOrInvalid");if(Y==="*"){J.push({type:"ASTERISK",index:W,value:$[W++]});continue}if(Y==="+"||Y==="?"){J.push({type:"OTHER_MODIFIER",index:W,value:$[W++]});continue}if(Y==="\\"){J.push({type:"ESCAPED_CHAR",index:W++,value:$[W++]});continue}if(Y==="{"){J.push({type:"OPEN",index:W,value:$[W++]});continue}if(Y==="}"){J.push({type:"CLOSE",index:W,value:$[W++]});continue}if(Y===":"){let z="",X=W+1;for(;X<$.length;){let Q=$.substr(X,1);if(X===W+1&&bD.test(Q)||X!==W+1&&RD.test(Q)){z+=$[X++];continue}break}if(!z){j(`Missing parameter name at ${W}`);continue}J.push({type:"NAME",index:W,value:z}),W=X;continue}if(Y==="("){let z=1,X="",Q=W+1,G=!1;if($[Q]==="?"){j(`Pattern cannot start with "?" at ${Q}`);continue}for(;Q<$.length;){if(!kQ($[Q],!1)){j(`Invalid character '${$[Q]}' at ${Q}.`),G=!0;break}if($[Q]==="\\"){X+=$[Q++]+$[Q++];continue}if($[Q]===")"){if(z--,z===0){Q++;break}}else if($[Q]==="("&&(z++,$[Q+1]!=="?")){j(`Capturing groups are not allowed at ${Q}`),G=!0;break}X+=$[Q++]}if(G)continue;if(z){j(`Unbalanced pattern at ${W}`);continue}if(!X){j(`Missing pattern at ${W}`);continue}J.push({type:"REGEX",index:W,value:X}),W=Q;continue}J.push({type:"CHAR",index:W,value:$[W++]})}return J.push({type:"END",index:W,value:""}),J}x(aW,"lexer");function rW($,Z={}){let J=aW($);Z.delimiter??="/#?",Z.prefixes??="./";let W=`[^${d0(Z.delimiter)}]+?`,Y=[],j=0,z=0,X="",Q=new Set,G=x((H)=>{if(z<J.length&&J[z].type===H)return J[z++].value},"tryConsume"),B=x(()=>G("OTHER_MODIFIER")??G("ASTERISK"),"tryConsumeModifier"),V=x((H)=>{let I=G(H);if(I!==void 0)return I;let{type:E,index:S}=J[z];throw TypeError(`Unexpected ${E} at ${S}, expected ${H}`)},"mustConsume"),K=x(()=>{let H="",I;for(;I=G("CHAR")??G("ESCAPED_CHAR");)H+=I;return H},"consumeText"),F=x((H)=>H,"DefaultEncodePart"),D=Z.encodePart||F,U="",O=x((H)=>{U+=H},"appendToPendingFixedValue"),L=x(()=>{U.length&&(Y.push(new nZ(3,"","",D(U),"",3)),U="")},"maybeAddPartFromPendingFixedValue"),P=x((H,I,E,S,R)=>{let k=3;switch(R){case"?":k=1;break;case"*":k=0;break;case"+":k=2;break}if(!I&&!E&&k===3){O(H);return}if(L(),!I&&!E){if(!H)return;Y.push(new nZ(3,"","",D(H),"",k));return}let N;E?E==="*"?N=sW:N=E:N=W;let v=2;N===W?(v=1,N=""):N===sW&&(v=0,N="");let _;if(I?_=I:E&&(_=j++),Q.has(_))throw TypeError(`Duplicate name '${_}'.`);Q.add(_),Y.push(new nZ(v,_,D(H),N,D(S),k))},"addPart");for(;z<J.length;){let H=G("CHAR"),I=G("NAME"),E=G("REGEX");if(!I&&!E&&(E=G("ASTERISK")),I||E){let R=H??"";Z.prefixes.indexOf(R)===-1&&(O(R),R=""),L();let k=B();P(R,I,E,"",k);continue}let S=H??G("ESCAPED_CHAR");if(S){O(S);continue}if(G("OPEN")){let R=K(),k=G("NAME"),N=G("REGEX");!k&&!N&&(N=G("ASTERISK"));let v=K();V("CLOSE");let _=B();P(R,k,N,v,_);continue}L(),V("END")}return Y}x(rW,"parse");function d0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(d0,"escapeString");function nW($){return $&&$.ignoreCase?"ui":"u"}x(nW,"flags");function wQ($,Z,J){return tW(rW($,J),Z,J)}x(wQ,"stringToRegexp");function e$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}x(e$,"modifierToString");function tW($,Z,J={}){J.delimiter??="/#?",J.prefixes??="./",J.sensitive??=!1,J.strict??=!1,J.end??=!0,J.start??=!0,J.endsWith="";let W=J.start?"^":"";for(let X of $){if(X.type===3){X.modifier===3?W+=d0(X.value):W+=`(?:${d0(X.value)})${e$(X.modifier)}`;continue}Z&&Z.push(X.name);let Q=`[^${d0(J.delimiter)}]+?`,G=X.value;if(X.type===1?G=Q:X.type===0&&(G=sW),!X.prefix.length&&!X.suffix.length){X.modifier===3||X.modifier===1?W+=`(${G})${e$(X.modifier)}`:W+=`((?:${G})${e$(X.modifier)})`;continue}if(X.modifier===3||X.modifier===1){W+=`(?:${d0(X.prefix)}(${G})${d0(X.suffix)})`,W+=e$(X.modifier);continue}W+=`(?:${d0(X.prefix)}`,W+=`((?:${G})(?:`,W+=d0(X.suffix),W+=d0(X.prefix),W+=`(?:${G}))*)${d0(X.suffix)})`,X.modifier===0&&(W+="?")}let Y=`[${d0(J.endsWith)}]|$`,j=`[${d0(J.delimiter)}]`;if(J.end)return J.strict||(W+=`${j}?`),J.endsWith.length?W+=`(?=${Y})`:W+="$",new RegExp(W,nW(J));J.strict||(W+=`(?:${j}(?=${Y}))?`);let z=!1;if($.length){let X=$[$.length-1];X.type===3&&X.modifier===3&&(z=J.delimiter.indexOf(X)>-1)}return z||(W+=`(?=${j}|${Y})`),new RegExp(W,nW(J))}x(tW,"partsToRegexp");var _$={delimiter:"",prefixes:"",sensitive:!0,strict:!0},fD={delimiter:".",prefixes:"",sensitive:!0,strict:!0},kD={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function qQ($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}x(qQ,"isAbsolutePathname");function eW($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}x(eW,"maybeStripPrefix");function yQ($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}x(yQ,"maybeStripSuffix");function $Y($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}x($Y,"treatAsIPv6Hostname");var vQ=["ftp","file","http","https","ws","wss"];function ZY($){if(!$)return!0;for(let Z of vQ)if($.test(Z))return!0;return!1}x(ZY,"isSpecialScheme");function gQ($,Z){if($=eW($,"#"),Z||$==="")return $;let J=new URL("https://example.com");return J.hash=$,J.hash?J.hash.substring(1,J.hash.length):""}x(gQ,"canonicalizeHash");function mQ($,Z){if($=eW($,"?"),Z||$==="")return $;let J=new URL("https://example.com");return J.search=$,J.search?J.search.substring(1,J.search.length):""}x(mQ,"canonicalizeSearch");function hQ($,Z){return Z||$===""?$:$Y($)?YY($):WY($)}x(hQ,"canonicalizeHostname");function pQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.password=$,J.password}x(pQ,"canonicalizePassword");function cQ($,Z){if(Z||$==="")return $;let J=new URL("https://example.com");return J.username=$,J.username}x(cQ,"canonicalizeUsername");function dQ($,Z,J){if(J||$==="")return $;if(Z&&!vQ.includes(Z))return new URL(`${Z}:${$}`).pathname;let W=$[0]=="/";return $=new URL(W?$:"/-"+$,"https://example.com").pathname,W||($=$.substring(2,$.length)),$}x(dQ,"canonicalizePathname");function uQ($,Z,J){return JY(Z)===$&&($=""),J||$===""?$:jY($)}x(uQ,"canonicalizePort");function lQ($,Z){return $=yQ($,":"),Z||$===""?$:i4($)}x(lQ,"canonicalizeProtocol");function JY($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}x(JY,"defaultPortForProtocol");function i4($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}x(i4,"protocolEncodeCallback");function iQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}x(iQ,"usernameEncodeCallback");function sQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}x(sQ,"passwordEncodeCallback");function WY($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}x(WY,"hostnameEncodeCallback");function YY($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}x(YY,"ipv6HostnameEncodeCallback");function jY($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}x(jY,"portEncodeCallback");function nQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}x(nQ,"standardURLPathnameEncodeCallback");function oQ($){return $===""?$:new URL(`data:${$}`).pathname}x(oQ,"pathURLPathnameEncodeCallback");function aQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}x(aQ,"searchEncodeCallback");function rQ($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}x(rQ,"hashEncodeCallback");var tQ=class{#j;#W=[];#Z={};#$=0;#Y=1;#G=0;#X=0;#F=0;#U=0;#D=!1;constructor($){this.#j=$}get result(){return this.#Z}parse(){for(this.#W=aW(this.#j,!0);this.#$<this.#W.length;this.#$+=this.#Y){if(this.#Y=1,this.#W[this.#$].type==="END"){if(this.#X===0){this.#H(),this.#K()?this.#J(9,1):this.#B()?this.#J(8,1):this.#J(7,0);continue}else if(this.#X===2){this.#V(5);continue}this.#J(10,0);break}if(this.#F>0)if(this.#C())this.#F-=1;else continue;if(this.#x()){this.#F+=1;continue}switch(this.#X){case 0:this.#P()&&this.#V(1);break;case 1:if(this.#P()){this.#E();let $=7,Z=1;this.#N()?($=2,Z=3):this.#D&&($=2),this.#J($,Z)}break;case 2:this.#L()?this.#V(3):(this.#M()||this.#B()||this.#K())&&this.#V(5);break;case 3:this.#_()?this.#J(4,1):this.#L()&&this.#J(5,1);break;case 4:this.#L()&&this.#J(5,1);break;case 5:this.#A()?this.#U+=1:this.#S()&&(this.#U-=1),this.#I()&&!this.#U?this.#J(6,1):this.#M()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 6:this.#M()?this.#J(7,0):this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 7:this.#B()?this.#J(8,1):this.#K()&&this.#J(9,1);break;case 8:this.#K()&&this.#J(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#J($,Z){switch(this.#X){case 0:break;case 1:this.#Z.protocol=this.#Q();break;case 2:break;case 3:this.#Z.username=this.#Q();break;case 4:this.#Z.password=this.#Q();break;case 5:this.#Z.hostname=this.#Q();break;case 6:this.#Z.port=this.#Q();break;case 7:this.#Z.pathname=this.#Q();break;case 8:this.#Z.search=this.#Q();break;case 9:this.#Z.hash=this.#Q();break;case 10:break}this.#X!==0&&$!==10&&([1,2,3,4].includes(this.#X)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#X)&&[8,9].includes($)&&(this.#Z.pathname??=this.#D?"/":""),[1,2,3,4,5,6,7].includes(this.#X)&&$===9&&(this.#Z.search??="")),this.#T($,Z)}#T($,Z){this.#X=$,this.#G=this.#$+Z,this.#$+=Z,this.#Y=0}#H(){this.#$=this.#G,this.#Y=0}#V($){this.#H(),this.#X=$}#O($){return $<0&&($=this.#W.length-$),$<this.#W.length?this.#W[$]:this.#W[this.#W.length-1]}#z($,Z){let J=this.#O($);return J.value===Z&&(J.type==="CHAR"||J.type==="ESCAPED_CHAR"||J.type==="INVALID_CHAR")}#P(){return this.#z(this.#$,":")}#N(){return this.#z(this.#$+1,"/")&&this.#z(this.#$+2,"/")}#L(){return this.#z(this.#$,"@")}#_(){return this.#z(this.#$,":")}#I(){return this.#z(this.#$,":")}#M(){return this.#z(this.#$,"/")}#B(){if(this.#z(this.#$,"?"))return!0;if(this.#W[this.#$].value!=="?")return!1;let $=this.#O(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#K(){return this.#z(this.#$,"#")}#x(){return this.#W[this.#$].type=="OPEN"}#C(){return this.#W[this.#$].type=="CLOSE"}#A(){return this.#z(this.#$,"[")}#S(){return this.#z(this.#$,"]")}#Q(){let $=this.#W[this.#$],Z=this.#O(this.#G).index;return this.#j.substring(Z,$.index)}#E(){let $={};Object.assign($,_$),$.encodePart=i4;let Z=wQ(this.#Q(),void 0,$);this.#D=ZY(Z)}};x(tQ,"Parser");var iW=["protocol","username","password","hostname","port","pathname","search","hash"],N$="*";function oW($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let J=new URL($,Z);return{protocol:J.protocol.substring(0,J.protocol.length-1),username:J.username,password:J.password,hostname:J.hostname,port:J.port,pathname:J.pathname,search:J.search!==""?J.search.substring(1,J.search.length):void 0,hash:J.hash!==""?J.hash.substring(1,J.hash.length):void 0}}x(oW,"extractValues");function N1($,Z){return Z?sZ($):$}x(N1,"processBaseURLString");function iZ($,Z,J){let W;if(typeof Z.baseURL=="string")try{W=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=N1(W.protocol.substring(0,W.protocol.length-1),J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=N1(W.username,J)),!J&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=N1(W.password,J)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=N1(W.hostname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=N1(W.port,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=N1(W.pathname,J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=N1(W.search.substring(1,W.search.length),J)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&Z.hash===void 0&&($.hash=N1(W.hash.substring(1,W.hash.length),J))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=lQ(Z.protocol,J)),typeof Z.username=="string"&&($.username=cQ(Z.username,J)),typeof Z.password=="string"&&($.password=pQ(Z.password,J)),typeof Z.hostname=="string"&&($.hostname=hQ(Z.hostname,J)),typeof Z.port=="string"&&($.port=uQ(Z.port,$.protocol,J)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,W&&!qQ($.pathname,J)){let Y=W.pathname.lastIndexOf("/");Y>=0&&($.pathname=N1(W.pathname.substring(0,Y+1),J)+$.pathname)}$.pathname=dQ($.pathname,$.protocol,J)}return typeof Z.search=="string"&&($.search=mQ(Z.search,J)),typeof Z.hash=="string"&&($.hash=gQ(Z.hash,J)),$}x(iZ,"applyInit");function sZ($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}x(sZ,"escapePatternString");function eQ($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}x(eQ,"escapeRegexpString");function $G($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let J=".*",W=`[^${eQ(Z.delimiter)}]+?`,Y=/[$_\u200C\u200D\p{ID_Continue}]/u,j="";for(let z=0;z<$.length;++z){let X=$[z];if(X.type===3){if(X.modifier===3){j+=sZ(X.value);continue}j+=`{${sZ(X.value)}}${e$(X.modifier)}`;continue}let Q=X.hasCustomName(),G=!!X.suffix.length||!!X.prefix.length&&(X.prefix.length!==1||!Z.prefixes.includes(X.prefix)),B=z>0?$[z-1]:null,V=z<$.length-1?$[z+1]:null;if(!G&&Q&&X.type===1&&X.modifier===3&&V&&!V.prefix.length&&!V.suffix.length)if(V.type===3){let K=V.value.length>0?V.value[0]:"";G=Y.test(K)}else G=!V.hasCustomName();if(!G&&!X.prefix.length&&B&&B.type===3){let K=B.value[B.value.length-1];G=Z.prefixes.includes(K)}G&&(j+="{"),j+=sZ(X.prefix),Q&&(j+=`:${X.name}`),X.type===2?j+=`(${X.value})`:X.type===1?Q||(j+=`(${W})`):X.type===0&&(!Q&&(!B||B.type===3||B.modifier!==3||G||X.prefix!=="")?j+="*":j+=`(${J})`),X.type===1&&Q&&X.suffix.length&&Y.test(X.suffix[0])&&(j+="\\"),j+=sZ(X.suffix),G&&(j+="}"),X.modifier!==3&&(j+=e$(X.modifier))}return j}x($G,"partsToPattern");var zY=class{#j;#W={};#Z={};#$={};#Y={};#G=!1;constructor($={},Z,J){try{let W;if(typeof Z=="string"?W=Z:J=Z,typeof $=="string"){let X=new tQ($);if(X.parse(),$=X.result,W===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=W}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(W)throw TypeError("parameter 1 is not of type 'string'.")}typeof J>"u"&&(J={ignoreCase:!1});let Y={ignoreCase:J.ignoreCase===!0},j={pathname:N$,protocol:N$,username:N$,password:N$,hostname:N$,port:N$,search:N$,hash:N$};this.#j=iZ(j,$,!0),JY(this.#j.protocol)===this.#j.port&&(this.#j.port="");let z;for(z of iW){if(!(z in this.#j))continue;let X={},Q=this.#j[z];switch(this.#Z[z]=[],z){case"protocol":Object.assign(X,_$),X.encodePart=i4;break;case"username":Object.assign(X,_$),X.encodePart=iQ;break;case"password":Object.assign(X,_$),X.encodePart=sQ;break;case"hostname":Object.assign(X,fD),$Y(Q)?X.encodePart=YY:X.encodePart=WY;break;case"port":Object.assign(X,_$),X.encodePart=jY;break;case"pathname":ZY(this.#W.protocol)?(Object.assign(X,kD,Y),X.encodePart=nQ):(Object.assign(X,_$,Y),X.encodePart=oQ);break;case"search":Object.assign(X,_$,Y),X.encodePart=aQ;break;case"hash":Object.assign(X,_$,Y),X.encodePart=rQ;break}try{this.#Y[z]=rW(Q,X),this.#W[z]=tW(this.#Y[z],this.#Z[z],X),this.#$[z]=$G(this.#Y[z],X),this.#G=this.#G||this.#Y[z].some((G)=>G.type===2)}catch{throw TypeError(`invalid ${z} pattern '${this.#j[z]}'.`)}}}catch(W){throw TypeError(`Failed to construct 'URLPattern': ${W.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return!1;try{typeof $=="object"?J=iZ(J,$,!1):J=iZ(J,oW($,Z),!1)}catch{return!1}let W;for(W of iW)if(!this.#W[W].exec(J[W]))return!1;return!0}exec($={},Z){let J={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof $!="string"&&Z)throw TypeError("parameter 1 is not of type 'string'.");if(typeof $>"u")return;try{typeof $=="object"?J=iZ(J,$,!1):J=iZ(J,oW($,Z),!1)}catch{return null}let W={};Z?W.inputs=[$,Z]:W.inputs=[$];let Y;for(Y of iW){let j=this.#W[Y].exec(J[Y]);if(!j)return null;let z={};for(let[X,Q]of this.#Z[Y].entries())if(typeof Q=="string"||typeof Q=="number"){let G=j[X+1];z[Q]=G}W[Y]={input:J[Y]??"",groups:z}}return W}static compareComponent($,Z,J){let W=x((X,Q)=>{for(let G of["type","modifier","prefix","value","suffix"]){if(X[G]<Q[G])return-1;if(X[G]===Q[G])continue;return 1}return 0},"comparePart"),Y=new nZ(3,"","","","",3),j=new nZ(0,"","","","",3),z=x((X,Q)=>{let G=0;for(;G<Math.min(X.length,Q.length);++G){let B=W(X[G],Q[G]);if(B)return B}return X.length===Q.length?0:W(X[G]??Y,Q[G]??Y)},"comparePartList");return!Z.#$[$]&&!J.#$[$]?0:Z.#$[$]&&!J.#$[$]?z(Z.#Y[$],[j]):!Z.#$[$]&&J.#$[$]?z([j],J.#Y[$]):z(Z.#Y[$],J.#Y[$])}get protocol(){return this.#$.protocol}get username(){return this.#$.username}get password(){return this.#$.password}get hostname(){return this.#$.hostname}get port(){return this.#$.port}get pathname(){return this.#$.pathname}get search(){return this.#$.search}get hash(){return this.#$.hash}get hasRegExpGroups(){return this.#G}};x(zY,"URLPattern");function i3($,Z){for(let[J,W]of Object.entries($)){let Y=new zY({pathname:J});if(Y.test({pathname:Z}))return{routePath:J,params:Y.exec({pathname:Z})?.pathname.groups??{},route:W}}return null}var $Z={startIndex:0,carriedViews:[]};function ZG($,Z){let J=D0($.path,Z);return J.includes("*")?null:J}function wD($,Z){if(!$)return $Z;if($.search!==Z.search)return $Z;let J=Math.min($.segments.length,Z.segments.length-1),W=0;while(W<J){let Y=$.segments[W],j=Z.segments[W];if(j.alwaysRun)break;if(Y.viewPath!==j.viewPath)break;let z=ZG(Y,$.params),X=ZG(j,Z.params);if(z===null||X===null||z!==X)break;W++}if(W===0)return $Z;return{startIndex:W,carriedViews:Z.segments.slice(0,W).map(({viewPath:Y})=>Y)}}function qD($,Z){let[,J,...W]=$.split("/");if(!Z.includes(J))return $;let Y=`/${W.join("/")}`;return Y==="/"?"/":Y.replace(/\/$/,"")}function JG($){let{flatViewRoutes:Z,supportedLocales:J,from:W,origin:Y,to:j}=$;if(!W)return $Z;let z;try{z=new URL(W,Y)}catch{return $Z}if(z.origin!==Y)return $Z;let X=i3(Z,qD(z.pathname,J));if(!X)return $Z;return wD({segments:X.route.segments,params:X.params,search:z.search},j)}var XY="x-gemi-from";import{createElement as u1,Fragment as _G}from"react";function yD($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function s4($){let Z={};for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if("children"in W){Z[J]=[Y];let j=new W.children,z=s4(j.routes);for(let[X,Q]of Object.entries(z)){let G=J==="/"?X:`${J}${X}`,B=X==="/"&&J!=="/"?J:G;Z[B]=[Y,...Q]}if(Z[J].length===1)delete Z[J]}else Z[J]=[Y]}else{let Y=new W,j=s4(Y.routes);for(let[z,X]of Object.entries(j)){let Q=J==="/"?z:`${J}${z}`,G=z==="/"&&J!=="/"?J:Q;Z[G]=X}}return Object.fromEntries(Object.entries(Z).map(([J,W])=>[yD(J),W]))}function n4($,Z){let[J,W]=Z,Y=$.find(([j])=>j===J);if(!Y){$.push([J,[...W]]);return}for(let j of W)n4(Y[1],j)}function o4($){let Z=[];for(let[J,W]of Object.entries($))if("run"in W){let Y=W.viewPath;if(Y==="__")continue;if(Y==="REDIRECT")continue;if(Y==="FILE")continue;if("children"in W){let j=new W.children,z=o4(j.routes);n4(Z,[Y,z])}else n4(Z,[Y,[]])}else{let Y=new W,j=o4(Y.routes);for(let z of j)n4(Z,z)}return Z}function QY($){let Z=[];for(let[J,W]of $)Z.push(J,...QY(W).flat());return Array.from(new Set(Z))}function WG($,Z){let[,J,...W]=$.split("/");if(J===void 0||!Z.includes(J))return{locale:null,pathname:$||"/"};return{locale:J,pathname:`/${W.join("/")}`}}class I$ extends m{static getFacadeAccessor(){return c}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=T.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(T.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??I$.locale(),$.timeZone??I$.timeZone())}static setLocale($=I$.locale(),Z={}){let J=this.getFacadeRoot(),W=$;if(!J.supportedLocales.includes($))W=J.defaultLocale;let Y=T.getStore();if(Z.cookie!==!1)Y.setCookie("i18n-locale",W,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1});return Y.setLocale(W),W}}class GY{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}function YG($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var vD=50;class oZ{fetcher;entries=new Map;settleListener=null;failListener=null;shellAt=null;settledBacklog=[];shipped=new Set;requestStartedAt=performance.now();renderStartedAt=null;discoveryHintsMuted=!1;constructor($){this.fetcher=$}elapsed(){return Math.round(performance.now()-this.requestStartedAt)}keyFor($,Z){return[$,Z].filter((J)=>J.length>0).join("?")}markRenderStart(){if(this.renderStartedAt===null)this.renderStartedAt=performance.now()}markShell(){if(this.shellAt===null)this.shellAt=this.elapsed()}summarize($){let Z=this.elapsed();return{shellAt:this.shellAt??Z,settledAt:Z,aborted:$,queries:Array.from(this.entries.values(),(J)=>({path:J.path,variantKey:J.variantKey,startedAt:J.startedAt,settledAt:J.settledAt,status:J.status,source:J.source}))}}onQueryFail($){this.failListener=$}muteDiscoveryHints(){this.discoveryHintsMuted=!0}maybeLogLateDiscovery($){if(!$.lateBy||this.discoveryHintsMuted)return;if($.status!=="resolved")return;if(Bun.env.NODE_ENV==="production")return;let Z="";try{let Y=JSON.stringify($.data)?.length??0;Z=Y>=1024?`${(Y/1024).toFixed(1)} kB`:`${Y} B`}catch{Z="an unserializable payload"}let J=($.settledAt??0)-$.startedAt,W=$.variantKey?`, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams($.variantKey)))} }`:"";console.warn(`[gemi] useQuery("${$.patternPath}") was discovered ${$.lateBy}ms into the `+`server render \u2014 under a suspended segment, so its fetch (${J}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${W})\` in the view `+"handler starts it at request time \u2014 but note prefetched data is also re-fetched and "+`streamed into every client-side navigation payload for the route, even when the client already holds it, so weigh that bandwidth against the ${Z}. If the data is only needed conditionally (a closed popover, a hidden tab), \`{ lazy: true }\` + \`trigger()\` avoids running it here at all. \`Query.noPrefetch()\` in the handler marks the omission intentional and silences this hint for the route.`)}read($,Z){return this.entries.get(this.keyFor($,Z))}ensure($,Z={},J="render"){let W=Z.params??{},Y=new URLSearchParams(YG(Z.search??{}));Y.delete("json"),Y.sort();let j=D0($,W),z=Y.toString(),X=this.keyFor(j,z),Q=this.entries.get(X);if(Q)return Q;let G;if(J==="render"&&this.renderStartedAt!==null){let F=Math.round(performance.now()-this.renderStartedAt);if(F>vD)G=F}let B,V=new Promise((F)=>{B=F}),K={path:j,patternPath:$,variantKey:z,lateBy:G,status:"pending",promise:V,source:J,startedAt:this.elapsed()};return this.entries.set(X,K),this.fetcher($,W,Y).then((F)=>{K.status="resolved",K.data=F},(F)=>{K.status="rejected",K.error=F}).then(()=>{if(K.settledAt=this.elapsed(),this.maybeLogLateDiscovery(K),K.status==="rejected"&&this.failListener)this.failListener(K);if(this.settleListener)this.settleListener(K);else this.settledBacklog.push(K);B()}),K}async allSettled(){let $=0;while($!==this.entries.size)$=this.entries.size,await Promise.all(Array.from(this.entries.values(),(Z)=>Z.promise))}snapshotResolved(){let $={};for(let[Z,J]of this.entries){if(J.status!=="resolved")continue;this.shipped.add(Z),$[J.path]??={},$[J.path][J.variantKey]=J.data}return $}onSettle($){this.settleListener=(J)=>{if(this.shipped.has(this.keyFor(J.path,J.variantKey)))return;$(J)};let Z=this.settledBacklog;this.settledBacklog=[];for(let J of Z)this.settleListener(J)}}class d1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,J,W,Y){super(typeof W?.message==="string"?W.message:`Request to /api${$} failed with status ${J}`);this.path=$;this.variantKey=Z;this.status=J;this.body=W;this.retryAfter=Y;this.name="QueryError"}}function aZ(){let $=JSON.stringify({error:J$("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function KY(){return{status:403,error:{message:"Forbidden"}}}function s3($){let Z=rZ.getStore(),J=T.getStore();return(W,Y,j)=>{let z=new URL($.url).origin,X=[D0(W,Y),j.toString()].filter((V)=>V.length>0).join("?"),Q=new Request(`${z}/${X}`,{headers:$.headers,signal:$.signal}),G=a4($);if(G)tZ(Q,G);let B=new C(Q,Y);return rZ.run(Z,()=>T.run(B,async()=>{let V=J?.locale;if(V&&M(c).isLocaleAware)T.getStore().setLocale(V);try{let K=M(Q1).dispatchers(G).api,F=await K.runRouteMiddleware(W,B)??await K.getRouteData(W);if(r1(F)){if(!F.ok)throw new d1(D0(W,Y),j.toString(),F.status,F.body);return F.body}if(F instanceof Response){let D=await F.json().catch(()=>null);if(!F.ok)throw new d1(D0(W,Y),j.toString(),F.status,D);return D}return F}catch(K){if(K instanceof d1)throw K;let F=new d1(D0(W,Y),j.toString(),500,{message:K instanceof Error?K.message:String(K)});throw F.cause=K,F}}))}}var gD=new Set(["script","style","template","title"]),mD=/\shidden([\s=/]|$)/i,hD=/"[^"]*"|'[^']*'/g;function pD($){let Z=0,J=0,W=0,Y=0;while(Y<$.length){let j=$.indexOf("<",Y),z=j===-1?$.length:j;if(z>Y){let V=$.slice(Y,z).replace(/\s+/g,"").length;if(W>0)J+=V;else Z+=V}if(j===-1)break;if($.startsWith("<!--",j)){let V=$.indexOf("-->",j+4);Y=V===-1?$.length:V+3;continue}let X=$.indexOf(">",j);if(X===-1)break;let Q=$.slice(j+1,X);Y=X+1;let G=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(Q)?.[1]?.toLowerCase();if(!G)continue;let B=Q.startsWith("/");if(!B&&gD.has(G)&&!Q.endsWith("/")){let V=$.indexOf(`</${G}`,Y);Y=V===-1?$.length:V;continue}if(G!=="div")continue;if(B){if(W>0)W-=1}else if(W>0)W+=1;else if(mD.test(Q.replace(hD,'""')))W=1}return{shellChars:Z,deferredChars:J}}var cD=1000,dD=64;function uD($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function lD($,Z){if(Z.deferredChars<cD)return null;if(Z.shellChars>=dD)return null;return`[gemi] GET ${$} streams ${uD(Z.deferredChars)} of its `+`content behind reveal scripts \u2014 a no-JS visitor sees ~${Z.shellChars} chars. If this is a public/content route, add "no-stream" to its middleware.`}function jG($=console.warn){let Z=new Set;return{shouldObserve(J){return!Z.has(J)},report(J,W){if(Z.has(J))return;let Y=lD(J,W);if(!Y)return;Z.add(J),$(Y)}}}function zG(){let $=new TextDecoder,Z="";return{onChunk(J){Z+=$.decode(J,{stream:!0})},measure(){return Z+=$.decode(),pD(Z)}}}function XG($,Z,J=1e4,W){let Y=new TextEncoder,j=()=>{};return new ReadableStream({start(z){let X=!1,Q=(B)=>{if(X)return;X=!0,clearTimeout(G);try{z.close()}catch{}W?.({aborted:B})};j=Q,z.enqueue(Y.encode(`${JSON.stringify($)}
|
|
20
20
|
`)),Z.onSettle((B)=>{if(X||B.status!=="resolved")return;z.enqueue(Y.encode(`${JSON.stringify([B.path,B.variantKey,B.data])}
|
|
21
|
-
`))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as $I,createContext as eD,createElement as ZI,lazy as JI,use as WI,useContext as YI}from"react";import{createContext as iD}from"react";var sD=iD(null);import{createContext as aD,useContext as a_}from"react";import{useContext as l_}from"react";import{createContext as nD}from"react";import{jsx as c_}from"react/jsx-runtime";var oD=nD({});var rD="gemi.islandI18n",tD=globalThis[Symbol.for(rD)]??=aD(null);function
|
|
21
|
+
`))});let G=setTimeout(()=>Q(!0),J);Z.allSettled().then(()=>Q(!1),()=>Q(!1))},cancel(){j(!1)}})}import{Fragment as $I,createContext as eD,createElement as ZI,lazy as JI,use as WI,useContext as YI}from"react";import{createContext as iD}from"react";var sD=iD(null);import{createContext as aD,useContext as a_}from"react";import{useContext as l_}from"react";import{createContext as nD}from"react";import{jsx as c_}from"react/jsx-runtime";var oD=nD({});var rD="gemi.islandI18n",tD=globalThis[Symbol.for(rD)]??=aD(null);function QG($,Z={}){let J=new Set,W={islands:[],render:$,instances:new WeakMap,count:0,i18n:{},localeAware:Boolean(Z.currentLocale),i18nUsed:!1,dictionaries:[],sink:{use(Y,j,z){let X=`${Y} ${j}`;if(J.has(X))return;J.add(X),W.dictionaries.push([Y,j,z])},onUse(){}}};for(let Y of["currentLocale","defaultLocale","timeZone"])Object.defineProperty(W.i18n,Y,{enumerable:!0,get(){return W.i18nUsed=!0,Z[Y]}});return W}function GG($){if(!$.i18nUsed&&!$.localeAware)return;let{currentLocale:Z,defaultLocale:J,timeZone:W}=$.i18n;return{...Z?{currentLocale:Z}:{},...J?{defaultLocale:J}:{},...W?{timeZone:W}:{},...$.dictionaries.length>0?{dictionaries:$.dictionaries}:{}}}var n3="gemi-slot",KG="data-slot",BG="data-gemi-slot";var $O=Symbol.for("gemi.staticRender"),VG=globalThis[$O]??=eD(null);import{createHash as LG}from"crypto";var BY='var r=document,i=window,a=history;i.__gemi_nav?.d();var L=new AbortController,h=(t,e,n,s)=>t.addEventListener(e,n,{signal:L.signal,...s}),q=i.__gemi_nav={d:()=>L.abort()},v=(t,e)=>{if(!t.g)t.g=1,import(e.s).then((n)=>{if(t.isConnected)t.r=n.h(t,n.m[e.e])}).catch((n)=>console.error(n))},D=(t)=>{let e=t.getElementById("gemi-islands");return e?JSON.parse(e.textContent):{i:[]}},R=(t,e)=>{for(let n of t.querySelectorAll("gemi-island")){let s=e.i[n.dataset.island];if(!s||n.o)continue;if(s.l=="eager")v(n,s);else if(s.l=="idle"||!i.IntersectionObserver||!n.children.length)(i.requestIdleCallback||setTimeout)(()=>v(n,s));else{let l=new IntersectionObserver((m)=>{if(m.some((d)=>d.isIntersecting))l.disconnect(),v(n,s)});for(let m of n.children)l.observe(m)}}},O=\'meta[name="gemi-static"]\',A="style:not([data-gemi-fonts])",T=A+",link[rel=stylesheet]",K=`head>${A},body>${A},link[rel=stylesheet]`,I=\'meta[name]:not([name=viewport]),meta[property],link[rel~=canonical],link[rel~=alternate],link[rel~=icon],link[rel=preload][as=font],style[data-gemi-fonts],script[type="application/ld+json"]\',w=(t)=>t.querySelector(O)?.content,C=(t)=>[...t.querySelectorAll(K)].map((e)=>e.outerHTML).join(),c=(t)=>t.href.split("#")[0],p=r.createElement("div");p.setAttribute("aria-live","polite");p.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap";r.body.append(p);var _=(t)=>{q.p={url:location.href,title:r.title,initial:t},r.dispatchEvent(new CustomEvent("gemi:page-load",{detail:q.p}))},f=new Map,k=(t)=>{let e=f.get(t);if(!e||Date.now()-e[0]>30000){let n=fetch(t,{headers:{accept:"text/html","x-gemi-navigate":"1"},signal:AbortSignal.timeout(1e4)}).then((s)=>{if(!s.ok||!/^text\\/html/.test(s.headers.get("content-type"))||new URL(s.url||t).origin!=location.origin)throw s;return s.text().then((l)=>[s.url||t,l])});e=[Date.now(),n],n.catch(()=>f.get(t)==e&&f.delete(t))}if(f.delete(t),f.set(t,e),f.size>10)f.delete(f.keys().next().value);return e[1]},M=(t)=>{let e=t.target.closest?.("a[href]"),n=e?.getAttribute("target");if(!e||n&&n!="_self"||e.hasAttribute("download")||/(^|\\s)external(\\s|$)/i.test(e.getAttribute("rel"))||e.closest("[data-gemi-reload]"))return;let s=new URL(e.getAttribute("href"),r.baseURI);if(s.origin==location.origin&&!(s.href.includes("#")&&c(s)==c(location)))return s},y={},U=()=>Math.random().toString(36).slice(2),E=()=>a.state?.g||a.replaceState({...a.state,g:U()},""),P=c(location),b=0,N=(t)=>{if(!t.hasAttribute("tabindex"))t.setAttribute("tabindex","-1"),t.addEventListener("blur",()=>t.removeAttribute("tabindex"),{once:!0});t.focus({preventScroll:!0})},Y=(t)=>{let e=r.body,n=t.body,s=D(t),l=r.documentElement;r.title=t.title;for(let o of["lang","dir"]){let u=t.documentElement.getAttribute(o);if(u==null)l.removeAttribute(o);else l.setAttribute(o,u)}for(let o of r.head.querySelectorAll(I))o.remove();let m=new Set([...r.querySelectorAll("link[rel=modulepreload]")].map((o)=>o.getAttribute("href")));r.head.append(...t.head.querySelectorAll(I),...[...t.head.querySelectorAll("link[rel=modulepreload]")].filter((o)=>!m.has(o.getAttribute("href"))));let d=new Map([...e.querySelectorAll("[data-gemi-persist]")].map((o)=>[o.dataset.gemiPersist,o])),g=[...n.querySelectorAll("[data-gemi-persist]")].map((o)=>[o,d.get(o.dataset.gemiPersist)]).filter((o)=>o[1]);for(let o of[...e.querySelectorAll("gemi-island")].reverse())if(o.o=1,!g.some((u)=>u[1].contains(o)))try{o.r?.unmount()}catch(u){console.error(u)}for(let[o,u]of g)o.replaceWith(u);for(let o of[...e.childNodes])if(!o.matches?.(T))o.remove();for(let o of[...n.children])if(o.matches(T))o.remove();for(let o of[...e.attributes])e.removeAttribute(o.name);for(let o of n.attributes)e.setAttribute(o.name,o.value);e.append(...n.childNodes,p),R(e,s)},H=async(t,e)=>{let n=++b,s=!e&&y[a.state?.g];a.scrollRestoration="manual";try{let[l,m]=await k(c(t));if(n!=b)return;let d=new DOMParser().parseFromString(m,"text/html");if(w(d)==null||w(d)!=w(r)||C(d)!=C(r))throw 0;if(e){let o=new URL(l);o.hash=t.hash,a.pushState({g:U()},"",o.href)}P=c(location),Y(d);let g=e&&t.hash&&r.getElementById(decodeURIComponent(t.hash.slice(1)));if(g)g.scrollIntoView({behavior:"instant"});else i.scrollTo({left:s?.[0]||0,top:s?.[1]||0,behavior:"instant"});if(e)N(g||r.querySelector("h1")||r.querySelector("main")||r.body);p.textContent=r.title,_(!1)}catch{if(n!=b)return;if(e)location.assign(t.href);else location.reload()}};h(r,"click",(t)=>{if(t.defaultPrevented||t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let e=M(t);if(e&&r.dispatchEvent(new CustomEvent("gemi:before-navigate",{cancelable:!0,detail:{url:e.href}})))t.preventDefault(),E(),y[a.state.g]=[i.scrollX,i.scrollY],H(e,1)});h(i,"popstate",()=>{if(b++,c(location)==P){let t=y[a.state?.g];if(t)i.scrollTo({left:t[0],top:t[1],behavior:"instant"})}else if(a.state?.g)H(new URL(location.href),0);else location.reload()});h(i,"hashchange",E);h(i,"scroll",()=>a.state?.g&&(y[a.state.g]=[i.scrollX,i.scrollY]),{passive:!0});var S,x=(t)=>{if(r.querySelector(O)?.dataset.prefetch=="none"||navigator.connection?.saveData)return;let e=M(t);if(e&&c(e)!=c(location))k(c(e))};h(r,"pointerover",(t)=>{clearTimeout(S),S=setTimeout(()=>x(t),65)});h(r,"pointerout",()=>clearTimeout(S));h(r,"focusin",x);h(r,"touchstart",x,{passive:!0});E();R(r,D(r));_(!0);';import{createHash as ZO}from"crypto";import{existsSync as UG,readFileSync as JO}from"fs";import{join as DY}from"path";var DG=".script",WO=[".ts",".js"],YO="document-scripts.json",OG="data-gemi-script",jO=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/;function zO($){if(typeof $!=="string"||!jO.test($))throw Error(`A static view's \`script\` is a path under app/views without the ".script.ts" suffix, e.g. "site/clicks". Got ${JSON.stringify($)}.`)}function XO($,Z){for(let J of WO){let W=DY($,"views",`${Z}${DG}${J}`);if(UG(W))return W}return null}async function FG($){let Z=await Bun.build({entrypoints:[$],target:"browser",format:"iife",minify:!0,throw:!1});if(!Z.success||!Z.outputs[0]){let W=Z.logs.map((Y)=>String(Y)).join(`
|
|
22
22
|
`);throw Error(`The document script ${$} does not bundle.
|
|
23
|
-
${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function QO($){return`'sha256-${ZO("sha256").update($).digest("base64")}'`}var VY,FY=new Map;function GO(){if(VY===void 0){let $=DY(UY(),"dist","server",YO);VY=FG($)?JSON.parse(JO($,"utf8")):null}return VY??null}async function OY($){zO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=GO()?.[$];if(j!==void 0)return j;let z=FY.get($);if(z)return z}let J=DY(UY(),"app"),W=XO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${UG}.ts (or .js).`);if(!Z)return VG(W);let Y=VG(W);return FY.set($,Y),Y.catch(()=>FY.delete($)),Y}async function FI($){return QO(await OY($))}var KO="gemi-islands",BO="gemi-island-i18n",TI=`'sha256-${OG("sha256").update(HY).digest("base64")}'`;function LY($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var MY=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),NI=`'sha256-${OG("sha256").update(BY).digest("base64")}'`,VO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',FO="gemi-static";function LG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let O=U.module?J(U.module):void 0;if(!O)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let L of O.preload)z.add(L);if(U.preloadDynamic)for(let L of O.dynamicPreload??[])z.add(L)}return{s:O.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${DG}="${MY(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return LY($,"</head>",G,!1);let V=(Y?`<meta name="${FO}" content="${MY(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${MY(U)}"/>`).join("")+G,K=Y?BY:HY,F=Q?QG(Z):void 0,D=(Q?`<script type="application/json" id="${KO}">${a0({i:X})}</script>`:"")+(F?`<script type="application/json" id="${BO}">${a0(F)}</script>`:"")+`<script type="module">${W?VO+K:K}</script>`;return LY(LY($,"</head>",V,!1),"</body>",D,!0)}function UO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function MG($){let Z=`<template ${KG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=UO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${s3} ${GG}="${j}" style="display:contents"></${s3}>`;$=$.split(Q).join(`<${s3} style="display:contents">${X}</${s3}>`)}return $}function PY($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function PG($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function DO($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var HG=new Set;function TG($,Z){if(!DO($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!HG.has(Z))HG.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var OO=async()=>(await import("./chunk-8tzmat5s.js")).default,TY,n3=async(...$)=>{return TY??=import("react-dom/server.browser").catch((Z)=>{throw TY=void 0,Z}),(await TY).renderToReadableStream(...$)},_G=1e4,IG="no-locale",LO="no-theme";async function MO($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var xY="/assets";function HO($){return $===xY||$.startsWith(`${xY}/`)}function PO($){let Z=$.filter(HO);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${xY}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function TO($){let Z=M(X1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function NY($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function NO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class o3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=YG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;constructor($,Z={}){let J=AQ();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.translate=$.translate,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":HQ(Z)};if(this.requiredViews=Object.fromEntries(LQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=l4(W),!this.assetRoutes)PO(Object.keys(this.flatViewRoutes));this.routeManifest=s4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=o4(W),this.flatComponentTree=QY(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=M(Y$);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)r4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{ZZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>c1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=IY(),V=new AbortController,K=setTimeout(()=>V.abort(),_G),F=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=XG(async(U,O)=>{let L=await n3(U,{signal:V.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});return await L.allReady.catch(()=>{}),await new Response(L).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone});try{let U,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)U={name:O,source:await OY(O)};let L;if(W.navigation){let I=W.navigation===!0?{}:W.navigation,S=I.version?String(await J(()=>I.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",U?.name??"",S].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let P=await n3(c1(BG.Provider,{value:D,children:c1(NG,{children:[...G,c1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});await P.allReady.catch(()=>{});let H=MG(await new Response(P).text());return new Response(LG(H,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,U),{status:$.status,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:V,noTheme:K,url:F,user:D,viewData:U,breadcrumbs:O,urlLocaleSegment:L,meta:P,isOgRequest:H,appId:I,features:S,staticView:A}=$,b=this.theme===!1||K||A?null:{cookie:this.theme.cookie??lW,default:this.theme.default??null,value:_O(Z,this.theme.cookie??lW)},k=L?JG(Q,[L]).pathname:Q,N={kind:"view",data:{meta:P,pageData:{[k]:U},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?TO(Z):null},appId:I,features:S,theme:b,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},v=this.root,_=this.routeManifest[Y];return async(f)=>{let{bootstrapModules:H0=[],loaders:Z3,getStyles:u1,viewImportMap:x1,cssManifest:n,ogMap:y,viewModules:$0,clientEntry:l1,modulePreloadManifest:t3,assetBase:jZ,resolveIsland:i1,buildId:Q1}=f,x$=l1?[]:H0,s1=(p)=>[p,`window.loaders=${Z3}`,...l1?[`import(${JSON.stringify(l1.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(H){let p=null,u0=null;for(let R of _??[])if(typeof y[R]==="function")u0=R,p=y[R];if(!p)return new Response("Not found",{status:404});let J3=Object.values(N.data.pageData)[0];try{await n3(c1(p,J3[u0]),{onError:()=>{}})}catch(R){let{fonts:r,...a1}=R.satoriOptions,e3=await Promise.all(r.map(($6)=>{return MO($6.name,$6.weight,$6.style).then((kK)=>({...$6,data:kK}))})),J5=new Headers(j);J5.set("Content-Type","image/png");let[EK,bK]=await Promise.all([OO(),d4("Rendering an OG image")]),RK=await EK(R.jsx,{...a1,fonts:e3}),fK=await bK(Buffer.from(RK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(fK),{headers:J5})}return new Response("data")}if(A&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:A,currentViews:_,data:N.data,serverQueries:G,headers:j,getStyles:u1,viewImportMap:x1,viewModules:$0,resolveIsland:i1,buildId:Q1,status:200});if(A&&!Y&&this.notFound){let p=this.notFound.view;if(!x1[p])throw Error(`The not-found view "${p}" (route.view.notFound) was not found. It is a view path: a file at app/views/${p}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:A,currentViews:[p],data:N.data,serverQueries:G,headers:j,getStyles:u1,viewImportMap:{...x1,"404":x1[p]},viewModules:$0&&{...$0,"404":$0[p]},resolveIsland:i1,buildId:Q1,status:$.refusedStatus??404})}if(N.data.cssManifest=n,N.data.modulePreloadManifest=t3??{},jZ&&jZ!=="/")N.data.assetBase=jZ;if(Q1&&Q1!=="dev")N.data.buildId=Q1;let j0=this.modulePreloadLinks({clientEntry:l1,modulePreloadManifest:t3,views:_??["404"],routeKey:Y??"404"}),U8=await u1(_??["404"]);N.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let C$=new AbortController,n1=setTimeout(()=>C$.abort(),_G),o1=T6(B)||V,zZ=Bun.env.NODE_ENV!=="production"&&!o1&&Y&&this.shellReporter.shouldObserve(Y)?jG():null,A$=IY();try{let p=await n3(c1(NG,{children:[...j0,...U8,...b?[c1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:RQ(a0({cookie:b.cookie,default:b.default}))}})]:[],c1(v,{data:N.data,viewImportMap:x1,viewModules:$0,serverQueries:G,dictionarySink:A$,key:"root"})]}),{bootstrapScriptContent:s1(`window.__GEMI_DATA__ = ${a0(N.data)}`),bootstrapModules:x$,signal:C$.signal,...o1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(u0){if(Bun.env.NODE_ENV!=="production")console.error(u0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(n1)),o1)await p.allReady.catch(()=>{});return new Response(a8(p,G,{onShell:o1?void 0:()=>G.markShell(),onChunk:zZ?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(C$.signal.aborted)),zZ)this.shellReporter.report(Y,zZ.measure())})},A$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(p){if(clearTimeout(n1),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(C$.signal.aborted))),p;let u0=await n3(c1("div"),{bootstrapScriptContent:s1(`window.error= ${a0(p.message)}; window.stack_trace=${a0(p.stack)};window.__GEMI_DATA__ = ${a0(N.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...x$]:x$});return new Response(a8(u0,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(C$.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(E$(Z))return 404;if(Z?.kind===$$){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(Z$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof p1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,B=null,V=M(c),K=l3(this.flatViewRoutes,j),F=V.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(IG);if(F&&V.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),f=F&&V.supportedLocales.includes(_.slice(1));if(_&&!f)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(F&&!Y&&B===null&&!(B===null&&K!==null)){let _=_Y(z,V.supportedLocales,V.defaultLocale);if(_){let f=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${f}${W?".json":""}${J.search}`}})}}if(F&&!Y){let _=M(c).detectLocale(new C($,{},"view",Q));if(B===null&&_!==V.defaultLocale){let f=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${f}${J.search}`}})}}Q=Q.replace("//","/");let U=[],O=[],L=null,P={},H=null,I=!1,S=!1,A=[],b,k=!1,N=!1;try{let _=l3(this.flatViewRoutes,Q);if(B&&_?.route.middleware.includes(IG))_=null;if(_){if(k=!0,L=_.routePath,P=_.params,U=_.route.exec,O=_.route.middleware,A=_.route.features,I=O.includes("no-stream"),S=O.includes(LO),b=_.route.static,N=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let f=$.headers.get(XY),H0=ZG({flatViewRoutes:this.flatViewRoutes,supportedLocales:M(c).supportedLocales,from:f,origin:J.origin,to:{segments:_.route.segments,params:P,search:J.search}});if(H0.startIndex>0)U=U.slice(H0.startIndex),H={from:f,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(b&&W)return new Response("Not found",{status:404});let v=new C($,P,"view",L);return this.hooks.onRequestStart(v),await T.run(v,async()=>{let _=null,f=T.getStore(),H0=rZ.getStore(),Z3=(y)=>rZ.run(H0,()=>T.runWith(f,y));f.serverQueries=new oZ(i3($));let u1=new Set;f.serverQueries.onQueryFail((y)=>{u1.add(y.error);try{Z3(()=>Promise.resolve(this.hooks.onRequestFail(n,y.error)).catch(()=>{}))}catch{}});let x1=PY(N?{}:b??(L===null&&!W?this.notFound?.static:void 0));if(B){let y=B.replaceAll("/","");I$.setLocale(y,{cookie:x1.locale})}else if(V.isLocaleAware&&!F)f.setLocale(V.defaultLocale);else I$.setLocale(void 0,{cookie:x1.locale});let n=f.req;if(x1.session)r4();try{let y=null;if(this.detectLocale&&!F&&M(c).isLocaleAware){let{supportedLocales:R,defaultLocale:r}=M(c),a1=await this.detectLocale(n,{supportedLocales:R,defaultLocale:r}),e3=typeof a1==="string"?_Y(a1,R,r):null;if(e3)f.setLocale(e3)}try{await M(e1).runMiddleware(O)}catch(R){if(y=this.viewRefusalStatus(n,R,u1),y===null)throw R}if(y!==null||A.length>0&&!await this.passesFeatureGates(A))L=null,U=[],n.routePath="";let $0=M(c),l1=$0.isEnabled,t3=$0.isLocaleAware,jZ=new C($,n.params),i1={defaultLocale:$0.defaultLocale,timeZone:$0.detectTimeZone(jZ)};if(t3){let R=null;if(B)R=B.replaceAll("/",""),f.setLocale(R);else if(!F)R=f.locale??$0.defaultLocale;else R=$0.detectLocale(jZ),f.setLocale(R);let r=l1?$0.getPageTranslations(R,n.routePath):{};i1={...i1,supportedLocales:$0.supportedLocales,currentLocale:R,dictionary:{[R]:r},defaultLocale:$0.defaultLocale,...F?{}:{localeRouting:"off"}}}await xG(i1.currentLocale??"");let Q1;try{Q1=await Promise.all(U.map((R)=>R(n)))}catch(R){if(y=this.viewRefusalStatus(n,R,u1),y===null)throw R;L=null,U=[],n.routePath="",Q1=[]}let x$=void 0;if(L===null)x$=await this.hooks.onNotFound(n,{status:y??404});if(this.defaultMeta&&!f.metadata.hasAllDefaultFields)f.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(n):this.defaultMeta);if(this.translate!==void 0)f.metadata.applyTranslateDefault(this.translate);let{cookies:s1,headers:j0}=f;if(y!==null)j0.set("Cache-Control","no-store");_={data:Q1,cookies:s1,headers:j0,user:f.user,prefetchedData:f.serverQueries.snapshotResolved(),currentPathName:L,params:n.params,urlLocaleSegment:G,meta:f.renderMeta(),appId:M(GY).id,features:await M(Y$).forClient()};let{params:U8,user:C$}=_,n1={},o1={};for(let R of Q1??[]){let[r,a1]=Object.entries(R)?.[0]??[];if(!r||!a1)continue;o1[`${r}:${L}`]=a1.breadcrumb,n1[r]=a1}let zZ=L===null&&this.notFound&&!W?this.notFound.static:void 0;if(zZ&&x$)n1["404"]=x$;let A$=n1.FILE;if(A$){try{await this.onRequestEnd(n,{mintSession:!1})}catch(r){ZZ.error(r?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(r)})}let R;if(A$ instanceof Response)R=e4(A$,j0,s1);else{for(let r of s1)j0.append("Set-Cookie",r.toString());R=await A8(A$,j0)}return TG(R,L)}if(W){j0.set("Content-Type","application/x-ndjson; charset=utf-8"),j0.append("Vary",XY),s1.forEach((r)=>j0.append("Set-Cookie",r.toString())),await this.hooks.onRequestEnd(n);let R={meta:H&&!f.metadata.touched?null:_.meta,data:{[Q]:n1},breadcrumbs:o1,prefetchedData:f.serverQueries.snapshotResolved(),i18n:i1,features:_.features,is404:!L,appId:_.appId,partial:H};return new Response(zG(R,f.serverQueries,void 0,({aborted:r})=>Z3(()=>this.completeStream(n,f.serverQueries.summarize(r)))),{headers:j0})}j0.set("Content-Type","text/html; charset=utf-8");let p=L?b:zZ,u0=Boolean(p),J3=PY(p);if(!I&&!u0)j0.append("Vary","User-Agent");if(!u0||J3.session)r4();for(let R of s1)j0.append("Set-Cookie",R.toString());if(!u0||J3.csrf){let R=Bun.CSRF.generate(process.env.SECRET);j0.append("Set-Cookie",`csrf_token=${R}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(n,{mintSession:!u0||J3.session})}catch(R){ZZ.error(R?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(R)})}if(u0&&(L||!k))PG(j0,p);return await this.render({req:n,runInRequestScope:Z3,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:j0,i18n:i1,params:U8,pathname:J.pathname,serverQueries:f.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,noTheme:S,url:J,user:C$,viewData:n1,breadcrumbs:o1,urlLocaleSegment:G,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:p,refusedStatus:y??void 0})}catch(y){if(y.kind===$$){let $0=W?NO(y.payload.viewData??y.payload.api):NY(y.payload.view);for(let l1 of f.cookies)$0.headers.append("Set-Cookie",l1.toString());return $0}if(!u1.has(y))this.hooks.onRequestFail(n,y);if(Z$(y))return console.error(y),W?aZ():NY(KY());if(y instanceof p1&&y.status===403)return W?aZ():NY(KY());throw y}},Z)}}function _O($,Z){let J=$.cookies?.get(Z);return bQ(J)?J:null}function CY(){let $=JSON.stringify({error:J$("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class EG extends C0{routes={"/api-routes":this.get(()=>{let $=M($8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=M(o3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var IO=new Set([t1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),xO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,CO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function AO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(IO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===t1)throw Error(`dispatchAs: credentials may not set the "${t1}" cookie. The access token stays the initiator's.`);if(!xO.test(Y)||!CO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function SO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function CG($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function e4($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function EO(){return Bun.env.NODE_ENV==="development"}class $8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=CQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=cW({"/":$.rootRouter,"/auth":yW,"/__gemi__/services/i18n":vW,"/__gemi__/services/image":hW,...EO()?{"/__gemi__/services/logs":pW,"/__gemi__/debug":EG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=SG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await M(e1).runMiddleware(W)}catch(Y){if(Y.kind===$$)return CG(Y.payload.api);else{if(E$(Y))return CY();if(this.onRequestFail(Z,Y),console.error(Y),Z$(Y))return aZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===$$)return CG(j.payload.api);if(E$(j))return CY();if(this.onRequestFail(J.req,j),console.error(j),Z$(j))return aZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){ZZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:J$("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=M(c);if(G.isEnabled){let U=G.detectLocale(j);z.setLocale(U)}z.setRequest(j),M(e1).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let U=e4(B,z.headers,z.cookies);return await Q(),U}let V=await this.getRouteData(W),K=z.headers,F=z.cookies;if(V instanceof Response){let U=e4(V,K,F);if(this.isOpenEndedBody($,U)){let O=SO(U,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),U}let D=(r1(V)?V:G1.json(V)).toResponse(K,F);return await Q(),D}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],V=Q?null:$.cookies.get(t1);if(V)B.push(`${t1}=${V}`);if(Y?.credentials)AO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(t1);if(K)G.set(t1,K);let F=$.headers.get("User-Agent");if(F)G.set("User-Agent",F);let D;if(W instanceof FormData)D=W;else if(W!==void 0)G.set("Content-Type","application/json"),D=JSON.stringify(W);let U=new Request(z,{method:Z,headers:G,body:D,...Y?.signal?{signal:Y.signal}:{}});if(AG(U,VZ($),Q?.grant,Y?.progress),$.domain)tZ(U,$.domain);let O=Q?{user:Q.user}:void 0;return T.exit(()=>X6.exit(()=>this.handleApiRequest(U,O)))}}import{timingSafeEqual as bO}from"crypto";var W8="",EY="*",RO=60000,fO=1e4,Z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,J8=16,AY=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,SY="x-forwarded-host";function RG($){return $.startsWith(":")}function a3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&bO(J,W)}function kO($){if(!$)return[];if($===!0)return[{header:SY,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:SY;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function wO($){if(!$||$===!0)return;if(!Array.isArray($)){bG($,"route.domains.trustProxy",SY);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);bG(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function bG($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!AY.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!AY.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!AY.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<J8)throw Error(`\`${Z}.secret.value\` must be at least ${J8} characters. A guessable one lets any client name its own host.`)}function N1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function qO($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function fG($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>Z8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function yO($){let Z=N1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>Z8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<J8)throw Error(`\`route.domains.ask.secret\` must be at least ${J8} characters. A guessable one is worse than leaving \`ask\` out.`);wO($.trustProxy),fG($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),RG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>Z8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class bY{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){yO($),this.root=N1($.root),this.devHosts=fG($.devHosts),this.hostTrusts=kO($.trustProxy);for(let Z of $.groups??[])if(RG(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??RO,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||a3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:R$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return N1(this.forwardedHost($))??N1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&N1(Y)?qO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:EY,params:{},custom:!0};return null}async allows($,Z){let J=N1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:W8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&Z8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=fO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=N1($);if(Z)this.cache.delete(Z)}}}var vO={kind:"none"};function ix($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return vO;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function sx($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:R$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var kG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,wG=16;function nx($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!kG.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!kG.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<wG)throw Error(`GEMI_PROXY_SECRET must be at least ${wG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function qG($,Z){if(!a3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:R$(J)}var gO="/__gemi__/domains/ask";class X1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(W8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new bY(J);let W=(Y)=>({api:Y.api?new $8({...Z.api,...Y.api}):$.api,view:Y.view?new o3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(EY,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)RY($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?qG($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)RY($,J);let Z=a4($)??await this.resolver.resolve($);if(!Z)return null;return tZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==gO)return null;if(!a3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??W8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function eZ($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var yG=600000;function vG($,Z){return[L6($,Z),L6($,Z-1)]}class E{static token="auth";config;provider;constructor($={},Z=new Z7){x2($.oauthProviders),this.config={...P1(C2($),$),emailCode:o8($.emailCode)},this.provider=Z}async oauthProvider($){return await MZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await h2(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=M().bound(X1)?M(X1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?M(X1).resolver?.root:N1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??N1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!d8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=eZ(J.expiresAt),j=eZ(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/yG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=L6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of vG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(d8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/yG),W=vG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=T.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new b$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=F2(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:P2(Z),Q=M6("link",$,j),G=M6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((F)=>eZ(F.createdAt)+B>Date.now()&&F.pin!==G&&F.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((F)=>F.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return OZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>eZ(G.createdAt)+W*60000>Date.now());if(z.length===0)return OZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await _2(G.id,eZ(G.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let Q=null;for(let G of z)if(OZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return OZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(OZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(eZ(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends m{static getFacadeAccessor(){return E}static async user(){let $=await q0.userOrNull();if($)return $;throw new b$({redirectTo:G6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await Y6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return B1(Z?.search.get(K1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await q0.user();if(!await $(Z))throw new FZ}static async guardSafe($){let Z=await q0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class Y8{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new oZ(i3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=Y8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){Y8.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new oZ(i3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function mO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function fY($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?mO(z):encodeURIComponent(String(z))}`});return`${j8}${J==="/"?"":J}`||j8}var gG=new Map;function mG($,Z){let J=gG.get($);if(!J)J=new URLPattern({pathname:`${j8}${$==="/"?"":$}`}),gG.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function hG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=hO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function hO($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class pG{static origin($){return kY($)}static absolute($,...Z){return`${t$()}${D0(String($),Z[0]??{})}`}static relative($,...Z){return D0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=M(X1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):t$();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return hG({root:W.root,origin:j},$,D0(String(Z),J[0]??{}))}static api($,...Z){return fY(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${kY()}${fY(String($),Z[0]??{})}`}static matchApi($,Z){return mG(String($),Z)}}class cG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static robots($){T.getStore().metadata.robots($)}static translate($=!0){T.getStore().metadata.translate($)}static fonts($){T.getStore().metadata.fonts($)}}var pO={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class d1 extends m{static getFacadeAccessor(){return JZ}static get client(){return this.getFacadeRoot().client}static get($){return d1.client.get($)}static set($,Z){return d1.client.set($,Z)}static del(...$){return d1.client.del(...$)}static exists($){return d1.client.exists($)}static incr($){return d1.client.incr($)}static expire($,Z){return d1.client.expire($,Z)}static ttl($){return d1.client.ttl($)}}function lC($){return $}function dG(){return{store:"memory",ttl:null}}class wY{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var cO="500";class qY{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${dO(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",cO]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=M(),Z=$.bound(JZ)?$.make(JZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function dO($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var uO="k:",uG="tag:",lO="t:";class yY{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class vY extends yY{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=P1(dG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)WZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new iG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return uO+sG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=uG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=lG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(uG+Z,lG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:WZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new wY(this.config.memory);if($==="redis"){let Z=this.options.application;return new qY({...this.config.redis,client:Z?{send:(J,W)=>Z.make(JZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class iG extends yY{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){sG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${lO}${Z.join(",")}:${$}`}}function sG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function lG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class nG extends m{static getFacadeAccessor(){return vY}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class oG extends m{static getFacadeAccessor(){return V1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class rG extends m{static getFacadeAccessor(){return aG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class eG extends m{static getFacadeAccessor(){return tG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class $K extends m{static getFacadeAccessor(){return u3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function HA($){return $}function ZK(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function z8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function gY($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:iO}=globalThis.Bun;function sO(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var nO=async($)=>{let Z=new iO($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},oO=async($)=>{let Z;try{Z=(await import("./chunk-qfqn7rz8.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},JK=($)=>sO()?nO($):oO($);var aO=/^[A-Za-z_][A-Za-z0-9_]*$/;class mY{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!aO.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??JK}async createTable(){for(let $ of rO(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return WK(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
23
|
+
${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))throw Error(`The document script ${$} contains "</script" or "<!--", which would end the inline <script> it is put in. Write it "<\\/script" or build the string from parts.`);return J}function QO($){return`'sha256-${ZO("sha256").update($).digest("base64")}'`}var VY,FY=new Map;function GO(){if(VY===void 0){let $=DY(UY(),"dist","server",YO);VY=UG($)?JSON.parse(JO($,"utf8")):null}return VY??null}async function OY($){zO($);let Z=Bun.env.NODE_ENV==="production";if(Z){let j=GO()?.[$];if(j!==void 0)return j;let z=FY.get($);if(z)return z}let J=DY(UY(),"app"),W=XO(J,$);if(!W)throw Error(`The document script "${$}" was not found. It is a file at app/views/${$}${DG}.ts (or .js).`);if(!Z)return FG(W);let Y=FG(W);return FY.set($,Y),Y.catch(()=>FY.delete($)),Y}async function FI($){return QO(await OY($))}var KO="gemi-islands",BO="gemi-island-i18n",TI=`'sha256-${LG("sha256").update(HY).digest("base64")}'`;function LY($,Z,J,W){if(!J)return $;let Y=W?$.lastIndexOf(Z):$.indexOf(Z);return Y===-1?$+J:$.slice(0,Y)+J+$.slice(Y)}var MY=($)=>$.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<"),NI=`'sha256-${LG("sha256").update(BY).digest("base64")}'`,VO='await import("/refresh.js").catch(()=>{});await import("/@vite/client").catch(()=>{});',FO="gemi-static";function MG($,Z,J,W,Y,j){let z=new Set,X=[];if(J)X=Z.islands.map((U)=>{let O=U.module?J(U.module):void 0;if(!O)return console.error(`[gemi] island ${U.module??"(unknown module)"}: no client build entry. Declare it as island(() => import("./Component")) so gemi's Vite plugin builds it.`),null;if(U.load==="eager"){for(let L of O.preload)z.add(L);if(U.preloadDynamic)for(let L of O.dynamicPreload??[])z.add(L)}return{s:O.src,e:U.export,l:U.load}});let Q=X.some((U)=>U!==null),G=j?`<script type="module" ${OG}="${MY(j.name)}">${j.source}</script>`:"";if(!Q&&!Y)return LY($,"</head>",G,!1);let V=(Y?`<meta name="${FO}" content="${MY(Y.identity)}"${Y.prefetch==="none"?' data-prefetch="none"':""}/>`:"")+[...z].map((U)=>`<link rel="modulepreload" href="${MY(U)}"/>`).join("")+G,K=Y?BY:HY,F=Q?GG(Z):void 0,D=(Q?`<script type="application/json" id="${KO}">${r0({i:X})}</script>`:"")+(F?`<script type="application/json" id="${BO}">${r0(F)}</script>`:"")+`<script type="module">${W?VO+K:K}</script>`;return LY(LY($,"</head>",V,!1),"</body>",D,!0)}function UO($,Z){let J=/<(\/?)template\b[^>]*>/gi;J.lastIndex=Z;let W=0;for(let Y=J.exec($);Y;Y=J.exec($))if(W+=Y[1]?-1:1,W===0)return J.lastIndex;return-1}function HG($){let Z=`<template ${BG}="`;for(let J=$.lastIndexOf(Z);J!==-1;J=$.lastIndexOf(Z)){let W=UO($,J);if(W===-1)break;let Y=J+Z.length,j=$.slice(Y,$.indexOf('"',Y)),z=$.indexOf(">",Y)+1,X=$.slice(z,W-11);$=$.slice(0,J)+$.slice(W);let Q=`<${n3} ${KG}="${j}" style="display:contents"></${n3}>`;$=$.split(Q).join(`<${n3} style="display:contents">${X}</${n3}>`)}return $}function PY($){if(!$)return{locale:!0,session:!0,csrf:!0};return{locale:!1,session:$.session===!0,csrf:$.csrf===!0}}function TG($,Z){if($.getSetCookie().length>0){if(Z.cacheControl&&Bun.env.NODE_ENV!=="production")console.warn(`[gemi] A static view with cacheControl "${Z.cacheControl}" set a cookie, so it was sent "private, no-store" instead. Static pages are cacheable only when nothing on them sets a cookie.`);$.set("Cache-Control","private, no-store");return}if(Z.cacheControl&&!$.has("Cache-Control"))$.set("Cache-Control",Z.cacheControl)}function DO($){let Z=$.headers.get("Cache-Control")?.toLowerCase()??"";return/(^|[\s,])(public|s-maxage)\b/.test(Z)}var PG=new Set;function NG($,Z){if(!DO($)||$.headers.getSetCookie().length===0)return $;if(Bun.env.NODE_ENV!=="production"&&!PG.has(Z))PG.add(Z),console.warn(`[gemi] The file route "${Z??""}" set a cookie on a response with Cache-Control "${$.headers.get("Cache-Control")}", so the cookie was not sent: a shared cache would hand it to every visitor. Make the response private, or set the cookie elsewhere.`);try{return $.headers.delete("Set-Cookie"),$}catch{let J=new Headers($.headers);return J.delete("Set-Cookie"),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}var OO=async()=>(await import("./chunk-8tzmat5s.js")).default,TY,o3=async(...$)=>{return TY??=import("react-dom/server.browser").catch((Z)=>{throw TY=void 0,Z}),(await TY).renderToReadableStream(...$)},IG=1e4,xG="no-locale",LO="no-theme";async function MO($,Z,J){let W=`${J==="italic"?"italic,":""}wght@${J==="italic"?"1,":""}${Z}`,z=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${W}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(z).then((X)=>X.arrayBuffer())}var CY="/assets";function HO($){return $===CY||$.startsWith(`${CY}/`)}function PO($){let Z=$.filter(HO);if(Z.length>0){let J=Z.length>1;throw Error(`View route path${J?"s":""} ${Z.map((W)=>`"${W}"`).join(", ")} use${J?"":"s"} the reserved "${CY}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else, or set \`assetRoutes: true\` on these views' config (route.view or a route.domains group's view).`)}}function TO($){let Z=M(Q1).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function NY($){let{status:Z=400,error:J,body:W,...Y}=$;return new Response(W??J?.message,{...Y,status:Z})}function NO($){let{status:Z=400,data:J,directive:W,headers:Y}=$;return new Response(JSON.stringify({data:J,directive:W}),{headers:Y,status:Z})}class a3{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];requiredViews={};staticRoutes=[];root=null;shellReporter=jG();preloadCache=new WeakMap;hooks;partialRendering;localeRouting;detectLocale;theme;defaultMeta;notFound;publicFiles;assetRoutes;translate;constructor($,Z={}){let J=SQ();if(this.partialRendering=$.partialRendering??J.partialRendering,this.localeRouting=$.localeRouting??J.localeRouting,this.detectLocale=$.detectLocale,this.detectLocale&&this.localeRouting!=="off")throw Error('`view.detectLocale` needs `view.localeRouting: "off"`: on locale-routed views the URL, the `i18n-locale` cookie and `Accept-Language` decide the locale. A `route.domains` group that inherits it and keeps locale routing can set `detectLocale: undefined`.');this.theme=$.theme??J.theme,this.defaultMeta=$.meta,this.notFound=$.notFound,this.publicFiles=$.publicFiles??J.publicFiles,this.assetRoutes=$.assetRoutes??J.assetRoutes,this.translate=$.translate,this.hooks={onNotFound:$.onNotFound??J.onNotFound,onRequestStart:$.onRequestStart??J.onRequestStart,onRequestEnd:$.onRequestEnd??J.onRequestEnd,onRequestFail:$.onRequestFail??J.onRequestFail,onStreamComplete:$.onStreamComplete??J.onStreamComplete};let W={"/":$.rootRouter,"/auth":PQ(Z)};if(this.requiredViews=Object.fromEntries(MQ(Z).map(({view:Y,requiredBy:j})=>[Y,j])),this.flatViewRoutes=l4(W),!this.assetRoutes)PO(Object.keys(this.flatViewRoutes));this.routeManifest=s4(W),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,Y])=>Y.at(-1)!=="FILE")),this.componentTree=o4(W),this.flatComponentTree=QY(this.componentTree),this.staticRoutes=Object.entries(this.flatViewRoutes).filter(([,Y])=>Y.static).map(([Y])=>Y);for(let Y of this.staticRoutes){let j=this.flatViewRoutes[Y].static?.layout;if(j&&!this.flatComponentTree.includes(j))this.flatComponentTree.push(j)}if(this.notFound){for(let Y of[this.notFound.view,this.notFound.static?.layout])if(Y&&!this.flatComponentTree.includes(Y))this.flatComponentTree.push(Y)}this.root=$.root}async passesFeatureGates($){let Z=M(Y$);for(let J of $)if(!await Z.enabled(J))return!1;return!0}async onRequestEnd($,Z={}){if(Z.mintSession!==!1)r4();return await this.hooks.onRequestEnd($)}completeStream($,Z){let J=(W)=>{ZZ.error(W?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(W)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(J)}catch(W){J(W)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:J,views:W,routeKey:Y}=$,j=()=>{let Q=new Set(Z?.preload??[]);for(let G of W)for(let B of J?.[G]??[])Q.add(B);return[...Q].map((G)=>u1("link",{key:`modulepreload:${G}`,rel:"modulepreload",href:G}))};if(!J)return j();let z=this.preloadCache.get(J);if(!z||z.clientEntry!==Z)z={clientEntry:Z,byRoute:new Map},this.preloadCache.set(J,z);let X=z.byRoute.get(Y);if(!X)X=j(),z.byRoute.set(Y,X);return X}async renderStatic($){let{req:Z,runInRequestScope:J,staticView:W,currentViews:Y,data:j,serverQueries:z,headers:X}=$,Q;if(W.layout){if(Q=$.viewImportMap[W.layout],!Q)throw Error(`The static layout "${W.layout}" was not found. It is a view path: a file at app/views/${W.layout}.tsx whose default export renders the document.`)}let G=await $.getStyles(Y,{static:!0,layout:W.layout});z.markRenderStart();let B=xY(),V=new AbortController,K=setTimeout(()=>V.abort(),IG),F=(U)=>{if(Bun.env.NODE_ENV!=="production")console.error(U)},D=QG(async(U,O)=>{let L=await o3(U,{signal:V.signal,identifierPrefix:O,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});return await L.allReady.catch(()=>{}),await new Response(L).text()},{currentLocale:j?.i18n?.currentLocale,defaultLocale:j?.i18n?.defaultLocale,timeZone:j?.i18n?.timeZone});try{let U,O=typeof W.script==="function"?await J(()=>W.script(Z)):W.script;if(O)U={name:O,source:await OY(O)};let L;if(W.navigation){let I=W.navigation===!0?{}:W.navigation,E=I.version?String(await J(()=>I.version(Z))):"";L={identity:[W.layout??"",$.buildId??"",U?.name??"",E].join("|"),prefetch:I.prefetch==="none"?"none":"intent"}}let P=await o3(u1(VG.Provider,{value:D,children:u1(_G,{children:[...G,u1(this.root,{data:j,viewImportMap:$.viewImportMap,viewModules:$.viewModules,serverQueries:z,dictionarySink:B,rootLayout:Q,key:"root"})]})}),{signal:V.signal,progressiveChunkSize:Number.MAX_SAFE_INTEGER,onError:F});await P.allReady.catch(()=>{});let H=HG(await new Response(P).text());return new Response(MG(H,D,$.resolveIsland,Bun.env.NODE_ENV!=="production",L,U),{status:$.status,headers:X})}finally{clearTimeout(K),J(()=>this.completeStream(Z,z.summarize(V.signal.aborted)))}}async render($){let{req:Z,runInRequestScope:J,csrfTokenHMAC:W,currentPathName:Y,headers:j,i18n:z,params:X,pathname:Q,serverQueries:G,userAgent:B,noStream:V,noTheme:K,url:F,user:D,viewData:U,breadcrumbs:O,urlLocaleSegment:L,meta:P,isOgRequest:H,appId:I,features:E,staticView:S}=$,R=this.theme===!1||K||S?null:{cookie:this.theme.cookie??lW,default:this.theme.default??null,value:_O(Z,this.theme.cookie??lW)},k=L?WG(Q,[L]).pathname:Q,N={kind:"view",data:{meta:P,pageData:{[k]:U},__csrf:W.toString("base64"),prefetchedData:{},i18n:z,auth:{user:D},routeManifest:this.clientRouteManifest,breadcrumbs:O,router:{urlLocaleSegment:L,pathname:Y,params:X,currentPath:Q,searchParams:F.search,is404:!Y?!0:!1,domain:Z.domain?TO(Z):null},appId:I,features:E,theme:R,componentTree:[["404",[]],...this.componentTree],...this.staticRoutes.length>0?{staticRoutes:this.staticRoutes}:{}},head:{}},v=this.root,_=this.routeManifest[Y];return async(f)=>{let{bootstrapModules:H0=[],loaders:Z3,getStyles:i1,viewImportMap:C1,cssManifest:i,ogMap:y,viewModules:r,clientEntry:A1,modulePreloadManifest:J3,assetBase:jZ,resolveIsland:o0,buildId:G1}=f,x$=A1?[]:H0,s1=(p)=>[p,`window.loaders=${Z3}`,...A1?[`import(${JSON.stringify(A1.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(H){let p=null,u0=null;for(let A of _??[])if(typeof y[A]==="function")u0=A,p=y[A];if(!p)return new Response("Not found",{status:404});let W3=Object.values(N.data.pageData)[0];try{await o3(u1(p,W3[u0]),{onError:()=>{}})}catch(A){let{fonts:t,...a1}=A.satoriOptions,e3=await Promise.all(t.map(($6)=>{return MO($6.name,$6.weight,$6.style).then((kK)=>({...$6,data:kK}))})),W5=new Headers(j);W5.set("Content-Type","image/png");let[EK,bK]=await Promise.all([OO(),d4("Rendering an OG image")]),RK=await EK(A.jsx,{...a1,fonts:e3}),fK=await bK(Buffer.from(RK)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array(fK),{headers:W5})}return new Response("data")}if(S&&Y)return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:_,data:N.data,serverQueries:G,headers:j,getStyles:i1,viewImportMap:C1,viewModules:r,resolveIsland:o0,buildId:G1,status:200});if(S&&!Y&&this.notFound){let p=this.notFound.view;if(!C1[p])throw Error(`The not-found view "${p}" (route.view.notFound) was not found. It is a view path: a file at app/views/${p}.tsx.`);return await this.renderStatic({req:Z,runInRequestScope:J,staticView:S,currentViews:[p],data:N.data,serverQueries:G,headers:j,getStyles:i1,viewImportMap:{...C1,"404":C1[p]},viewModules:r&&{...r,"404":r[p]},resolveIsland:o0,buildId:G1,status:$.refusedStatus??404})}if(N.data.cssManifest=i,N.data.modulePreloadManifest=J3??{},jZ&&jZ!=="/")N.data.assetBase=jZ;if(G1&&G1!=="dev")N.data.buildId=G1;let j0=this.modulePreloadLinks({clientEntry:A1,modulePreloadManifest:J3,views:_??["404"],routeKey:Y??"404"}),U8=await i1(_??["404"]);N.data.prefetchedData=G.snapshotResolved(),G.markRenderStart();let C$=new AbortController,n1=setTimeout(()=>C$.abort(),IG),o1=T6(B)||V,zZ=Bun.env.NODE_ENV!=="production"&&!o1&&Y&&this.shellReporter.shouldObserve(Y)?zG():null,A$=xY();try{let p=await o3(u1(_G,{children:[...j0,...U8,...R?[u1("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:fQ(r0({cookie:R.cookie,default:R.default}))}})]:[],u1(v,{data:N.data,viewImportMap:C1,viewModules:r,serverQueries:G,dictionarySink:A$,key:"root"})]}),{bootstrapScriptContent:s1(`window.__GEMI_DATA__ = ${r0(N.data)}`),bootstrapModules:x$,signal:C$.signal,...o1?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(u0){if(Bun.env.NODE_ENV!=="production")console.error(u0)}});if(p.allReady.catch(()=>{}).finally(()=>clearTimeout(n1)),o1)await p.allReady.catch(()=>{});return new Response(a8(p,G,{onShell:o1?void 0:()=>G.markShell(),onChunk:zZ?.onChunk,onClose:()=>J(()=>{if(this.completeStream(Z,G.summarize(C$.signal.aborted)),zZ)this.shellReporter.report(Y,zZ.measure())})},A$),{status:!Y?$.refusedStatus??404:200,headers:j})}catch(p){if(clearTimeout(n1),Bun.env.NODE_ENV==="production")throw J(()=>this.completeStream(Z,G.summarize(C$.signal.aborted))),p;let u0=await o3(u1("div"),{bootstrapScriptContent:s1(`window.error= ${r0(p.message)}; window.stack_trace=${r0(p.stack)};window.__GEMI_DATA__ = ${r0(N.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...x$]:x$});return new Response(a8(u0,G,{onClose:()=>J(()=>this.completeStream(Z,G.summarize(C$.signal.aborted)))}),{status:!Y?$.refusedStatus??404:200,headers:j})}}}viewRefusalStatus($,Z,J){if(E$(Z))return 404;if(Z?.kind===$$){let W=Z.payload?.view?.status;return W===403||W===404?W:null}if(Z$(Z)){if(!J.has(Z))this.hooks.onRequestFail($,Z);return console.error(Z),403}if(Z instanceof d1&&(Z.status===403||Z.status===404))return Z.status;return null}async handleViewRequest($,Z){let J=new URL($.url),W=J.pathname.endsWith(".json"),Y=J.pathname.endsWith(".og"),j=J.pathname.replace(".json","").replace(".og",""),[,z,...X]=j.split("/"),Q=j,G=null,B=null,V=M(c),K=i3(this.flatViewRoutes,j),F=V.isLocaleAware&&this.localeRouting==="prefix"&&!K?.route.middleware.includes(xG);if(F&&V.supportedLocales.includes(z))Q=`/${X.join("/")}`,G=z,B=z;if(($.method==="GET"||$.method==="HEAD")&&!W&&!Y&&K===null&&J.pathname.endsWith("/")&&!J.pathname.startsWith("//")){let _=J.pathname.replace(/\/+$/,""),f=F&&V.supportedLocales.includes(_.slice(1));if(_&&!f)return new Response("",{status:301,headers:{Location:`${_}${J.search}`}})}if(F&&!Y&&B===null&&!(B===null&&K!==null)){let _=_Y(z,V.supportedLocales,V.defaultLocale);if(_){let f=X.length?`/${X.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${f}${W?".json":""}${J.search}`}})}}if(F&&!Y){let _=M(c).detectLocale(new C($,{},"view",Q));if(B===null&&_!==V.defaultLocale){let f=J.pathname==="/"?"":J.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${_}${f}${J.search}`}})}}Q=Q.replace("//","/");let U=[],O=[],L=null,P={},H=null,I=!1,E=!1,S=[],R,k=!1,N=!1;try{let _=i3(this.flatViewRoutes,Q);if(B&&_?.route.middleware.includes(xG))_=null;if(_){if(k=!0,L=_.routePath,P=_.params,U=_.route.exec,O=_.route.middleware,S=_.route.features,I=O.includes("no-stream"),E=O.includes(LO),R=_.route.static,N=_.route.segments.at(-1)?.viewPath==="FILE",W&&this.partialRendering){let f=$.headers.get(XY),H0=JG({flatViewRoutes:this.flatViewRoutes,supportedLocales:M(c).supportedLocales,from:f,origin:J.origin,to:{segments:_.route.segments,params:P,search:J.search}});if(H0.startIndex>0)U=U.slice(H0.startIndex),H={from:f,carriedViews:H0.carriedViews}}}}catch(_){throw _}if(R&&W)return new Response("Not found",{status:404});let v=new C($,P,"view",L);return this.hooks.onRequestStart(v),await T.run(v,async()=>{let _=null,f=T.getStore(),H0=rZ.getStore(),Z3=(y)=>rZ.run(H0,()=>T.runWith(f,y));f.serverQueries=new oZ(s3($));let i1=new Set;f.serverQueries.onQueryFail((y)=>{i1.add(y.error);try{Z3(()=>Promise.resolve(this.hooks.onRequestFail(i,y.error)).catch(()=>{}))}catch{}});let C1=PY(N?{}:R??(L===null&&!W?this.notFound?.static:void 0));if(B){let y=B.replaceAll("/","");I$.setLocale(y,{cookie:C1.locale})}else if(V.isLocaleAware&&!F)f.setLocale(V.defaultLocale);else I$.setLocale(void 0,{cookie:C1.locale});let i=f.req;if(C1.session)r4();try{let y=null;if(this.detectLocale&&!F&&M(c).isLocaleAware){let{supportedLocales:A,defaultLocale:t}=M(c),a1=await this.detectLocale(i,{supportedLocales:A,defaultLocale:t}),e3=typeof a1==="string"?_Y(a1,A,t):null;if(e3)f.setLocale(e3)}try{await M(e1).runMiddleware(O)}catch(A){if(y=this.viewRefusalStatus(i,A,i1),y===null)throw A}if(y!==null||S.length>0&&!await this.passesFeatureGates(S))L=null,U=[],i.routePath="";let r=M(c),A1=r.isEnabled,J3=r.isLocaleAware,jZ=new C($,i.params),o0={defaultLocale:r.defaultLocale,timeZone:r.detectTimeZone(jZ)};if(J3){let A=null;if(B)A=B.replaceAll("/",""),f.setLocale(A);else if(!F)A=f.locale??r.defaultLocale;else A=r.detectLocale(jZ),f.setLocale(A);let t=A1?r.getPageTranslations(A,i.routePath):{};o0={...o0,supportedLocales:r.supportedLocales,currentLocale:A,dictionary:{[A]:t},defaultLocale:r.defaultLocale,...F?{}:{localeRouting:"off"}}}await IY(o0.currentLocale??"");let G1;try{G1=await Promise.all(U.map((A)=>A(i)))}catch(A){if(y=this.viewRefusalStatus(i,A,i1),y===null)throw A;L=null,U=[],i.routePath="",G1=[]}let x$=void 0;if(L===null){if(x$=await this.hooks.onNotFound(i,{status:y??404}),J3&&!F&&f.locale&&f.locale!==o0.currentLocale){let A=f.locale;o0={...o0,currentLocale:A,dictionary:{[A]:A1?r.getPageTranslations(A,i.routePath):{}}},await IY(A)}}if(this.defaultMeta&&!f.metadata.hasAllDefaultFields)f.metadata.applyDefaults(typeof this.defaultMeta==="function"?await this.defaultMeta(i):this.defaultMeta);if(this.translate!==void 0)f.metadata.applyTranslateDefault(this.translate);let{cookies:s1,headers:j0}=f;if(y!==null)j0.set("Cache-Control","no-store");_={data:G1,cookies:s1,headers:j0,user:f.user,prefetchedData:f.serverQueries.snapshotResolved(),currentPathName:L,params:i.params,urlLocaleSegment:G,meta:f.renderMeta(),appId:M(GY).id,features:await M(Y$).forClient()};let{params:U8,user:C$}=_,n1={},o1={};for(let A of G1??[]){let[t,a1]=Object.entries(A)?.[0]??[];if(!t||!a1)continue;o1[`${t}:${L}`]=a1.breadcrumb,n1[t]=a1}let zZ=L===null&&this.notFound&&!W?this.notFound.static:void 0;if(zZ&&x$)n1["404"]=x$;let A$=n1.FILE;if(A$){try{await this.onRequestEnd(i,{mintSession:!1})}catch(t){ZZ.error(t?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(t)})}let A;if(A$ instanceof Response)A=e4(A$,j0,s1);else{for(let t of s1)j0.append("Set-Cookie",t.toString());A=await A8(A$,j0)}return NG(A,L)}if(W){j0.set("Content-Type","application/x-ndjson; charset=utf-8"),j0.append("Vary",XY),s1.forEach((t)=>j0.append("Set-Cookie",t.toString())),await this.hooks.onRequestEnd(i);let A={meta:H&&!f.metadata.touched?null:_.meta,data:{[Q]:n1},breadcrumbs:o1,prefetchedData:f.serverQueries.snapshotResolved(),i18n:o0,features:_.features,is404:!L,appId:_.appId,partial:H};return new Response(XG(A,f.serverQueries,void 0,({aborted:t})=>Z3(()=>this.completeStream(i,f.serverQueries.summarize(t)))),{headers:j0})}j0.set("Content-Type","text/html; charset=utf-8");let p=L?R:zZ,u0=Boolean(p),W3=PY(p);if(!I&&!u0)j0.append("Vary","User-Agent");if(!u0||W3.session)r4();for(let A of s1)j0.append("Set-Cookie",A.toString());if(!u0||W3.csrf){let A=Bun.CSRF.generate(process.env.SECRET);j0.append("Set-Cookie",`csrf_token=${A}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`)}try{await this.onRequestEnd(i,{mintSession:!u0||W3.session})}catch(A){ZZ.error(A?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(A)})}if(u0&&(L||!k))TG(j0,p);return await this.render({req:i,runInRequestScope:Z3,csrfTokenHMAC:Buffer.from(""),currentPathName:L,headers:j0,i18n:o0,params:U8,pathname:J.pathname,serverQueries:f.serverQueries,userAgent:$.headers.get("user-agent"),noStream:I,noTheme:E,url:J,user:C$,viewData:n1,breadcrumbs:o1,urlLocaleSegment:G,meta:_.meta,appId:_.appId,features:_.features,isOgRequest:Y,staticView:p,refusedStatus:y??void 0})}catch(y){if(y.kind===$$){let r=W?NO(y.payload.viewData??y.payload.api):NY(y.payload.view);for(let A1 of f.cookies)r.headers.append("Set-Cookie",A1.toString());return r}if(!i1.has(y))this.hooks.onRequestFail(i,y);if(Z$(y))return console.error(y),W?aZ():NY(KY());if(y instanceof d1&&y.status===403)return W?aZ():NY(KY());throw y}},Z)}}function _O($,Z){let J=$.cookies?.get(Z);return RQ(J)?J:null}function AY(){let $=JSON.stringify({error:J$("not_found","Not found",404)});return new Response($,{status:404,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}class EG extends C0{routes={"/api-routes":this.get(()=>{let $=M($8).flatRoutes,Z=[];for(let[J,W]of Object.entries($))for(let[Y,j]of Object.entries(W)){let{exec:z,middleware:X}=j;Z.push({path:J,method:Y,middleware:X})}return Z}),"/view-routes":this.get(()=>{let $=M(a3).flatViewRoutes,Z=[];for(let[J,{middleware:W,viewPath:Y}]of Object.entries($))Z.push({path:J,method:"GET",viewPath:Y,middleware:W});return Z})}}var IO=new Set([t1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),xO=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,CO=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function AO($,Z,J,W){for(let[Y,j]of Object.entries(J.headers??{})){if(j===void 0||j===null)continue;let z=Y.toLowerCase();if(IO.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${Y}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);if(W&&z==="authorization")throw Error(`dispatchAs: credentials may not set "Authorization" on a call dispatched as an identity. The caller's token is for the MCP endpoint and is never passed on.`);$.set(Y,j)}for(let[Y,j]of Object.entries(J.cookies??{})){if(j===void 0||j===null)continue;if(Y===t1)throw Error(`dispatchAs: credentials may not set the "${t1}" cookie. The access token stays the initiator's.`);if(!xO.test(Y)||!CO.test(j))throw Error(`dispatchAs: "${Y}" is not a cookie a Cookie header can carry.`);Z.push(`${Y}=${j}`)}}function SO($,Z){let J=$.body.getReader(),W=!1,Y=()=>{if(W)return;W=!0;try{Z()}catch(z){console.error(z)}},j=new ReadableStream({async pull(z){let X;try{X=await J.read()}catch(Q){Y(),z.error(Q);return}if(X.done){Y();try{z.close()}catch{}return}try{z.enqueue(X.value)}catch{}},async cancel(z){try{await J.cancel(z)}finally{Y()}}},{highWaterMark:0});return new Response(j,{status:$.status,statusText:$.statusText,headers:$.headers})}function CG($){let{status:Z=400,data:J,headers:W}=$,Y=new Headers({"Content-Type":"application/json",...W});if(!Y.has("Cache-Control"))Y.set("Cache-Control","no-store");return new Response(JSON.stringify(J),{status:Z,headers:Y})}function e4($,Z,J){let W=[];Z?.forEach((z,X)=>W.push([X,z]));let Y=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(J??[])];if(W.length===0&&Y.length===0)return $;let j=(z)=>{for(let[X,Q]of W){if(X.toLowerCase()==="set-cookie")continue;if(!z.has(X))z.set(X,Q)}for(let X of Y)z.append("Set-Cookie",X)};try{return j($.headers),$}catch{let z=new Headers($.headers);return j(z),new Response($.body,{status:$.status,statusText:$.statusText,headers:z})}}function EO(){return Bun.env.NODE_ENV==="development"}class $8{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=AQ();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=cW({"/":$.rootRouter,"/auth":yW,"/__gemi__/services/i18n":vW,"/__gemi__/services/image":hW,...EO()?{"/__gemi__/services/logs":pW,"/__gemi__/debug":EG}:{}})}getRouteHandlerAndParams($){let Z=new URL($.url),J=SG(Z.pathname),W={},Y;for(let[j]of Object.entries(this.flatRoutes))try{let z=new URLPattern({pathname:j});if(z.test({pathname:J})){Y=j,W=z.exec({pathname:J})?.pathname.groups;break}}catch(z){console.error(z)}return{params:W,path:Y}}async runRouteMiddleware($,Z){let W=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await M(e1).runMiddleware(W)}catch(Y){if(Y.kind===$$)return CG(Y.payload.api);else{if(E$(Y))return AY();if(this.onRequestFail(Z,Y),console.error(Y),Z$(Y))return aZ();throw Y}}}async getRouteData($){let Z=this.flatRoutes[$],J=T.getStore(),W=Z[J.req.rawRequest.method].exec??(()=>Promise.resolve({})),Y={};try{Y=await W()}catch(j){if(j.kind===$$)return CG(j.payload.api);if(E$(j))return AY();if(this.onRequestFail(J.req,j),console.error(j),Z$(j))return aZ();throw j}return Y}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,J){let W=async()=>{try{if(!this.isFrameworkRoute(J))await this.onRequestEnd(Z)}catch(Y){ZZ.error(Y?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(Y)})}finally{$.destroy()}};if(!$.hasPendingWork()){await W();return}$.whenIdle().then(W).catch((Y)=>{console.error(Y)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:J,path:W}=this.getRouteHandlerAndParams($),Y=this.flatRoutes[W];if(!Y||!Y[$.method])return new Response(JSON.stringify({error:J$("not_found","Not found",404)}),{status:404});let j=new C($,J,"api",W);if(!this.isFrameworkRoute(W))this.onRequestStart(j);return await T.run(j,async()=>{let z=T.getStore(),X=!1,Q=async()=>{X=!0,await this.endRequest(z,j,W)};try{let G=M(c);if(G.isEnabled){let U=G.detectLocale(j);z.setLocale(U)}z.setRequest(j),M(e1).applyDefaultBodyLimit($);let B=await this.runRouteMiddleware(W,j);if(B instanceof Response){let U=e4(B,z.headers,z.cookies);return await Q(),U}let V=await this.getRouteData(W),K=z.headers,F=z.cookies;if(V instanceof Response){let U=e4(V,K,F);if(this.isOpenEndedBody($,U)){let O=SO(U,()=>this.endRequest(z,j,W));return X=!0,O}return await Q(),U}let D=(r1(V)?V:K1.json(V)).toResponse(K,F);return await Q(),D}catch(G){if(!X)try{await Q()}catch(B){console.error(B)}throw G}},Z)}async dispatchAs($,Z,J,W,Y){let j=new URL($.rawRequest.url).origin,z=new URL(`${j}/api${J}`),X=`/api${J.split(/[?#]/)[0]}`;if(!J.startsWith("/")||z.origin!==j||z.pathname!==X||z.hash!==""||z.pathname.startsWith("/api/__gemi__")||z.pathname==="/api/auth"||z.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${J}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Q=Y?.identity;if(Q!==void 0&&(typeof Q!=="object"||!Q?.user))throw Error("dispatchAs: identity needs the user to dispatch as.");let G=new Headers,B=[],V=Q?null:$.cookies.get(t1);if(V)B.push(`${t1}=${V}`);if(Y?.credentials)AO(G,B,Y.credentials,Q!==void 0);if(B.length>0)G.set("Cookie",B.join("; "));let K=Q?null:$.headers.get(t1);if(K)G.set(t1,K);let F=$.headers.get("User-Agent");if(F)G.set("User-Agent",F);let D;if(W instanceof FormData)D=W;else if(W!==void 0)G.set("Content-Type","application/json"),D=JSON.stringify(W);let U=new Request(z,{method:Z,headers:G,body:D,...Y?.signal?{signal:Y.signal}:{}});if(AG(U,VZ($),Q?.grant,Y?.progress),$.domain)tZ(U,$.domain);let O=Q?{user:Q.user}:void 0;return T.exit(()=>X6.exit(()=>this.handleApiRequest(U,O)))}}import{timingSafeEqual as bO}from"crypto";var W8="",bY="*",RO=60000,fO=1e4,Z8=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,J8=16,SY=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,EY="x-forwarded-host";function RG($){return $.startsWith(":")}function r3($,Z){if($===null)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return J.length===W.length&&bO(J,W)}function kO($){if(!$)return[];if($===!0)return[{header:EY,clientIpHeader:null,secret:null}];let Z=Array.isArray($)?$:[$],J=Array.isArray($)?null:EY;return Z.map((W)=>({header:W.hostHeader?.toLowerCase()??J,clientIpHeader:W.clientIpHeader?.toLowerCase()??null,secret:W.secret?{header:W.secret.header.toLowerCase(),value:W.secret.value}:null}))}function wO($){if(!$||$===!0)return;if(!Array.isArray($)){bG($,"route.domains.trustProxy",EY);return}if($.length===0)throw Error("`route.domains.trustProxy` is an empty list. List at least one proxy, or leave `trustProxy` out.");let Z=new Map;$.forEach((J,W)=>{let Y=`route.domains.trustProxy[${W}]`;if(typeof J!=="object"||J===null||Array.isArray(J))throw Error(`\`${Y}\` must be an object: { hostHeader?, clientIpHeader?, secret }. \`true\` is only accepted on its own.`);if(!J.secret)throw Error(`\`${Y}.secret\` is required: in a list, each proxy proves itself with a secret of its own.`);if(J.hostHeader===void 0&&J.clientIpHeader===void 0)throw Error(`\`${Y}\` names neither \`hostHeader\` nor \`clientIpHeader\`, so it would trust nothing.`);bG(J,Y,null);let j=Z.get(J.secret.value);if(j!==void 0)throw Error(`\`${Y}.secret.value\` is the same as \`route.domains.trustProxy[${j}].secret.value\`. Give each proxy a secret of its own.`);Z.set(J.secret.value,W)})}function bG($,Z,J){let{hostHeader:W,clientIpHeader:Y,secret:j}=$;if(W!==void 0&&(typeof W!=="string"||!SY.test(W)))throw Error(`\`${Z}.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(W)}.`);let z=(W??J)?.toLowerCase()??null;if(Y!==void 0){if(typeof Y!=="string"||!SY.test(Y))throw Error(`\`${Z}.clientIpHeader\` must be a single header name, e.g. "x-client-ip". Got ${JSON.stringify(Y)}.`);if(!j)throw Error(`\`${Z}.clientIpHeader\` needs \`secret\`: without proof the proxy sent it, any client that reaches the app directly picks its own address.`);if(Y.toLowerCase()===z)throw Error(`\`${Z}.clientIpHeader\` names the same header as \`hostHeader\`.`);if(typeof j.header==="string"&&Y.toLowerCase()===j.header.toLowerCase())throw Error(`\`${Z}.clientIpHeader\` names the same header as \`secret.header\`.`)}if(!j)return;if(typeof j.header!=="string"||!SY.test(j.header))throw Error(`\`${Z}.secret.header\` must be a header name. Got "${j.header}".`);if(j.header.toLowerCase()===z)throw Error(`\`${Z}.secret.header\` names the same header as \`hostHeader\`; the secret needs a header of its own.`);if(typeof j.value!=="string"||j.value.length<J8)throw Error(`\`${Z}.secret.value\` must be at least ${J8} characters. A guessable one lets any client name its own host.`)}function _1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function qO($){try{let Z=new URL(`http://${$.trim()}`),J=Z.hostname.toLowerCase().replace(/\.$/,"");return J?Z.port?`${J}:${Z.port}`:J:null}catch{return null}}function fG($){if($===void 0)return[];if($===!0)return!0;if(!Array.isArray($))throw Error(`\`route.domains.devHosts\` must be a list of hostnames (or \`true\`). Got ${JSON.stringify($)}.`);return $.map((Z,J)=>{let W=typeof Z==="string"?Z.trim().toLowerCase():"",Y=W.startsWith(".")?W.slice(1):W;if(!Y||!Y.split(".").every((j)=>Z8.test(j)))throw Error(`\`route.domains.devHosts[${J}]\` must be a bare hostname, e.g. "app.acme.test", or ".acme.test" for the domain and its subdomains \u2014 no scheme, port, path or "*". Got ${JSON.stringify(Z)}.`);return W})}function yO($){let Z=_1($.root),J=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==J||!Z.split(".").every((j)=>Z8.test(j)))throw Error(`\`route.domains.root\` must be a bare hostname, e.g. "example.com" \u2014 no scheme, port or path. Got "${$.root}".`);if($.custom&&($.custom.cacheTtlMs??0)<0)throw Error(`\`route.domains.custom.cacheTtlMs\` is ${$.custom.cacheTtlMs}; it cannot be negative. Use 0 to disable the cache.`);if($.ask&&$.ask.secret.length<J8)throw Error(`\`route.domains.ask.secret\` must be at least ${J8} characters. A guessable one is worse than leaving \`ask\` out.`);wO($.trustProxy),fG($.devHosts);let W=new Set,Y=null;for(let j of $.groups??[]){let{subdomain:z}=j;if(W.has(z))throw Error(`\`route.domains\` declares the subdomain "${z}" twice.`);if(W.add(z),RG(z)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(z))throw Error(`"${z}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(Y)throw Error(`\`route.domains\` declares two param subdomains, "${Y.subdomain}" and "${z}"; a host could match either.`);Y=j;continue}if(j.exists)throw Error(`The subdomain "${z}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!z.split(".").every((X)=>Z8.test(X)))throw Error(`"${z}" is not a valid subdomain.`)}if($.custom&&!W.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&Y&&!Y.exists)throw Error(`\`route.domains.ask\` is set, so "${Y.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class RY{root;devHosts;hostTrusts;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeaders;constructor($){yO($),this.root=_1($.root),this.devHosts=fG($.devHosts),this.hostTrusts=kO($.trustProxy);for(let Z of $.groups??[])if(RG(Z.subdomain))this.param={...Z,name:Z.subdomain.slice(1)};else this.fixed.set(Z.subdomain.toLowerCase(),Z);this.custom=$.custom??null,this.cacheTtlMs=this.custom?.cacheTtlMs??RO,this.askSecret=$.ask?.secret??null,this.proxySecretHeaders=Array.from(new Set(this.hostTrusts.flatMap((Z)=>Z.secret?[Z.secret.header]:[])))}trustOf($){let Z=null;for(let J of this.hostTrusts)if((!J.secret||r3($.headers.get(J.secret.header),J.secret.value))&&!Z)Z=J;return Z}forwardedHost($){let Z=this.trustOf($)?.header;if(!Z)return null;return $.headers.get(Z)?.split(",")[0]?.trim()||null}trustedClientIp($){let Z=this.trustOf($);if(!Z?.clientIpHeader||!Z.secret)return null;let J=$.headers.get(Z.clientIpHeader)?.split(",")[0];return J===void 0?null:R$(J)}applyClientIp($){let Z=this.trustedClientIp($);if(!Z)return;$.headers.set("x-forwarded-for",Z),$.headers.delete("x-real-ip")}hostOf($){return _1(this.forwardedHost($))??_1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),J=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),W=J==="http"||J==="https"?J:Z.protocol.replace(/:$/,""),Y=this.forwardedHost($),j=Y&&_1(Y)?qO(Y):null;return`${W}://${j??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let J=await this.match(Z,$);if(J)return J;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:bY,params:{},custom:!0};return null}async allows($,Z){let J=_1($);return J?await this.match(J,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:W8,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let W=$.slice(0,-(this.root.length+1)),Y=this.fixed.get(W);if(Y)return{host:$,group:Y.subdomain,params:{},custom:!1};if(this.param&&Z8.test(W)){let j={[this.param.name]:W};if(this.param.exists&&!await this.param.exists(j,Z))return null;return{host:$,group:this.param.subdomain,params:j,custom:!1}}return null}if(!this.custom)return null;let J=await this.resolveCustom($);return J?{host:$,group:this.custom.group,params:J,custom:!0}:null}async resolveCustom($){let Z=Date.now(),J=this.cache.get($);if(J&&J.expiresAt>Z)return this.cache.delete($),this.cache.set($,J),J.value;let W=this.inFlight.get($);if(W)return W;let Y=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,Y);let j;try{j=await Y}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=fO)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:j,expiresAt:Date.now()+this.cacheTtlMs})}return j}forget($){if($===void 0)this.cache.clear();else{let Z=_1($);if(Z)this.cache.delete(Z)}}}var vO={kind:"none"};function ix($){let Z=($??"").trim().toLowerCase();if(Z===""||Z==="false"||Z==="off"||Z==="0")return vO;if(Z==="true")return{kind:"all"};if(/^[1-9]\d*$/.test(Z))return{kind:"hops",hops:Number(Z)};throw Error(`GEMI_TRUST_PROXY must be "false", "true" or the number of proxies in front of the app (e.g. 1). Got ${JSON.stringify($)}.`)}function sx($,Z,J){if(J.kind==="all"){if(!$.get("x-forwarded-for")&&Z)$.set("x-forwarded-for",Z);return}$.delete("x-real-ip");let W=Z;if(J.kind==="hops"){let Y=($.get("x-forwarded-for")??"").split(",").map((X)=>X.trim()).filter(Boolean),j=Y.length-J.hops,z=j>=0?Y[j]:Y[0];W=(z===void 0?null:R$(z))??Z}if(W)$.set("x-forwarded-for",W);else $.delete("x-forwarded-for")}var kG=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,wG=16;function nx($){let Z=$.GEMI_CLIENT_IP_HEADER?.trim()??"",J=$.GEMI_PROXY_SECRET_HEADER?.trim()??"",W=$.GEMI_PROXY_SECRET??"";if(Z===""&&J===""&&W==="")return null;if(Z===""||J===""||W==="")throw Error("GEMI_CLIENT_IP_HEADER, GEMI_PROXY_SECRET_HEADER and GEMI_PROXY_SECRET go together: the client-IP header is only believed on a request that carries the proxy's secret. Set all three, or none.");if(!kG.test(Z))throw Error(`GEMI_CLIENT_IP_HEADER must be a single header name, e.g. "x-azure-clientip". Got ${JSON.stringify(Z)}.`);if(!kG.test(J))throw Error(`GEMI_PROXY_SECRET_HEADER must be a single header name, e.g. "x-azure-fdid". Got ${JSON.stringify(J)}.`);if(Z.toLowerCase()===J.toLowerCase())throw Error("GEMI_CLIENT_IP_HEADER and GEMI_PROXY_SECRET_HEADER name the same header.");if(W.length<wG)throw Error(`GEMI_PROXY_SECRET must be at least ${wG} characters. A guessable one lets any client name its own address.`);return{header:Z.toLowerCase(),secretHeader:J.toLowerCase(),secret:W}}function qG($,Z){if(!r3($.get(Z.secretHeader),Z.secret))return null;let J=$.get(Z.header)?.split(",")[0];return J===void 0?null:R$(J)}var gO="/__gemi__/domains/ask";class Q1{static token="router.domains";resolver;acceptsCustomDomains;clientIpTrust;groups=new Map;staticFilesVary=!1;constructor($,Z){this.groups.set(W8,$),this.clientIpTrust=Z.clientIpTrust??null;let{domains:J}=Z;if(this.acceptsCustomDomains=Boolean(J?.custom),!J){this.resolver=null;return}this.resolver=new RY(J);let W=(Y)=>({api:Y.api?new $8({...Z.api,...Y.api}):$.api,view:Y.view?new a3({...Z.view,...Y.view},Z.auth):$.view});for(let Y of J.groups??[])this.groups.set(Y.subdomain,W(Y));if(J.custom?.fallback)this.groups.set(bY,W(J.custom.fallback));this.staticFilesVary=this.viewDispatchers().some((Y)=>Y.publicFiles!==$.view.publicFiles||Y.assetRoutes!==$.view.assetRoutes)}async staticFiles($){let Z=(this.staticFilesVary?await this.route($):null)?.view??this.dispatchers(null).view;return{publicFiles:Z.publicFiles,assetRoutes:Z.assetRoutes}}applyClientIp($){let Z=this.clientIpTrust;if(Z)fY($,Z.secretHeader);let J=this.resolver?.trustedClientIp($)??(Z?qG($.headers,Z):null);if(!J)return;$.headers.set("x-forwarded-for",J),$.headers.delete("x-real-ip")}async route($){if(!this.resolver)return this.dispatchers(null);for(let J of this.resolver.proxySecretHeaders)fY($,J);let Z=a4($)??await this.resolver.resolve($);if(!Z)return null;return tZ($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==gO)return null;if(!r3(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let J=Z.searchParams.get("domain"),W=J?await this.resolver.allows(J,$):!1;return new Response(null,{status:W?200:404})}dispatchers($){return this.groups.get($?.group??W8)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}viewGroups(){let $=new Set,Z=[];for(let[J,W]of this.groups){if($.has(W.view))continue;$.add(W.view),Z.push({group:J,view:W.view})}return Z}}function eZ($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var yG=600000;function vG($,Z){return[L6($,Z),L6($,Z-1)]}class b{static token="auth";config;provider;constructor($={},Z=new Z7){Cj($.oauthProviders),this.config={...T1(Aj($),$),emailCode:o8($.emailCode)},this.provider=Z}async oauthProvider($){return await MZ(this.config.oauthProviders,$)}async oauthProviderNames(){return await pj(this.config.oauthProviders)}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=M().bound(Q1)?M(Q1).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let J=Z==="root"?M(Q1).resolver?.root:_1(Z);if(!J)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let W=$.domain?.host??_1(new URL($.rawRequest.url).host);return W===J||W?.endsWith(`.${J}`)?J:void 0}async getSession($,Z){if(!$)return null;if(!d8($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let J=await this.userProvider.findSession({token:$,userAgent:Z});if(!J?.user)return null;let W=Date.now(),Y=eZ(J.expiresAt),j=eZ(J.absoluteExpiresAt);if(Y<=W||j<=W)return await this.userProvider.deleteSession({token:$}),null;let X=await this.slideSession(J,W);return X.user.extension=await this.config.extendSession(X.user),X}async convertLegacySession($,Z,J){let W=T.getStore()?.req;if(!W)return null;let Y=Date.now(),j=Math.floor(Y/yG),z=null,X=await this.userProvider.findSession({token:$,userAgent:Z});if(X?.user){if(!await J(X,{token:$,req:W,userAgent:Z}))return null;let G=L6($,j),B=X.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:G,userId:B,userAgent:Z,...this.freshLifetime(Y)}),!0}))z=G}if(!z){for(let G of vG($,j))if((await this.userProvider.findSession({token:G,userAgent:Z}))?.user){z=G;break}}if(!z)return null;let Q=await this.getSession(z,Z);if(Q)W.ctx().setCookie("access_token",z,this.accessTokenCookieOptions(W,new Date(Q.expiresAt)));return Q}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(d8($)||!this.config.migrateLegacySession){let Y=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),Y}let J=Math.floor(Date.now()/yG),W=vG($,J);return this.userProvider.withLegacySessionLock($,async()=>{let Y=await this.userProvider.findSession({token:$,userAgent:Z});for(let j of W){if(Y?.user)break;Y=await this.userProvider.findSession({token:j,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let j of W)await this.userProvider.deleteSession({token:j});return Y})}requestCarryingCookie($){let Z=T.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let J=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=J/2)return $;let W=new Date(Math.min(Z+J,new Date($.absoluteExpiresAt).getTime())),Y=await this.userProvider.updateSession({token:$.token,expiresAt:W}),j=this.requestCarryingCookie($.token);if(j)j.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(j,W));if(!Y)return $;return{...$,expiresAt:Y.expiresAt??W}}freshLifetime($){return{expiresAt:new Date($+this.config.sessionExpiresInHours*3600000),absoluteExpiresAt:new Date($+this.config.sessionAbsoluteExpiresInHours*3600000)}}async generateMagicLink($){}async upsertSession($){await this.userProvider.findSession({token:"",userAgent:""})}async authenticate($){try{let Z=await this.userProvider.findUserByEmailAddress($,!1);if(!Z)throw Error(`User not found with email: ${$}`);let J=await this.createOrUpdateSession({email:$,id:Z.id}),W=new C;if(W.ctx().setCookie("access_token",J.token,this.accessTokenCookieOptions(W,J.expiresAt)),J?.user)J.user.extension=await this.config.extendSession(J.user);return J}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),J=null;if(Z?.user)J=await this.config.extendSession(Z.user),Z.user.extension=J;return Z}async createOrUpdateSession($){let Z=new C,J=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!J)throw new b$;let W=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),Y=Uj(J),j=await this.userProvider.createSessionV2({token:Y,userId:J,userAgent:W,...this.freshLifetime(Date.now())}),z=await this.userProvider.findSession({token:Y,userAgent:W??""});return z?.user?z:j}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:J,token:W}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:J,token:W}}return{}}async issueOneTimeCode($,Z){let{activeCodes:J,expiresInMinutes:W,linkExpiresInMinutes:Y}=this.config.emailCode,j=await this.config.generateMagicLinkToken($),z=await this.config.generateCode($),X=typeof z==="string"&&z!==""?z:Tj(Z),Q=M6("link",$,j),G=M6("pin",$,X);if(J===1)await this.userProvider.deleteMagicLinkToken($);else{let B=Math.max(W,Y)*60000,K=(await this.userProvider.listMagicLinkTokensByEmail($,J-1)).filter((F)=>eZ(F.createdAt)+B>Date.now()&&F.pin!==G&&F.token!==Q);await this.userProvider.deleteMagicLinkTokensExcept($,K.map((F)=>F.id))}return await this.userProvider.createMagicLinkToken({email:$,token:Q,pin:G}),{email:$,pin:X,token:j}}async oneTimeCodeRows($){let{activeCodes:Z}=this.config.emailCode;if(Z===1){let J=await this.userProvider.findMagicLinkTokenByEmail($);return J?[J]:[]}return await this.userProvider.listMagicLinkTokensByEmail($,Z)}async claimOneTimeCode($,Z){if(!await this.userProvider.claimMagicLinkToken(Z))return!1;if(this.config.emailCode.activeCodes>1)await this.userProvider.deleteMagicLinkToken($);return!0}async verifyOneTimeCode($,Z,J={}){let{expiresInMinutes:W,maxAttempts:Y}=this.config.emailCode,j=await this.oneTimeCodeRows($);if(j.length===0)return OZ("pin",$,null,Z),{status:"invalid"};let z=j.filter((G)=>eZ(G.createdAt)+W*60000>Date.now());if(z.length===0)return OZ("pin",$,null,Z),{status:"expired"};let X=!0;for(let G of z)if(!await Ij(G.id,eZ(G.createdAt),Y,W))X=!1;if(!X){if(this.config.emailCode.activeCodes===1)await this.userProvider.claimMagicLinkToken(z[0].id);else await this.userProvider.deleteMagicLinkToken($);return{status:"too_many_attempts"}}let Q=null;for(let G of z)if(OZ("pin",$,G.pin,Z))Q??=G;if(!Q)return{status:"invalid"};if(J.claim!==!1&&!await this.claimOneTimeCode($,Q.id))return{status:"invalid"};return{status:"ok",row:Q}}async verifyMagicLinkToken($,Z){let J=await this.oneTimeCodeRows($);if(J.length===0)return OZ("link",$,void 0,Z),!1;let W=null;for(let j of J)if(OZ("link",$,j.token,Z))W??=j;if(!W)return!1;if(eZ(W.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.claimOneTimeCode($,W.id)}}class q0 extends m{static getFacadeAccessor(){return b}static async user(){let $=await q0.userOrNull();if($)return $;throw new b$({redirectTo:G6(T.getStore()?.req,this.getFacadeRoot().config.signInPath)})}static async userOrNull(){let $=T.getStore();if($?.user)return $.user;let Z=await Y6(this.getFacadeRoot(),$?.req);if(Z)$?.setUser(Z);return Z}static intendedUrl($){let Z=T.getStore()?.req;return V1(Z?.search.get(B1),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await q0.user();if(!await $(Z))throw new FZ}static async guardSafe($){let Z=await q0.user();try{return await $(Z)}catch(J){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async oauthProviders(){return await this.getFacadeRoot().oauthProviderNames()}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class Y8{static ensure($,Z={}){let J=T.getStore();if(J.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return J.serverQueries??=new oZ(s3(J.req.rawRequest)),J.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let J=Y8.ensure($,Z[0]);if(await J.promise,J.status==="rejected")throw J.error;return J.data}static prefetch($,...Z){Y8.ensure($,Z[0])}static noPrefetch(){let $=T.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new oZ(s3($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function mO($){return(Array.isArray($)?$:String($).split("/")).map((J)=>encodeURIComponent(String(J))).join("/")}function kY($,Z={}){let J=$.replace(/\/:(\w+)([*?]?)/g,(W,Y,j)=>{let z=Object.hasOwn(Z,Y)?Z[Y]:void 0;if(z===void 0||z===""){if(j)return"";throw Error(`\`${$}\` needs a value for :${Y}.`)}return`/${j==="*"?mO(z):encodeURIComponent(String(z))}`});return`${j8}${J==="/"?"":J}`||j8}var gG=new Map;function mG($,Z){let J=gG.get($);if(!J)J=new URLPattern({pathname:`${j8}${$==="/"?"":$}`}),gG.set($,J);let W;try{W=new URL(Z,"http://localhost").pathname}catch{return null}let Y=J.exec({pathname:W})?.pathname.groups;if(!Y)return null;let j={};for(let[z,X]of Object.entries(Y)){if(X===void 0)continue;try{j[z]=decodeURIComponent(X)}catch{return null}}return j}function hG($,Z,J="/"){let W=new URL($.origin),Y=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,j=new URL(J.startsWith("/")?J:`/${J}`,W),z=hO(Y);if(!z)throw Error(`"${Y}" is not a hostname, so there is no URL for it. Give a bare host, optionally with a port \u2014 no scheme, path or credentials.`);if(j.hostname=z.hostname,z.port)j.port=z.port;return j.toString()}function hO($){try{let Z=new URL(`http://${$.trim()}`);return Z.host===$.trim().toLowerCase()&&Z.pathname==="/"?{hostname:Z.hostname,port:Z.port}:null}catch{return null}}class pG{static origin($){return wY($)}static absolute($,...Z){return`${t$()}${D0(String($),Z[0]??{})}`}static relative($,...Z){return D0(String($),Z[0]??{})}static forDomain($,Z,...J){let W=M(Q1).resolver;if(!W)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let Y=T.getStore()?.req?.rawRequest,j=Y?W.publicOrigin(Y):t$();if(!j)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` (or `APP_URL`) for the protocol.");return hG({root:W.root,origin:j},$,D0(String(Z),J[0]??{}))}static api($,...Z){return kY(String($),Z[0]??{})}static apiAbsolute($,...Z){return`${wY()}${kY(String($),Z[0]??{})}`}static matchApi($,Z){return mG(String($),Z)}}class cG{name="Meta";static description($){T.getStore().metadata.description($)}static title($){T.getStore().metadata.title($)}static openGraph($){T.getStore().metadata.openGraph($)}static htmlAttributes($){T.getStore().metadata.htmlAttributes($)}static canonical($){T.getStore().metadata.canonical($)}static alternates($){T.getStore().metadata.alternates($)}static robots($){T.getStore().metadata.robots($)}static translate($=!0){T.getStore().metadata.translate($)}static fonts($){T.getStore().metadata.fonts($)}}var pO={set($,Z,J){T.getStore().setCookie($,Z,J)},setIfAbsent($,Z,J){if(T.getStore().req.cookies.has($))return!1;return T.getStore().setCookie($,Z,J),!0},delete($,Z){T.getStore().deleteCookie($,Z)}};class l1 extends m{static getFacadeAccessor(){return JZ}static get client(){return this.getFacadeRoot().client}static get($){return l1.client.get($)}static set($,Z){return l1.client.set($,Z)}static del(...$){return l1.client.del(...$)}static exists($){return l1.client.exists($)}static incr($){return l1.client.incr($)}static expire($,Z){return l1.client.expire($,Z)}static ttl($){return l1.client.ttl($)}}function lC($){return $}function dG(){return{store:"memory",ttl:null}}class qY{entries=new Map;maxEntries;now;constructor($={}){let Z=$.maxEntries??1e4;if(!Number.isInteger(Z)||Z<1)throw TypeError(`MemoryCacheStore maxEntries is a whole number of 1 or more; got ${Z}.`);this.maxEntries=Z,this.now=$.now??Date.now}get size(){return this.entries.size}async get($){let Z=this.live($);if(!Z)return null;return this.entries.delete($),this.entries.set($,Z),Z.value}async set($,Z,J){this.entries.delete($),this.entries.set($,{value:Z,expiresAt:J===null?null:this.now()+J});while(this.entries.size>this.maxEntries)this.entries.delete(this.entries.keys().next().value)}async delete($){let Z=this.live($)!==void 0;return this.entries.delete($),Z}async flush(){this.entries.clear()}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt!==null&&Z.expiresAt<=this.now()){this.entries.delete($);return}return Z}}var cO="500";class yY{prefix;injectedClient;constructor($={}){this.injectedClient=$.client,this.prefix=$.prefix??"gemi:cache:"}async get($){let Z=await this.client.send("GET",[this.prefix+$]);return Z===null||Z===void 0?null:String(Z)}async set($,Z,J){let W=[this.prefix+$,Z];if(J!==null)W.push("PX",String(Math.max(1,Math.round(J))));await this.client.send("SET",W)}async delete($){return Number(await this.client.send("DEL",[this.prefix+$]))>0}async flush(){if(this.prefix==="")throw Error("RedisCacheStore refuses to flush with an empty prefix: that would delete every key in the database.");let $=this.client,Z=`${dO(this.prefix)}*`,J="0";do{let W=await $.send("SCAN",[J,"MATCH",Z,"COUNT",cO]),[Y,j]=Array.isArray(W)?W:["0",[]];if(J=String(Y),Array.isArray(j)&&j.length>0)await $.send("UNLINK",j.map(String))}while(J!=="0")}get client(){if(this.injectedClient)return this.injectedClient;let $=M(),Z=$.bound(JZ)?$.make(JZ).client:void 0;if(!Z)throw Error("RedisCacheStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisCacheStore({ client }).");return Z}}function dO($){return $.replace(/[*?[\]\\^-]/g,(Z)=>`\\${Z}`)}var uO="k:",uG="tag:",lO="t:";class vY{async get($){let Z=await this.manager.read(await this.storeKey($));return Z.found?Z.value:void 0}async has($){return(await this.manager.read(await this.storeKey($))).found}async set($,Z,J){await this.manager.write(await this.storeKey($),Z,J)}async delete($){return this.manager.store.delete(await this.storeKey($))}async pull($){let Z=await this.storeKey($),J=await this.manager.read(Z);if(!J.found)return;return await this.manager.store.delete(Z),J.value}async remember($,Z,J){let[W,Y]=typeof Z==="function"?[void 0,Z]:[Z,J];if(typeof Y!=="function")throw TypeError("Cache.remember needs a function that computes the value.");return this.manager.rememberAt(await this.storeKey($),W,Y)}}class gY extends vY{options;static token="cache";config;builtStore;inflight=new Map;constructor($={},Z={}){super();this.options=Z;if(this.config=T1(dG(),$),this.config.ttl!==null&&this.config.ttl!==void 0)WZ(this.config.ttl)}get manager(){return this}get store(){return this.builtStore??=this.buildStore()}tags(...$){let Z=[...new Set($.flat())].sort();if(Z.length===0)throw TypeError("Cache.tags needs at least one tag.");for(let J of Z)if(typeof J!=="string"||J==="")throw TypeError(`A cache tag is a non-empty string; got ${JSON.stringify(J)}.`);return new iG(this,Z)}async flush(){await this.store.flush()}async storeKey($){return uO+sG($)}async read($){let Z=await this.store.get($);if(Z===null)return{found:!1};try{return{found:!0,value:JSON.parse(Z)}}catch{return{found:!1}}}async write($,Z,J){if(Z===void 0)throw TypeError("Cache.set cannot store undefined: get() returns undefined for a miss. Store null instead.");let W=this.ttlMs(J);if(W===0){await this.store.delete($);return}let Y=JSON.stringify(Z);if(Y===void 0)throw TypeError(`Cache.set cannot store a ${typeof Z}: it has no JSON form.`);await this.store.set($,Y,W)}async rememberAt($,Z,J){let W=await this.read($);if(W.found)return W.value;let Y=this.inflight.get($);if(Y)return Y;let j=(async()=>{try{let z=await J();if(z!==void 0)await this.write($,z,Z);return z}finally{this.inflight.delete($)}})();return this.inflight.set($,j),j}async tagVersions($){return Promise.all($.map(async(Z)=>{let J=uG+Z,W=await this.store.get(J);if(W!==null)return W;let Y=lG();return await this.store.set(J,Y,null),Y}))}async flushTags($){await Promise.all($.map((Z)=>this.store.set(uG+Z,lG(),null)))}ttlMs($){let Z=$===void 0?this.config.ttl:$;return Z===null||Z===void 0?null:WZ(Z)}buildStore(){let{store:$}=this.config;if($===void 0||$==="memory")return new qY(this.config.memory);if($==="redis"){let Z=this.options.application;return new yY({...this.config.redis,client:Z?{send:(J,W)=>Z.make(JZ).client.send(J,W)}:void 0})}if(typeof $==="function"){let Z=this.options.application;if(!Z)throw Error("A cache store factory needs the application: build CacheManager with { application }.");return $(Z)}if($&&typeof $==="object")return $;throw Error(`Unknown cache store ${JSON.stringify($)} in app/config/cache.ts: use "memory", "redis", a CacheStore, or a function returning one.`)}}class iG extends vY{manager;tagNames;constructor($,Z){super();this.manager=$;this.tagNames=Z}async flush(){await this.manager.flushTags([...this.tagNames])}async storeKey($){sG($);let Z=await this.manager.tagVersions([...this.tagNames]);return`${lO}${Z.join(",")}:${$}`}}function sG($){if(typeof $!=="string"||$==="")throw TypeError(`A cache key is a non-empty string; got ${JSON.stringify($)}.`);return $}function lG(){let $=new Uint8Array(9);return crypto.getRandomValues($),Array.from($,(Z)=>Z.toString(16).padStart(2,"0")).join("")}class nG extends m{static getFacadeAccessor(){return gY}static get($){return this.getFacadeRoot().get($)}static has($){return this.getFacadeRoot().has($)}static set($,Z,J){return this.getFacadeRoot().set($,Z,J)}static delete($){return this.getFacadeRoot().delete($)}static pull($){return this.getFacadeRoot().pull($)}static remember($,Z,J){let W=this.getFacadeRoot();return typeof Z==="function"?W.remember($,Z):W.remember($,Z,J)}static tags(...$){return this.getFacadeRoot().tags(...$)}static flush(){return this.getFacadeRoot().flush()}}class oG extends m{static getFacadeAccessor(){return F1}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}static enforce($,Z={},J){return this.getFacadeRoot().enforce($,Z,J)}}class rG extends m{static getFacadeAccessor(){return aG}static run($,Z,J){return this.getFacadeRoot().run($,Z,J)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class eG extends m{static getFacadeAccessor(){return tG}static encrypt($){return this.getFacadeRoot().encrypt($)}static decrypt($){return this.getFacadeRoot().decrypt($)}static needsReencryption($){return this.getFacadeRoot().needsReencryption($)}}class $K extends m{static getFacadeAccessor(){return l3}static for($,Z,J){return this.getFacadeRoot().for($,Z,J)}static list($,Z){return this.getFacadeRoot().list($,Z)}static save($,Z,J){return this.getFacadeRoot().save($,Z,J)}static fake($={}){return this.getFacadeRoot().fake($)}static restore(){this.getFacadeRoot().restore()}}function HA($){return $}function ZK(){return{driver:"memory",pollInterval:30000,maxSubscriptions:1e4,batchSize:100,keepaliveInterval:5000}}function z8($){let Z=new URLSearchParams;for(let[J,W]of $)Z.append(J,String(W));return Z.toString()}function mY($){let Z=new Map;if(!$)return Z;let J;try{J=new URLSearchParams($)}catch{return Z}for(let[W,Y]of J){let j=Number(Y);if(Y!==""&&Number.isSafeInteger(j)&&j>=0)Z.set(W,j)}return Z}var{SQL:iO}=globalThis.Bun;function sO(){return Bun.semver.satisfies(Bun.version,">=1.4.0")}var nO=async($)=>{let Z=new iO($,{max:1,idleTimeout:0,maxLifetime:0});return{listen:(J,W,Y)=>Z.listen(J,W,Y),close:()=>Z.close({timeout:1})}},oO=async($)=>{let Z;try{Z=(await import("./chunk-qfqn7rz8.js")).default}catch(W){throw Error("The change feed's database driver needs a Postgres client that can LISTEN: Bun 1.4 or later, or the `postgres` package (bun add postgres).",{cause:W})}let J=Z($,{max:1,idle_timeout:0,max_lifetime:null,fetch_types:!1,onnotice:()=>{}});return{listen:(W,Y,j)=>J.listen(W,Y,j),close:()=>J.end({timeout:1}).catch(()=>{})}},JK=($)=>sO()?nO($):oO($);var aO=/^[A-Za-z_][A-Za-z0-9_]*$/;class hY{headsTable;entriesTable;notifyChannel;sql;dialect;connection;url;retain;listener;sqliteTurn=Promise.resolve();constructor($,Z={}){if($.dialect!=="postgres"&&$.dialect!=="sqlite")throw Error(`The change feed's database driver supports Postgres and SQLite, not ${$.dialect}.`);let J=Z.headsTable??"gemi_change_heads",W=Z.entriesTable??"gemi_changes",Y=Z.notifyChannel??"gemi_changes";for(let z of[J,W,Y])if(!aO.test(z))throw Error(`"${z}" is not a plain identifier. Use letters, digits and underscores.`);let j=Z.retain??1000;if(!Number.isInteger(j)||j<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${j}.`);this.headsTable=J,this.entriesTable=W,this.notifyChannel=Y,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name,this.url=$.url,this.retain=j,this.listener=Z.listener??JK}async createTable(){for(let $ of rO(this.headsTable,this.entriesTable))await this.sql.unsafe($)}joinsTransaction(){return this.transaction()!==void 0}publish($,Z){let J=this.transaction();if(!J){let Y=()=>this.sql.begin((z)=>this.append(z,$,Z));if(this.dialect!=="sqlite")return Y();let j=this.sqliteTurn.then(Y);return this.sqliteTurn=j.catch(()=>{}),j}let W=this.append(J,$,Z);return WK(W),W}async append($,Z,J){let W=$.unsafe(`"${this.headsTable}"`),Y=$.unsafe(`"${this.entriesTable}"`),[j]=await $`
|
|
24
24
|
INSERT INTO ${W} (channel, seq) VALUES (${Z}, 1)
|
|
25
25
|
ON CONFLICT (channel) DO UPDATE SET seq = ${W}.seq + 1
|
|
26
26
|
RETURNING seq
|
|
@@ -37,7 +37,7 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
|
|
|
37
37
|
WHERE channel = ${$} AND seq > ${Z}
|
|
38
38
|
ORDER BY seq
|
|
39
39
|
LIMIT ${J}
|
|
40
|
-
`;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:j,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:j,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let Y=W.indexOf(" "),j=Number(W.slice(0,Y));if(Y>0&&Number.isInteger(j))$(W.slice(Y+1),j)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=l0();if($===void 0||
|
|
40
|
+
`;if(z.length===0||Number(z[0].seq)!==Z+1)return{entries:[],head:j,gap:!0};return{entries:z.map((X)=>({seq:Number(X.seq),data:JSON.parse(X.data)})),head:j,gap:!1}}async listen($,Z){if(this.dialect!=="postgres")return{close:async()=>{}};if(!this.url)throw Error("The change feed's database driver needs the connection's url to LISTEN. Build it from a DatabaseManager connection, which has one.");let J=await this.listener(this.url);try{await J.listen(this.notifyChannel,(W)=>{let Y=W.indexOf(" "),j=Number(W.slice(0,Y));if(Y>0&&Number.isInteger(j))$(W.slice(Y+1),j)},Z)}catch(W){throw await J.close(),W}return{close:()=>J.close()}}transaction(){if(this.dialect==="sqlite"||this.connection===void 0)return;let $=l0();if($===void 0||R1()!==this.connection)return;return $}}function rO($,Z){return[`CREATE TABLE IF NOT EXISTS "${$}" (
|
|
41
41
|
"channel" TEXT NOT NULL PRIMARY KEY,
|
|
42
42
|
"seq" BIGINT NOT NULL
|
|
43
43
|
)`,`CREATE TABLE IF NOT EXISTS "${Z}" (
|
|
@@ -46,35 +46,35 @@ ${W}`)}let J=(await Z.outputs[0].text()).trim();if(/<\/script|<!--/i.test(J))thr
|
|
|
46
46
|
"data" TEXT NOT NULL,
|
|
47
47
|
"created_at" BIGINT NOT NULL,
|
|
48
48
|
PRIMARY KEY ("channel", "seq")
|
|
49
|
-
)`]}class
|
|
49
|
+
)`]}class pY{logs=new Map;retain;constructor($={}){let Z=$.retain??1000;if(!Number.isInteger(Z)||Z<1)throw Error(`The change feed's retain must be a whole number, 1 or more; got ${Z}.`);this.retain=Z}async publish($,Z){let J=this.logs.get($);if(!J)J={head:0,entries:[]},this.logs.set($,J);let W=++J.head;if(J.entries.push({seq:W,data:Z===void 0?null:structuredClone(Z)}),J.entries.length>this.retain)J.entries.splice(0,J.entries.length-this.retain);return W}async heads($){return new Map($.map((Z)=>[Z,this.logs.get(Z)?.head??0]))}async read($,Z,J){let W=this.logs.get($),Y=W?.head??0;if(Z>Y)return{entries:[],head:Y,gap:!0};if(!W||Z===Y)return{entries:[],head:Y,gap:!1};let j=W.entries[0]?.seq??Y+1;if(j>Z+1)return{entries:[],head:Y,gap:!0};let z=Z+1-j;return{entries:W.entries.slice(z,z+J),head:Y,gap:!1}}}var QK=new TextEncoder;function YK($,Z){return QK.encode(`id: ${$}
|
|
50
50
|
data: ${JSON.stringify(Z)}
|
|
51
51
|
|
|
52
|
-
`)}function GK($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(K){if(!(K instanceof X8))throw K;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,Q=!1,G=!1,B=(K)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{K.close()}catch{}},V=new ReadableStream({start(K){X=setInterval(()=>{if(XK())return B(K);try{K.enqueue(QK.encode(jK))}catch{B(K)}},$.config.keepaliveInterval)},async pull(K){try{if(!Q){if(await z.ready(),Q=!0,!G)K.enqueue(YK(z.cursor,{type:"ready"}));return}let F=await z.next();if(F.done||G)return B(K);K.enqueue(YK(z.cursor,F.value))}catch(F){if(!G)console.error("[gemi] A change feed stream failed.",F);B(K)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(V,{headers:zK()})}var KK=255,BK=500,tO=30000;class X8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class $3{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=BK;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=P1(ZK(),$),this.driver=$L(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){cY($);let J=Z===void 0?null:Z;if(l0()!==void 0&&!this.driver.joinsTransaction?.())return uZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return uZ(()=>this.wake($,W)),W}async head($){return cY($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=pY($);return z8(await this.driver.heads(Z))}subscribe($,Z={}){let J=pY($);if(this.all.size>=this.config.maxSubscriptions)throw new X8(this.config.maxSubscriptions);let W=new VK(this,J,eO(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return GK(this,$,pY(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,Y]of J)this.wake(W,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=BK,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,tO)}}}class VK{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return z8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function cY($){if(typeof $!=="string"||$===""||$.length>KK)throw Error(`A change feed channel is a string of 1 to ${KK} characters; got ${JSON.stringify($)}.`)}function pY($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)cY(J);return Z}function eO($){if($===void 0||$===null)return new Map;if(typeof $==="string")return gY($);let Z=$ instanceof Map?[...$]:Object.entries($);return gY(z8(new Map(Z)))}function $L($,Z){if($==="memory")return new hY;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new mY(Z.make(b1));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class FK extends m{static getFacadeAccessor(){return $3}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class r3 extends c0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(c0)?$.make(c0):void 0;if(Z instanceof r3)return Z;let J=new r3($,Z);return $.instance(c0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(c0,this.previous);return}this.application.forget(c0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${dY($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${dY($,Z,J)} not to have been broadcast, but it was broadcast ${uY(W.length)}: ${lY(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${dY($,J,W)} to have been broadcast ${uY(Z)}, but it was broadcast ${uY(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${lY(this.sent)}.`)}matching($,Z,J){return GZ($),this.sent.filter((W)=>(W.pattern===$||N5($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${lY(this.sent)}.`}}function dY($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function uY($){return`${$} ${$===1?"time":"times"}`}function lY($){return $.map((Z)=>`${Z.topic} ${Z.event}(${ZL(Z.data)})`).join(", ")}function ZL($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class UK extends m{static getFacadeAccessor(){return c0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return r3.install(M())}}function tA($){return $}function DK(){return{store:"memory",sweepLimit:500}}var iY=["completed","failed","cancelled","timed_out"],_1=["pending","running"];function I1($){return iY.includes($)}class sY{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,nY($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(I1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(_1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function nY($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class rY{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of JL(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
|
|
52
|
+
`)}function GK($,Z,J,W){let Y=Z instanceof Request?Z:Z.rawRequest,j=W.cursor??Y.headers.get("Last-Event-ID")??new URL(Y.url).searchParams.get("cursor"),z;try{z=$.subscribe(J,{cursor:j,signal:Y.signal})}catch(K){if(!(K instanceof X8))throw K;return new Response(JSON.stringify({error:"The change feed is at capacity."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":String(W.retryAfter??5)}})}let X=null,Q=!1,G=!1,B=(K)=>{if(X)clearInterval(X);if(X=null,z.close(),G)return;G=!0;try{K.close()}catch{}},V=new ReadableStream({start(K){X=setInterval(()=>{if(XK())return B(K);try{K.enqueue(QK.encode(jK))}catch{B(K)}},$.config.keepaliveInterval)},async pull(K){try{if(!Q){if(await z.ready(),Q=!0,!G)K.enqueue(YK(z.cursor,{type:"ready"}));return}let F=await z.next();if(F.done||G)return B(K);K.enqueue(YK(z.cursor,F.value))}catch(F){if(!G)console.error("[gemi] A change feed stream failed.",F);B(K)}},cancel(){if(G=!0,X)clearInterval(X);X=null,z.close()}});return new Response(V,{headers:zK()})}var KK=255,BK=500,tO=30000;class X8 extends Error{limit;constructor($){super(`The change feed holds its limit of ${$} subscriptions.`);this.limit=$;this.name="ChangeFeedFullError"}}class $3{options;static token="changeFeed";driver;config;followers=new Map;all=new Set;listenState="off";listening=null;retryTimer=null;backoffMs=BK;pollTimer=null;polling=null;constructor($={},Z={}){this.options=Z;this.config=T1(ZK(),$),this.driver=$L(this.config.driver,Z.application)}get subscriptions(){return this.all.size}get isListening(){return this.listenState==="listening"}async publish($,Z){dY($);let J=Z===void 0?null:Z;if(l0()!==void 0&&!this.driver.joinsTransaction?.())return uZ(async()=>{this.wake($,await this.driver.publish($,J))}),null;let W=await this.driver.publish($,J);return uZ(()=>this.wake($,W)),W}async head($){return dY($),(await this.driver.heads([$])).get($)??0}async cursor($){let Z=cY($);return z8(await this.driver.heads(Z))}subscribe($,Z={}){let J=cY($);if(this.all.size>=this.config.maxSubscriptions)throw new X8(this.config.maxSubscriptions);let W=new VK(this,J,eO(Z.cursor),this.config,Z.signal);this.all.add(W);for(let Y of J){let j=this.followers.get(Y);if(!j)this.followers.set(Y,j=new Set);j.add(W)}return this.startListening(),this.startPolling(),W}stream($,Z,J={}){return GK(this,$,cY(Z),J)}async close(){if(this.listenState="closed",this.retryTimer)clearTimeout(this.retryTimer);this.retryTimer=null,this.stopPolling();for(let Z of this.all)Z.close();let $=this.listening;this.listening=null,await $?.close(),await this.driver.close?.()}forget($){if(!this.all.delete($))return;for(let Z of $.channels){let J=this.followers.get(Z);if(J?.delete($),J?.size===0)this.followers.delete(Z)}if(this.all.size===0)this.stopPolling()}poll(){return this.polling??=(async()=>{try{let $=[...this.followers.keys()];for(let Z=0;Z<$.length;Z+=500){let J=await this.driver.heads($.slice(Z,Z+500));for(let[W,Y]of J)this.wake(W,Y)}}catch($){console.error("[gemi] The change feed could not read its channels' heads.",$)}finally{this.polling=null}})(),this.polling}startPolling(){if(this.pollTimer)return;this.pollTimer=setInterval(()=>void this.poll(),this.config.pollInterval),this.pollTimer.unref?.()}stopPolling(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=null}wake($,Z){for(let J of this.followers.get($)??[])J.moved($,Z)}resync(){this.poll()}startListening(){if(this.listenState!=="off"||!this.driver.listen)return;this.connect()}async connect(){this.listenState="connecting",this.retryTimer=null;try{let $=await this.driver.listen((Z,J)=>this.wake(Z,J),()=>this.resync());if(this.listenState!=="connecting"){await $.close();return}this.listening=$,this.listenState="listening",this.backoffMs=BK,this.resync()}catch($){if(this.listenState!=="connecting")return;console.error(`[gemi] The change feed could not listen for other instances' changes; retrying in ${this.backoffMs}ms.`,$),this.listenState="retrying",this.retryTimer=setTimeout(()=>void this.connect(),this.backoffMs),this.retryTimer.unref?.(),this.backoffMs=Math.min(this.backoffMs*2,tO)}}}class VK{manager;config;signal;channels;positions=new Map;readTo=new Map;dirty=new Set;pending=[];started=null;wakeUp=null;closed=!1;onAbort=()=>this.close();constructor($,Z,J,W,Y){this.manager=$;this.config=W;this.signal=Y;this.channels=Z;for(let j of Z){let z=J.get(j);if(z!==void 0)this.positions.set(j,z),this.readTo.set(j,z),this.dirty.add(j)}if(Y?.aborted)this.close();else Y?.addEventListener("abort",this.onAbort,{once:!0})}get cursor(){return z8(this.positions)}get isClosed(){return this.closed}ready(){return this.started??=(async()=>{let $=this.channels.filter((J)=>!this.positions.has(J));if($.length===0)return;let Z=await this.manager.driver.heads($);for(let J of $){let W=Z.get(J)??0;this.positions.set(J,W),this.readTo.set(J,W)}})(),this.started}async next(){await this.ready();for(;;){if(this.closed)return{done:!0,value:void 0};let $=this.pending.shift();if($)return this.positions.set($.channel,$.seq),{done:!1,value:$};let Z=this.dirty.values().next().value;if(Z!==void 0){await this.read(Z);continue}await this.idle()}}async return(){return this.close(),{done:!0,value:void 0}}[Symbol.asyncIterator](){return this}close(){if(this.closed)return;this.closed=!0,this.pending.length=0,this.signal?.removeEventListener("abort",this.onAbort),this.manager.forget(this),this.wake()}moved($,Z){let J=this.readTo.get($);if(J!==void 0&&Z===J)return;this.dirty.add($),this.wake()}async read($){let Z=this.readTo.get($)??0;this.dirty.delete($);let{batchSize:J}=this.config,{entries:W,head:Y,gap:j}=await this.manager.driver.read($,Z,J);if(this.closed)return;if(j){this.readTo.set($,Y),this.pending.push({type:"reset",channel:$,seq:Y});return}for(let z of W)this.readTo.set($,z.seq),this.pending.push({type:"change",channel:$,seq:z.seq,data:z.data});if(W.length===J)this.dirty.add($)}idle(){return new Promise(($)=>{this.wakeUp=$})}wake(){let $=this.wakeUp;this.wakeUp=null,$?.()}}function dY($){if(typeof $!=="string"||$===""||$.length>KK)throw Error(`A change feed channel is a string of 1 to ${KK} characters; got ${JSON.stringify($)}.`)}function cY($){let Z=[...new Set(typeof $==="string"?[$]:$)];if(Z.length===0)throw Error("A change feed subscription needs at least one channel.");for(let J of Z)dY(J);return Z}function eO($){if($===void 0||$===null)return new Map;if(typeof $==="string")return mY($);let Z=$ instanceof Map?[...$]:Object.entries($);return mY(z8(new Map(Z)))}function $L($,Z){if($==="memory")return new pY;if($==="database"||typeof $==="function"){if(!Z&&($==="database"||$.length>0))throw Error("The change feed driver needs the application it belongs to, and this ChangeFeedManager was built without one. Pass { application }.");if($==="database")return new hY(Z.make(f1));return $(Z)}if(typeof $==="string")throw Error(`Unknown change feed driver "${$}". The changeFeed slice's driver is "memory", "database", a ChangeFeedDriver, or a function returning one.`);return $}class FK extends m{static getFacadeAccessor(){return $3}static publish($,Z){return this.getFacadeRoot().publish($,Z)}static head($){return this.getFacadeRoot().head($)}static cursor($){return this.getFacadeRoot().cursor($)}static subscribe($,Z){return this.getFacadeRoot().subscribe($,Z)}static stream($,Z,J){return this.getFacadeRoot().stream($,Z,J)}}class t3 extends c0{application;previous;sent=[];revoked=[];static install($){let Z=$.bound(c0)?$.make(c0):void 0;if(Z instanceof t3)return Z;let J=new t3($,Z);return $.instance(c0,J),J}constructor($,Z){super({driver:"memory",maxEventBytes:Z?.config.maxEventBytes,warnEventBytes:Z?.config.warnEventBytes},{application:$});this.application=$;this.previous=Z;this.channelsFrom=Z}channelsFrom;get channels(){return this.channelsFrom?.channels??null}publish($){this.sent.push($)}sendRevocation($){this.revoked.push($)}restore(){if(this.previous){this.application.instance(c0,this.previous);return}this.application.forget(c0)}assertSent($,Z,J){if(this.matching($,Z,J).length>0)return;throw Error(`Expected ${uY($,Z,J)} to have been broadcast. ${this.summary()}`)}assertNotSent($,Z,J){let W=this.matching($,Z,J);if(W.length===0)return;throw Error(`Expected ${uY($,Z,J)} not to have been broadcast, but it was broadcast ${lY(W.length)}: ${iY(W)}.`)}assertSentTimes($,Z,J,W){let Y=this.matching($,J,W);if(Y.length===Z)return;throw Error(`Expected ${uY($,J,W)} to have been broadcast ${lY(Z)}, but it was broadcast ${lY(Y.length)}. `+this.summary())}assertNothingSent(){if(this.sent.length===0)return;throw Error(`Expected nothing to have been broadcast, but ${this.sent.length} ${this.sent.length===1?"emit was":"emits were"}: ${iY(this.sent)}.`)}matching($,Z,J){return GZ($),this.sent.filter((W)=>(W.pattern===$||_5($,W.topic))&&(Z===void 0||W.event===Z)&&(J===void 0||J(W.data,W)))}summary(){if(this.sent.length===0)return"Nothing was broadcast.";return`Broadcast: ${iY(this.sent)}.`}}function uY($,Z,J){return`${Z?`"${Z}" on `:"an event on "}"${$}"`+(J?" matching the predicate":"")}function lY($){return`${$} ${$===1?"time":"times"}`}function iY($){return $.map((Z)=>`${Z.topic} ${Z.event}(${ZL(Z.data)})`).join(", ")}function ZL($){if($===void 0)return"";try{return JSON.stringify($)??String($)}catch{return String($)}}class UK extends m{static getFacadeAccessor(){return c0}static to($,...Z){return this.getFacadeRoot().to($,...Z)}static toUser($){return this.getFacadeRoot().toUser($)}static toOthers($){return this.getFacadeRoot().toOthers($)}static revoke($){this.getFacadeRoot().revoke($)}static fake(){return t3.install(M())}}function tA($){return $}function DK(){return{store:"memory",sweepLimit:500}}var sY=["completed","failed","cancelled","timed_out"],I1=["pending","running"];function x1($){return sY.includes($)}class nY{runs=new Map;clock=0;get size(){return this.runs.size}async create($){if(this.runs.has($.id))throw Error(`A run with the id ${$.id} already exists.`);let Z=this.tick(),J={id:$.id,kind:$.kind,subject:$.subject,owner:$.owner,status:$.status,meta:structuredClone($.meta??null),progress:null,result:null,error:null,version:1,createdAt:Z,startedAt:$.status==="running"?Z:null,updatedAt:Z,finishedAt:null,deadlineAt:$.deadlineMs===null?null:Z+$.deadlineMs};return this.runs.set(J.id,J),structuredClone(J)}async get($){let Z=this.runs.get($);return Z?structuredClone(Z):null}async list($){let Z=[];for(let J of this.runs.values()){if($.kind!==void 0&&J.kind!==$.kind)continue;if($.subject!==void 0&&J.subject!==$.subject)continue;if($.owner!==void 0&&J.owner!==$.owner)continue;if($.statuses&&!$.statuses.includes(J.status))continue;Z.push(J)}return Z.reverse().sort((J,W)=>W.createdAt-J.createdAt),Z.slice(0,oY($.limit)).map((J)=>structuredClone(J))}async transition($,Z,J){let W=this.runs.get($);if(!W||!Z.includes(W.status))return null;let Y=structuredClone(J),j=this.tick();if(Y.status!==void 0){if(W.startedAt===null&&Y.status!=="pending")W.startedAt=j;if(x1(Y.status))W.finishedAt=j;W.status=Y.status}if("progress"in Y)W.progress=Y.progress??null;if("result"in Y)W.result=Y.result??null;if("error"in Y)W.error=Y.error??null;return W.version+=1,W.updatedAt=j,structuredClone(W)}async overdue($,Z){let J=[];for(let W of this.runs.values())if(I1.includes(W.status)&&W.deadlineAt!==null&&W.deadlineAt<=$)J.push(W);return J.sort((W,Y)=>W.deadlineAt-Y.deadlineAt),J.slice(0,Math.max(0,Z)).map((W)=>structuredClone(W))}async now(){return this.tick()}async prune($){let Z=this.tick()-$,J=0;for(let[W,Y]of this.runs)if(Y.finishedAt!==null&&Y.finishedAt<=Z)this.runs.delete(W),J++;return J}tick(){return this.clock=Math.max(this.clock,Date.now()),this.clock}}function oY($){if($===void 0)return 50;return Math.max(0,Math.floor($))}class tY{table;sql;dialect;connection;constructor($,Z={}){let J=Z.table??"gemi_runs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`The runs table name "${J}" is not a plain identifier. Use letters, digits and underscores.`);this.table=J,this.sql=$.sql,this.dialect=$.dialect,this.connection=$.name}async createTable(){for(let $ of JL(this.dialect,this.table))await this.sql.unsafe($)}async create($){let Z=this.q(),J=this.clock(Z),W=$.deadlineMs===null?Z`NULL`:Z`${J} + ${this.ms(Z,$.deadlineMs)}`,Y=$.status==="running"?J:Z`NULL`;await Z`
|
|
53
53
|
INSERT INTO ${this.name(Z)}
|
|
54
54
|
(id, kind, subject, owner, status, meta, version,
|
|
55
55
|
created_at, started_at, updated_at, deadline_at)
|
|
56
56
|
VALUES
|
|
57
57
|
(${$.id}, ${$.kind}, ${$.subject}, ${$.owner}, ${$.status},
|
|
58
58
|
${G8($.meta)}, 1, ${J}, ${Y}, ${J}, ${W})
|
|
59
|
-
`;let j=await this.get($.id);if(!j)throw Error(`The run ${$.id} was not found after it was written.`);return j}async get($){let Z=this.q(),J=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return J[0]?
|
|
59
|
+
`;let j=await this.get($.id);if(!j)throw Error(`The run ${$.id} was not found after it was written.`);return j}async get($){let Z=this.q(),J=await Z`SELECT * FROM ${this.name(Z)} WHERE id = ${$}`;return J[0]?rY(J[0]):null}async list($){let Z=this.q(),J=[Z`1 = 1`];if($.kind!==void 0)J.push(Z`kind = ${$.kind}`);if($.subject!==void 0)J.push(Z`subject = ${$.subject}`);if($.owner!==void 0)J.push(Z`owner = ${$.owner}`);if($.statuses!==void 0)J.push($.statuses.length===0?Z`1 = 0`:Z`status IN (${Q8(Z,$.statuses)})`);let W=J.reduce((j,z)=>Z`${j} AND ${z}`);return(await Z`
|
|
60
60
|
SELECT * FROM ${this.name(Z)}
|
|
61
61
|
WHERE ${W}
|
|
62
62
|
ORDER BY created_at DESC, id DESC
|
|
63
|
-
LIMIT ${
|
|
64
|
-
`).map(
|
|
63
|
+
LIMIT ${oY($.limit)}
|
|
64
|
+
`).map(rY)}async transition($,Z,J){if(Z.length===0)return null;let W=this.q(),Y=this.clock(W),j=[W`updated_at = ${Y}`,W`version = version + 1`];if(J.status!==void 0){if(j.push(W`status = ${J.status}`),J.status!=="pending")j.push(W`started_at = COALESCE(started_at, ${Y})`);if(x1(J.status))j.push(W`finished_at = ${Y}`)}if("progress"in J)j.push(W`progress = ${G8(J.progress)}`);if("result"in J)j.push(W`result = ${G8(J.result)}`);if("error"in J)j.push(W`error = ${G8(J.error)}`);let z=j.reduce((Q,G)=>W`${Q}, ${G}`),X=await W`
|
|
65
65
|
UPDATE ${this.name(W)} SET ${z}
|
|
66
66
|
WHERE id = ${$} AND status IN (${Q8(W,Z)})
|
|
67
67
|
`;if(LK(X)===0)return null;return this.get($)}async overdue($,Z){let J=this.q();return(await J`
|
|
68
68
|
SELECT * FROM ${this.name(J)}
|
|
69
|
-
WHERE status IN (${Q8(J,
|
|
69
|
+
WHERE status IN (${Q8(J,I1)})
|
|
70
70
|
AND deadline_at IS NOT NULL AND deadline_at <= ${this.ms(J,$)}
|
|
71
71
|
ORDER BY deadline_at, id
|
|
72
72
|
LIMIT ${Math.max(0,Math.floor(Z))}
|
|
73
|
-
`).map(
|
|
73
|
+
`).map(rY)}async now(){let $=this.q(),[Z]=await $`SELECT ${this.clock($)} AS now`;return Number(Z.now)}async prune($){let Z=this.q(),J=await Z`
|
|
74
74
|
DELETE FROM ${this.name(Z)}
|
|
75
|
-
WHERE status IN (${Q8(Z,
|
|
75
|
+
WHERE status IN (${Q8(Z,sY)})
|
|
76
76
|
AND finished_at <= ${this.clock(Z)} - ${this.ms(Z,$)}
|
|
77
|
-
`;return LK(J)}joinable(){if(this.connection===void 0)return;let $=l0();if($===void 0||
|
|
77
|
+
`;return LK(J)}joinable(){if(this.connection===void 0)return;let $=l0();if($===void 0||R1()!==this.connection)return;return $}q(){return this.joinable()??this.sql}name($){let Z=this.dialect==="mysql"||this.dialect==="mariadb";return $.unsafe(Z?`\`${this.table}\``:`"${this.table}"`)}clock($){switch(this.dialect){case"postgres":return $`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;case"mysql":case"mariadb":return $`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;case"sqlite":return $`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`}}ms($,Z){let J=Math.max(0,Math.round(Z));return this.dialect==="mysql"||this.dialect==="mariadb"?$`CAST(${J} AS SIGNED)`:$`CAST(${J} AS BIGINT)`}}function Q8($,Z){return Z.map((J)=>$`${J}`).reduce((J,W)=>$`${J}, ${W}`)}function G8($){return $===void 0||$===null?null:JSON.stringify($)}function K8($){if($===null||$===void 0)return null;return JSON.parse(String($))}function aY($){return $===null||$===void 0?null:Number($)}function OK($){return $===null||$===void 0?null:String($)}function rY($){return{id:String($.id),kind:String($.kind),subject:OK($.subject),owner:OK($.owner),status:String($.status),meta:K8($.meta),progress:K8($.progress),result:K8($.result),error:K8($.error),version:Number($.version),createdAt:Number($.created_at),startedAt:aY($.started_at),updatedAt:Number($.updated_at),finishedAt:aY($.finished_at),deadlineAt:aY($.deadline_at)}}function LK($){let Z=$;return Math.max(Number(Z.count??0),Number(Z.affectedRows??0))}function JL($,Z){if($==="mysql"||$==="mariadb")return[`CREATE TABLE IF NOT EXISTS \`${Z}\` (
|
|
78
78
|
\`id\` VARCHAR(191) NOT NULL,
|
|
79
79
|
\`kind\` VARCHAR(191) NOT NULL,
|
|
80
80
|
\`subject\` VARCHAR(191) NULL,
|
|
@@ -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 MK=191,HK=30000;class B8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class V8 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 tY{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=P1(DK(),$),this.store=jL(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make($3);return this.ownFeed??=new $3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){NK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;NK("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:WZ($.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 YL(Z),this.change($,_1,{status:"running",progress:Z})}complete($,Z){return this.change($,_1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,_1,{status:"failed",error:TK(Z)})}cancel($,Z){return this.change($,_1,{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 B8($);if(I1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof V8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,_1,{status:"failed",error:Q instanceof V8?TK(Q):{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()+WZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new B8($);let z=null;for(;;){if(I1(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 Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await PK(z,Math.min(Q,X??1/0,HK),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 B8($);if(yield W,I1(W.status))return;for await(let Y of J){let j=WL(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,I1(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=WZ($);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||I1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,_1,{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(I1(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,PK(j,Math.min(z??1/0,HK))]);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 PK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function WL($,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 TK($){if(typeof $==="string")return{message:$};if($ instanceof V8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function NK($,Z){if(typeof Z!=="string"||Z===""||Z.length>MK)throw TypeError(`A run's ${$} is a string of 1 to ${MK} characters; got ${JSON.stringify(Z)}.`)}function YL($){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 jL($,Z){if($==="memory")return new sY;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(b1).connection();return new rY(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 _K extends m{static getFacadeAccessor(){return tY}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 IK extends m{static getFacadeAccessor(){return Y$}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 Z5{value;constructor($){this.value=$}}var zL=/^[A-Za-z_][A-Za-z0-9_$]*$/;function XL($){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"||!zL.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 F8{bound;constructor($){this.bound=$}get name(){return this.bound??E1()}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 $5(J.sql,(W)=>eY(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=XL(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(l0()!==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 $5(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await eY(j,()=>W(X));throw new Z5(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof Z5)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-g3m7t5zc.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=AK($,CK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=l0();if($===void 0)return;return E1()===this.name?$:void 0}connection($=this.name){return xK($),M(b1).connection($)}}var YZ=new F8;class SK extends m{static getFacadeAccessor(){return b1}static connection($){return new F8($)}static get sql(){return YZ.sql}static get dialect(){return YZ.dialect}static query($){return YZ.query($)}static execute($){return YZ.execute($)}static transaction($){return YZ.transaction($)}static readOnly($,Z){return YZ.readOnly($,Z)}static schema(){return YZ.schema()}static close(){return this.getFacadeRoot().close()}}export{G1 as ie,qK as je,o0 as ke,W3 as le,M8 as me,QZ as ne,j3 as oe,C0 as pe,Y6 as qe,c8 as re,d8 as se,F2 as te,W$ as ue,V1 as ve,R$ as we,Z0 as xe,l5 as ye,VZ as ze,U2 as Ae,D2 as Be,l8 as Ce,i8 as De,M6 as Ee,OZ as Fe,nB as Ge,CP as He,C2 as Ie,k2 as Je,r8 as Ke,w2 as Le,q2 as Me,JV as Ne,y2 as Oe,t8 as Pe,jV as Qe,zV as Re,e8 as Se,v2 as Te,g2 as Ue,Y$ as Ve,m2 as We,KV as Xe,Z7 as Ye,E8 as Ze,K6 as _e,C1 as $e,A8 as af,A1 as bf,I$ as cf,Y8 as df,pG as ef,cG as ff,pO as gf,d1 as hf,lC as if,dG as jf,wY as kf,qY as lf,vY as mf,iG as nf,nG as of,oG as pf,rG as qf,eG as rf,$K as sf,HA as tf,ZK as uf,z8 as vf,gY as wf,mY as xf,hY as yf,X8 as zf,$3 as Af,VK as Bf,FK as Cf,u as Df,z3 as Ef,q4 as Ff,KT as Gf,BT as Hf,VT as If,OT as Jf,lX as Kf,AW as Lf,nX as Mf,TT as Nf,rX as Of,c0 as Pf,p3 as Qf,tX as Rf,UK as Sf,tA as Tf,iY as Uf,_1 as Vf,I1 as Wf,sY as Xf,rY as Yf,JL as Zf,B8 as _f,V8 as $f,tY as ag,_K as bg,IK as cg,F8 as dg,SK as eg,EW as fg,XD as gg,gW as hg,mW as ig,RN as jg,PQ as kg,IQ as lg,j6 as mg,e1 as ng,iN as og,CQ as pg,AQ as qg,GY as rg,aZ as sg,KY as tg,FI as ug,TI as vg,NI as wg,DO as xg,xY as yg,HO as zg,NY as Ag,NO as Bg,o3 as Cg,CY as Dg,CG as Eg,e4 as Fg,$8 as Gg,ix as Hg,sx as Ig,nx as Jg,X1 as Kg,E as Lg,q0 as Mg,z6 as Ng,A5 as Og,oK as Pg,I5 as Qg,E5 as Rg,I8 as Sg,Q6 as Tg,x8 as Ug,b5 as Vg,JB as Wg,WB as Xg,y5 as Yg,g5 as Zg,h5 as _g,s5 as $g,n5 as ah,o5 as bh,k8 as ch,GB as dh,X0 as eh,z2 as fh,UZ as gh,B2 as hh};
|
|
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 MK=191,HK=30000;class B8 extends Error{id;constructor($){super(`No run has the id ${$}.`);this.id=$;this.name="RunNotFoundError"}}class V8 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 eY{options;static token="runs";store;config;ownFeed=null;constructor($={},Z={}){this.options=Z;this.config=T1(DK(),$),this.store=jL(this.config.store,Z.application)}get feed(){if(this.options.feed)return this.options.feed;if(this.options.application)return this.options.application.make($3);return this.ownFeed??=new $3,this.ownFeed}channel($){return`gemi:run:${$}`}async create($){NK("kind",$.kind);let Z=$.id??`run_${crypto.randomUUID().replaceAll("-","")}`;NK("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:WZ($.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 YL(Z),this.change($,I1,{status:"running",progress:Z})}complete($,Z){return this.change($,I1,{status:"completed",result:Z===void 0?null:Z})}fail($,Z){return this.change($,I1,{status:"failed",error:TK(Z)})}cancel($,Z){return this.change($,I1,{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 B8($);if(x1(W.status))return W;let Y=new AbortController,j=this.watch($,W,J,Y),z={id:$,record:W,signal:Y.signal,progress:async(Q)=>{if(Y.signal.aborted)return;await this.progress($,Q)}},X;try{let Q=await Z(z);X=await this.complete($,Q)}catch(Q){if(!(Q instanceof V8)&&!Y.signal.aborted)console.error(`[gemi] Run ${$} failed.`,Q);X=await this.change($,I1,{status:"failed",error:Q instanceof V8?TK(Q):{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()+WZ(Z.timeout),Y=this.feed.subscribe(this.channel($),{signal:J});try{await Y.ready();let j=await this.store.get($);if(!j)throw new B8($);let z=null;for(;;){if(x1(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 Q=W-Date.now();if(Q<=0)return j;if(z??=Y.isClosed?new Promise(()=>{}):Y.next(),await PK(z,Math.min(Q,X??1/0,HK),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 B8($);if(yield W,x1(W.status))return;for await(let Y of J){let j=WL(Y,$)??await this.store.get($);if(!j||j.version<=W.version)continue;if(W=j,yield W,x1(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=WZ($);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||x1(Z.status))return null;let J=await this.untilDeadline(Z);if(J===null||J>0)return null;return this.change($,I1,{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(x1(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,PK(j,Math.min(z??1/0,HK))]);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 PK($,Z,J){return new Promise((W,Y)=>{let j=Number.isFinite(Z)?setTimeout(()=>Q(!1),Math.max(0,Z)):null,z=()=>{X(),Y(J.reason)},X=()=>{if(j)clearTimeout(j);J?.removeEventListener("abort",z)},Q=(G)=>{X(),W(G)};J?.addEventListener("abort",z,{once:!0}),$.then(()=>Q(!0),()=>Q(!0))})}function WL($,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 TK($){if(typeof $==="string")return{message:$};if($ instanceof V8)return{message:$.message,...$.code!==void 0?{code:$.code}:{},...$.data!==void 0?{data:$.data}:{}};if($ instanceof Error)return{message:$.message};return $}function NK($,Z){if(typeof Z!=="string"||Z===""||Z.length>MK)throw TypeError(`A run's ${$} is a string of 1 to ${MK} characters; got ${JSON.stringify(Z)}.`)}function YL($){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 jL($,Z){if($==="memory")return new nY;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 tY(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 _K extends m{static getFacadeAccessor(){return eY}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 IK extends m{static getFacadeAccessor(){return Y$}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 J5{value;constructor($){this.value=$}}var zL=/^[A-Za-z_][A-Za-z0-9_$]*$/;function XL($){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"||!zL.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 F8{bound;constructor($){this.bound=$}get name(){return this.bound??R1()}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 Z5(J.sql,(W)=>$5(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=XL(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(l0()!==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 Z5(z.sql,async(X)=>{for(let G of Y)await X.unsafe(G);let Q=await $5(j,()=>W(X));throw new J5(Q)},{slowTransactionThreshold:z.config.slowTransactionThreshold,connection:j})}catch(X){if(X instanceof J5)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-g3m7t5zc.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let J=this.connection(),{text:W,values:Y}=AK($,CK(J.dialect),Z);return(this.handle()??J.sql).unsafe(W,Y)}handle(){let $=l0();if($===void 0)return;return R1()===this.name?$:void 0}connection($=this.name){return xK($),M(f1).connection($)}}var YZ=new F8;class SK extends m{static getFacadeAccessor(){return f1}static connection($){return new F8($)}static get sql(){return YZ.sql}static get dialect(){return YZ.dialect}static query($){return YZ.query($)}static execute($){return YZ.execute($)}static transaction($){return YZ.transaction($)}static readOnly($,Z){return YZ.readOnly($,Z)}static schema(){return YZ.schema()}static close(){return this.getFacadeRoot().close()}}export{K1 as ie,qK as je,a0 as ke,Y3 as le,M8 as me,QZ as ne,z3 as oe,C0 as pe,Y6 as qe,c8 as re,d8 as se,Uj as te,W$ as ue,F1 as ve,R$ as we,Z0 as xe,i5 as ye,VZ as ze,Dj as Ae,Oj as Be,l8 as Ce,i8 as De,M6 as Ee,OZ as Fe,nB as Ge,CP as He,Aj as Ie,wj as Je,r8 as Ke,qj as Le,yj as Me,JV as Ne,vj as Oe,t8 as Pe,jV as Qe,zV as Re,e8 as Se,gj as Te,mj as Ue,Y$ as Ve,hj as We,KV as Xe,Z7 as Ye,E8 as Ze,K6 as _e,S1 as $e,A8 as af,E1 as bf,I$ as cf,Y8 as df,pG as ef,cG as ff,pO as gf,l1 as hf,lC as if,dG as jf,qY as kf,yY as lf,gY as mf,iG as nf,nG as of,oG as pf,rG as qf,eG as rf,$K as sf,HA as tf,ZK as uf,z8 as vf,mY as wf,hY as xf,pY as yf,X8 as zf,$3 as Af,VK as Bf,FK as Cf,u as Df,X3 as Ef,q4 as Ff,KT as Gf,BT as Hf,VT as If,OT as Jf,iX as Kf,AW as Lf,oX as Mf,TT as Nf,tX as Of,c0 as Pf,c3 as Qf,eX as Rf,UK as Sf,tA as Tf,sY as Uf,I1 as Vf,x1 as Wf,nY as Xf,tY as Yf,JL as Zf,B8 as _f,V8 as $f,eY as ag,_K as bg,IK as cg,F8 as dg,SK as eg,EW as fg,XD as gg,gW as hg,mW as ig,RN as jg,TQ as kg,xQ as lg,j6 as mg,e1 as ng,iN as og,AQ as pg,SQ as qg,GY as rg,aZ as sg,KY as tg,FI as ug,TI as vg,NI as wg,DO as xg,CY as yg,HO as zg,NY as Ag,NO as Bg,a3 as Cg,AY as Dg,CG as Eg,e4 as Fg,$8 as Gg,ix as Hg,sx as Ig,nx as Jg,Q1 as Kg,b as Lg,q0 as Mg,z6 as Ng,S5 as Og,oK as Pg,x5 as Qg,b5 as Rg,I8 as Sg,Q6 as Tg,x8 as Ug,R5 as Vg,JB as Wg,WB as Xg,v5 as Yg,m5 as Zg,p5 as _g,n5 as $g,o5 as ah,a5 as bh,k8 as ch,GB as dh,X0 as eh,Xj as fh,UZ as gh,Vj as hh};
|
|
116
116
|
|
|
117
|
-
//# debugId=
|
|
117
|
+
//# debugId=976BBF86269B2C1764756E2164756E21
|