gemi 0.100.0 → 0.102.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/ai/Schema.d.ts +59 -5
  2. package/dist/ai/Schema.d.ts.map +1 -1
  3. package/dist/ai/index.d.ts +1 -1
  4. package/dist/ai/index.d.ts.map +1 -1
  5. package/dist/ai/index.js +13 -13
  6. package/dist/ai/index.js.map +3 -3
  7. package/dist/chunk-23mpa8t7.js +5 -0
  8. package/dist/{chunk-jv38q9n7.js.map → chunk-23mpa8t7.js.map} +3 -3
  9. package/dist/chunk-4x41cmg3.js +9 -0
  10. package/dist/chunk-4x41cmg3.js.map +31 -0
  11. package/dist/chunk-9hs7prvj.js +17 -0
  12. package/dist/{chunk-rc4z7ykq.js.map → chunk-9hs7prvj.js.map} +4 -4
  13. package/dist/{chunk-q2r6b35k.js → chunk-hr0m35tr.js} +1 -1
  14. package/dist/{chunk-kgckt396.js → chunk-mb8chren.js} +2 -2
  15. package/dist/{chunk-kgckt396.js.map → chunk-mb8chren.js.map} +1 -1
  16. package/dist/{chunk-vdynb16s.js → chunk-md8hmejq.js} +1 -1
  17. package/dist/facades/index.js +1 -1
  18. package/dist/http/McpRouter.d.ts +126 -11
  19. package/dist/http/McpRouter.d.ts.map +1 -1
  20. package/dist/http/index.js +1 -1
  21. package/dist/i18n/index.js +1 -1
  22. package/dist/kernel/index.js +1 -1
  23. package/dist/server/index.js +1 -1
  24. package/dist/services/index.d.ts +2 -2
  25. package/dist/services/index.d.ts.map +1 -1
  26. package/dist/services/index.js +1 -1
  27. package/dist/services/mcp/McpRegistry.d.ts +56 -3
  28. package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
  29. package/dist/services/mcp/toAgentTools.d.ts +57 -1
  30. package/dist/services/mcp/toAgentTools.d.ts.map +1 -1
  31. package/dist/services/router/ApiRouteDispatcher.d.ts +27 -1
  32. package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-h15bd9vn.js +0 -9
  35. package/dist/chunk-h15bd9vn.js.map +0 -31
  36. package/dist/chunk-jv38q9n7.js +0 -5
  37. package/dist/chunk-rc4z7ykq.js +0 -17
  38. /package/dist/{chunk-q2r6b35k.js.map → chunk-hr0m35tr.js.map} +0 -0
  39. /package/dist/{chunk-vdynb16s.js.map → chunk-md8hmejq.js.map} +0 -0
@@ -0,0 +1,17 @@
1
+ // @bun
2
+ import{Nd as Cz,Ud as iJ}from"./chunk-bf1q3m7a.js";import{$d as OZ,Le as dJ,ee as uZ}from"./chunk-adm5g1v8.js";import{$e as b4,Me as s3,Qe as SJ,Re as o4,Se as p3,Te as k3,We as g3,Xe as y3,Ye as $Z,Ze as GJ,_e as HJ,af as y,ff as _,gf as n3,hf as a3,if as h3,kf as d1,lf as K0,mf as I3,uf as x7,vf as B$,wf as kJ}from"./chunk-4x41cmg3.js";import{Af as L1,Bf as e4,yf as iZ,zf as a0}from"./chunk-9xf2fx98.js";import{Cf as TJ,Df as V4,Ef as N}from"./chunk-eqtsfvvd.js";import{Hf as yJ}from"./chunk-br9p390p.js";import{If as NJ,Jf as DZ,Kf as FZ,Lf as hJ,Mf as cJ,Xf as lJ}from"./chunk-n4807648.js";import{kg as UZ}from"./chunk-ghz3e8b7.js";import{pg as VJ,ug as IJ}from"./chunk-7vjbebst.js";import{vg as vJ}from"./chunk-3fr22rtg.js";import{Cg as fJ,Gg as u}from"./chunk-qttatc7h.js";import{Hg as e$,Kg as C}from"./chunk-48dek9s7.js";import{Yg as _J}from"./chunk-2tm56xq1.js";import{bh as L4}from"./chunk-68zf43ah.js";function tZ($){return typeof $==="function"&&$.prototype!==void 0}function W1($){return typeof $==="string"?[$]:$}function eZ($,Z){let O=Z?"attachment":"inline",j=$.replace(/["\\]/g,"").replace(/[^\x20-\x7e]/g,"_");return`${O}; filename="${j}"; filename*=UTF-8''${encodeURIComponent($)}`}function OW($){return"total"in $&&"partial"in $&&"body"in $}function H4(){return new Response("Not found",{status:404,headers:{"X-Content-Type-Options":"nosniff"}})}function zZ($){return new Response(null,{status:416,headers:{"Accept-Ranges":"bytes","Content-Range":y3($),"Content-Length":"0","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}})}async function jW($){if($ instanceof Blob)return{body:$,start:0,end:$.size-1,total:$.size,partial:!1,type:$.type,name:$.name,download:!1,status:200,extraHeaders:{}};if(OW($))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,O=Z instanceof Blob?Z:null,j=$.total??O?.size??-1;return{body:Z,start:$.start??0,end:$.end??j-1,total:j,partial:$.partial??!1,type:$.type??O?.type??"",name:$.name??Z?.name,download:$.download??!1,etag:$.etag,lastModified:$.lastModified,status:$.status??200,extraHeaders:$.headers??{}}}async function m3($,Z){if($ instanceof Response)return $;if(!$)return H4();let O=await jW($),{body:j,start:T,end:z,total:J,partial:W}=O;if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return H4()}let{range:Y}=Z;if(Y){if(J<=0)return zZ(Math.max(J,0));if(!W){if(j instanceof Blob){let F=k3(Y,J);if(!F)return zZ(J);j=j.slice(F.start,F.end+1),T=F.start,z=F.end,W=!0}}}let X=Boolean(Y)&&W,D=X?206:O.status,U=new Headers;if(U.set("Accept-Ranges","bytes"),U.set("Content-Type",O.type||"application/octet-stream"),U.set("X-Content-Type-Options","nosniff"),X)U.set("Content-Range",g3(T,z,J)),U.set("Content-Length",String(z-T+1));else if(J>=0)U.set("Content-Length",String(J));if(O.name)U.set("Content-Disposition",eZ(O.name,O.download));if(O.etag)U.set("ETag",O.etag);if(O.lastModified)U.set("Last-Modified",O.lastModified.toUTCString());for(let[F,G]of Object.entries(O.extraHeaders))U.set(F,G);if((Z.method??"GET").toUpperCase()==="HEAD"){if(j&&"cancel"in j&&typeof j.cancel==="function")await j.cancel();return new Response(null,{status:D,headers:U})}return new Response(j,{status:D,headers:U})}function E4($){return tZ($)}class r{method;handler;methodName;__internal_brand="RouteHandler";middlewares=[];constructor($,Z,O){this.method=$;this.handler=Z;this.methodName=O;this.handler=Z,this.methodName=O,this.method=$}get source(){if(!E4(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(E4(this.handler)){let Z=new this.handler;return Z[this.methodName].bind(Z)()}return this.handler()}middleware($){return this.middlewares=W1($),this}}class v4{url;headers;__internal_brand="ProxyHandler";middlewares=[];constructor($,Z){this.url=$;this.headers=Z}middleware($){return this.middlewares=W1($),this}run(){let $=new _,Z=$.headers.toJSON();for(let O of b4($.rawRequest))delete Z[O];return fetch(this.url,{method:$.rawRequest.method,headers:{...Z,...this.headers},body:$.rawRequest.body})}}class R4{constructor(...$){return new r(...$)}}class w4 extends r{__internal_brand="StreamHandler";async run($){let Z=N.getStore(),O=Z?.req?.rawRequest,j=p3(O?.headers.get("Range"));if(Z)Z.rangeRequest=j;try{let T=await super.run($);return await m3(T,{range:j,method:O?.method})}catch(T){if(T instanceof h3)return zZ(T.total);throw T}finally{if(Z)Z.rangeRequest=null}}}class q4{constructor(...$){return new w4(...$)}}class k4{__internal_brand="ResourceRoutes";first;second;constructor($){this.first={get:new r("GET",$,"list"),post:new r("POST",$,"store")},this.second={get:new r("GET",$,"show"),put:new r("PUT",$,"update"),delete:new r("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 N0{static __brand="ApiRouter";routes={};middlewares=[];middleware($){}get($,Z){return new r("GET",$,Z)}post($,Z){return new r("POST",$,Z)}put($,Z){return new r("PUT",$,Z)}patch($,Z){return new r("PATCH",$,Z)}delete($,Z){return new r("DELETE",$,Z)}resource($){return new k4($)}agent($){return TW($,this)}file($,Z){return new R4("GET",$,Z)}stream($,Z){return new q4("GET",$,Z)}proxy($,Z={}){return new v4($,Z)}}function TW($,Z){let O={stream:new r("POST",$,"stream"),attach:new r("POST",$,"attach"),stop:new r("POST",$,"stop"),upload:new r("POST",$,"upload")};return class extends N0{static __internal_brand="AgentRoute";static controller=$;static handlers=O;constructor(){super();this.middlewares=[...Z?.middlewares??[]]}routes={"/":O.stream,"/attach":O.attach,"/stop":O.stop,"/files":O.upload};static middleware(T){if(T.stream)O.stream.middleware(T.stream);if(T.attach)O.attach.middleware(T.attach);if(T.stop)O.stop.middleware(T.stop);if(T.upload)O.upload.middleware(T.upload);return this}}}class c3{method;url;meta;__internal_brand="McpRoute";constructor($,Z,O){this.method=$;this.url=Z;this.meta=O}}class g4{static __brand="McpRouter";routes={};fromApiRoute($,Z,O){return new c3($,Z,O)}}function z0($,Z){return $.replace(/:([^/]+[*?]?)/g,(O,j)=>{let T=j.endsWith("?")||j.endsWith("*"),z=T?j.slice(0,-1):j,J=Z[z];if(J===void 0){if(T)return"";if(import.meta.env.DEV)throw Error(`Missing parameter: ${z}`);console.error(`Missing parameter: ${z} in URL: ${$}`)}return String(J)}).replace(/\/\//g,"/").replace(/\/$/,"")}class l3 extends a0{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 $O{static to($,...Z){let[O={}]=Z,{search:j={},params:T={},permanent:z,status:J}={params:{},status:307,permanent:!1,...O},W=new URLSearchParams(j).toString();throw new l3([z0($,T)||"/",W.toString()].filter(Boolean).join("?"),J??(z?301:307))}static external($,Z=307){throw new l3($,Z)}}var y4=Symbol.for("gemi.HttpResponse");class l1{kind;body;status;headers;[y4]=!0;constructor($,Z,O,j){this.kind=$;this.body=Z;this.status=O;this.headers=j}static json($,Z={}){let O=Z.status??200;return zW(O),new l1("json",$,O,new Headers(Z.headers))}static error($,Z,O={}){if(!Number.isInteger($)||$<400||$>599)throw RangeError(`HttpResponse.error: status must be an integer from 400 to 599, got ${$}.`);return l1.json({error:Z},{...O,status:$})}get ok(){return this.status>=200&&this.status<300}toResponse($,Z){let O=$,j=this.serialize(O);for(let T of Z)O.append("Set-Cookie",T);this.headers.forEach((T,z)=>{if(z.toLowerCase()!=="set-cookie")O.set(z,T)});for(let T of this.headers.getSetCookie())O.append("Set-Cookie",T);if(this.status>=400&&!this.headers.has("Cache-Control"))O.set("Cache-Control","no-store");return new Response(j,{status:this.status,headers:O})}serialize($){switch(this.kind){case"json":return $.set("Content-Type","application/json"),JSON.stringify(this.body)??null}}}function zW($){if(!Number.isInteger($)||$<200||$>599)throw RangeError(`HttpResponse: status must be an integer from 200 to 599, got ${$}.`);if($===204||$===205||$===304)throw RangeError(`HttpResponse.json: a ${$} response has no body.`)}function f$($){return typeof $==="object"&&$!==null&&$[y4]===!0}function JW($,Z,O={}){return l1.error($,Z,O)}class m4{kind="redirect";viewPath="REDIRECT";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>({});else if(typeof $==="function")this.handler=$;else{let[Z,O]=$;this.handler=(j)=>{return new Z()[O](j)}}}async run($,Z){let{destination:O,permanent:j=!1,status:T=307}=await this.handler($);if(!O)throw Error(`Redirect destination is required see ${Z}`);return $O.to(O,{permanent:j,status:T}),{}}middleware($){return this.middlewares=W1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}async function d3($,Z){if($ instanceof Response)return $;let O=$ instanceof Blob,j=O?$:$.file,T=O?$.name:$.name??$.file?.name,z=(O?$.type:$.type??$.file?.type)||"",J=O?!1:$.download??!1,W=O?200:$.status??200;if(!O)for(let[Y,X]of Object.entries($.headers??{}))Z.set(Y,X);if(j instanceof Blob&&"exists"in j&&typeof j.exists==="function"){if(!await j.exists())return new Response("Not found",{status:404})}if(Z.set("Content-Type",z||"application/octet-stream"),j instanceof Blob)Z.set("Content-Length",String(j.size));if(T)Z.set("Content-Disposition",eZ(T,J));return new Response(j instanceof Blob?j.stream():j,{status:W,headers:Z})}class p4{kind="file";viewPath="FILE";middlewares=[];featureGates=[];handler;constructor($){if(!$)this.handler=()=>null;else if(typeof $==="function")this.handler=$;else{let[Z,O]=$;this.handler=(j)=>{return new Z()[O](j)}}}async run($,Z){let O=await this.handler($);if(!O)throw Error(`File route handler must return a file see ${Z}`);return{FILE:O}}middleware($){return this.middlewares=W1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}function h4($,Z){if(f$($))throw Error(`The handler of view "${Z}" returned an HttpResponse. HttpResponse is for api routes; a view handler returns its props.`);return $}class c4{viewPath;middlewares=[];featureGates=[];handler;constructor($,Z){this.viewPath=$;if(!Z)this.handler=()=>({});else if(typeof Z==="function")this.handler=Z;else{let[O,j]=Z;this.handler=(T)=>{return new O()[j](T)}}}async run($,Z){let O=h4(await this.handler($),this.viewPath);return{[this.viewPath]:{...O,breadcrumb:{label:O?.breadcrumb??"",href:Z}}}}middleware($){return this.middlewares=W1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class l4{viewPath;children;middlewares=[];featureGates=[];alwaysRuns=!1;handler=()=>({});constructor($,Z,O){this.viewPath=$;if(typeof Z==="function")this.handler=Z,this.children=class extends V1{routes=O??{}};else if(Array.isArray(Z)){let[j,T]=Z;this.handler=(z)=>{return new j()[T](z)},this.children=class extends V1{routes=O??{}}}else this.children=class extends V1{routes=Z},this.handler=()=>({})}async run($,Z){let O=h4(await this.handler($),this.viewPath);return{[this.viewPath]:{...O,breadcrumb:{label:O?.breadcrumb??"",href:Z}}}}alwaysRun(){return this.alwaysRuns=!0,this}middleware($){return this.middlewares=W1($),this}feature($){return this.featureGates=[...this.featureGates,$],this}}class V1{middlewares=[];featureGates=[];routes={};view($,Z){return new c4($,Z)}file($){return new p4($)}redirect($){return new m4($)}layout($,Z,O){return new l4($,Z,O)}}class R0{req;config={};constructor($){this.req=$}run(...$){return{}}static configure($){let Z=this;return class extends Z{config=$}}}function WW($){return $}function YW(){return{aliases:{},global:[]}}var V$="redirect";function JZ($,Z="/"){if(typeof $!=="string"||!$.startsWith("/"))return Z;if(/[\u0000-\u001f\u007f\\]/.test($)||$.startsWith("//"))return Z;try{let O=new URL($,"http://gemi.invalid");if(O.origin!=="http://gemi.invalid")return Z;let j=`${O.search}${O.hash}`.replaceAll("/","%2F"),T=`${O.pathname}${j}`.replaceAll(":","%3A");return T.startsWith("//")?Z:T}catch{return Z}}function d4($){let Z=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return Z?Z==="https":new URL($.url).protocol==="https:"}function XW($,Z=!0){let O=new URL($.rawRequest.url),j=O.pathname.replace(/\.(json|og)$/,""),[,T,...z]=j.split("/");if(C(u).supportedLocales.includes(T))j=`/${z.join("/")}`;return Z?`${j}${O.search}`:j}function DW($,Z){let O=(j)=>j.replace(/\/+$/,"")||"/";return O($)===O(Z)}function ZO($,Z){let O=Z||C(H).config.signInPath,j=/^[a-z][a-z\d+.-]*:/i.test(O);if(j?!/^https?:\/\//i.test(O):!O.startsWith("/"))throw Error(`\`auth.signInPath\` must be a path like "/auth/sign-in", or an http(s) URL for sign-in hosted elsewhere. Got "${O}". A route's own \`"auth:<path>"\` cannot carry a URL, because the alias parser splits it on the colon.`);let T=new URL(O,"http://gemi.invalid");if($?.kind==="view"){let z=XW($,!j);if(j||!DW(new URL(z,T).pathname,T.pathname))T.searchParams.set(V$,z)}return j?T.href:`${T.pathname}${T.search}`}var I1="access_token";function i3($){return $?.cookies?.get("access_token")||$?.headers?.get("access_token")||null}async function OO($,Z){let O=i3(Z);if(!O)return null;return(await $.getSession(O,Z.headers.get("User-Agent")))?.user??null}class i4 extends R0{async run($){let Z=N.getStore(),O=Z.req;if(Z.user)return{};let j=await OO(C(H),O);if(!j)throw new d1({redirectTo:ZO(O,$)});return Z.setUser(j),{}}}class u4 extends R0{async run(...$){let[Z="public",O="864000",...j]=$,T=`${Z}, max-age=${O}${j.length>0?", ":""}${j.join(", ")}`;if($.length===0)T="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="public")T="public, max-age=864000, stale-while-revalidate=300, stale-if-error=600";if($.length===1&&$[0]==="private")T="private, max-age=0, stale-while-revalidate=300, stale-if-error=600";if(this.req.rawRequest.method==="GET")this.req.ctx().setHeaders("Cache-Control",T);return{}}}var FW={"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 s4 extends R0{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(this.config.origins[Z]){$.ctx().setHeaders("Access-Control-Allow-Origin",Z);let O={...FW,...this.config.origins[Z]};for(let[j,T]of Object.entries(O))$.ctx().setHeaders(j,T)}return{}}}class o0{config;static token="ratelimiter";constructor($){this.config=$}get driver(){return this.config.driver}async consume($,Z={}){let O=Z.limit??this.config.limit,j=Z.window??this.config.window,T=Z.cost??1;if(n4("window",j),n4("limit",O),!Number.isFinite(T)||T<0)throw Error(`Rate limiter cost must be zero or greater, got ${T}`);return await this.config.driver.consume({key:$,limit:O,window:j*1000,cost:T})}}function n4($,Z){if(!Number.isFinite(Z)||Z<=0)throw Error(`Rate limiter ${$} must be greater than zero, got ${Z}`)}class WZ extends a0{constructor($){super("Rate limit exceeded");let Z={"Content-Type":"application/json",...$?t4($):{}};this.payload={api:{status:429,data:{error:L1("rate_limit","Rate limit exceeded",429)},headers:Z},view:{error:{message:"Rate limit exceeded"},status:429,headers:Z}}}}class r4 extends R0{async run($,Z){let O=UW();if(!O)return{};let j=await O.consume(this.key(),{limit:a4($)??this.config.limit,window:a4(Z)??this.config.window});if(this.config.headers!==!1){let T=this.req.ctx?.();if(T)for(let[z,J]of Object.entries(t4(j)))T.setHeaders(z,J)}if(!j.allowed)throw new WZ(j);return{}}key(){if(this.config.key)return this.config.key(this.req);return`${I$(this.req)}:${this.req.routePath??"*"}`}}function UW(){try{let $=C();return $.bound(o0)?$.make(o0):null}catch{return null}}function I$($){let Z=o4($.rawRequest);if(Z!==void 0)return Z;let O=$.headers.get("x-forwarded-for");if(O){let[j]=O.split(",");if(j?.trim())return j.trim()}return $.headers.get("x-real-ip")?.trim()||"unknown"}function t4($){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}function a4($){if($===void 0||$===null||$==="")return;let Z=Number($);if(!Number.isFinite(Z)||Z<=0)return;return Z}class $z extends R0{async run(){let $=this.req.cookies.get("csrf_token");if(!$)throw new u3;if(!["POST","PUT","PATCH","DELETE"].includes(this.req.rawRequest.method))return{};if(!Bun.CSRF.verify($,{secret:process.env.SECRET}))throw new u3;return{}}}class u3 extends a0{constructor(){super("Invalid CSRF token");this.name="InvalidCSRFTokenError"}payload={api:{status:403,data:{error:e4("csrf","Invalid CSRF token",403)}},view:{}}}class Zz{policiesList={};constructor(){let $=this.register();for(let Z of $){let O=new Z;this.policiesList[Z.name]=O}}register(){return[]}}class Oz{all($,Z){return!0}}import{createHmac as jz,randomBytes as BW}from"crypto";var o3="v2.";function r3($){return $.startsWith(o3)}function jO(){let $=process.env.SECRET;if(!$)throw Error("Signing in needs a secret to mint session tokens with. Set SECRET in the environment.");return $}function Tz($){let Z=BW(16).toString("hex"),O=jz("sha256",jO()).update(`${$}:${Z}`).digest("hex");return`${o3}${O}`}function TO($,Z){let O=jz("sha256",jO()).update(`legacy-session:${Z}:${$}`).digest("hex");return`${o3}${O}`}import{createHash as QW,createHmac as CW,randomInt as fW,timingSafeEqual as Wz}from"crypto";function zz($,Z){return Math.floor($/Z)*Z}function GW($,Z){if(Z<=0)return 0;return Math.min(1,Math.max(0,(Z-$)/Z))}function t3($,Z,O,j){return Z*GW(O,j)+$}function KW($){let{current:Z,previous:O,elapsed:j,window:T,limit:z,cost:J}=$,W=z-J;if(W<0)return T;let Y=Math.max(0,T-j);if(O>0){let D=T*(1-(W-Z)/O);if(D<=T)return Math.max(0,Math.ceil(D-j))}if(Z<=W)return Y;if(Z<=0)return Y;let X=T*(1-W/Z);return Y+Math.max(0,Math.ceil(X))}function Jz($){let{allowed:Z,current:O,previous:j,now:T,elapsed:z,window:J,limit:W,cost:Y}=$;if(Z){let D=t3(O,j,z,J);return{allowed:!0,limit:W,remaining:Math.max(0,Math.floor(W-D)),resetAt:T-z+J,retryAfter:0}}let X=KW({current:O,previous:j,elapsed:z,window:J,limit:W,cost:Y});return{allowed:!1,limit:W,remaining:0,resetAt:T+X,retryAfter:X}}class e3{}class $j extends e3{buckets=new Map;maxKeys;constructor($={}){super();this.maxKeys=Math.max(1,$.maxKeys??1e5)}consume($){let{key:Z,limit:O,window:j}=$,T=$.cost??1,z=Date.now(),J=zz(z,j),W=z-J,Y=this.roll(Z,j,J);Y.limit=O;let D=t3(Y.current,Y.previous,W,j)+T<=O;if(D)Y.current+=T;if(this.buckets.delete(Z),this.buckets.set(Z,Y),this.buckets.size>this.maxKeys)this.evict(z);return Jz({allowed:D,current:Y.current,previous:Y.previous,now:z,elapsed:W,window:j,limit:O,cost:T})}clear(){this.buckets.clear()}get size(){return this.buckets.size}roll($,Z,O){let j=this.buckets.get($);if(!j||j.window!==Z)return{window:Z,limit:0,windowStart:O,current:0,previous:0};if(j.windowStart===O)return j;if(j.windowStart+Z===O)return j.previous=j.current,j.current=0,j.windowStart=O,j;return j.previous=0,j.current=0,j.windowStart=O,j}evict($){for(let[j,T]of this.buckets)if($-T.windowStart>=T.window*2)this.buckets.delete(j);let Z=this.maxKeys-Math.floor(this.maxKeys/10);if(this.buckets.size<=Z)return;let O=[...this.buckets].map(([j,T],z)=>({key:j,order:z,spent:T.limit>0?(T.current+T.previous)/T.limit:0}));O.sort((j,T)=>j.spent-T.spent||j.order-T.order);for(let{key:j}of O){if(this.buckets.size<=Z)break;this.buckets.delete(j)}}}var Dz="h1.";function zO($,Z,O){let j=CW("sha256",jO()).update(`gemi:one-time:${$}:${Z}:${O}`).digest("hex");return`${Dz}${j}`}function YZ($,Z,O,j){let T=typeof j==="string"?j:"",z=typeof O==="string"?O:"",J=z.startsWith(Dz),W=zO($,Z,T),Y=Buffer.from(J?W:T),X=Buffer.from(z);if(Y.length!==X.length||T===""||z==="")return Wz(Y,Y),!1;return Wz(Y,X)}function Fz($){let Z="";for(let O=0;O<$;O++)Z+=String(fW(0,10));return Z}var Uz=320;function XZ($){if(typeof $!=="string")return null;let Z=$.trim();if(Z===""||Z.length>Uz)return null;return Z.toLowerCase()}function Zj($){if(typeof $!=="string")return null;let Z=$.trim();if(Z.length>Uz)return null;let O=Z.toLowerCase();if(O.length<3||O.length>254||!/^[^\s@]+@[^\s@]+$/.test(O))return null;return O}var Yz=null;function Bz(){try{let $=C();if(typeof $?.bound==="function"&&$.bound(o0))return $.make(o0)}catch{}return Yz??=new o0({driver:new $j,limit:1000,window:60}),Yz}function Xz($){return $.length<=64?$:`sha256:${QW("sha256").update($).digest("hex")}`}async function L$($,Z,O,j){let T=Bz(),z=[[`auth:code-${$}:ip:${Xz(I$(O))}`,j.perIp]];if(Z!==null)z.push([`auth:code-${$}:email:${Xz(Z)}`,j.perEmail]);for(let[J,W]of z){if(!W)continue;let[Y,X]=W,D=await T.consume(J,{limit:Y,window:X});if(!D.allowed)throw new WZ(D)}}async function Gz($,Z,O,j=10){let T=Math.max(86400,Math.ceil(j*60*(O+1)));return(await Bz().consume(`auth:code-attempt:${$}:${Z}`,{limit:O,window:T})).allowed}import{randomBytes as jj}from"crypto";class Oj extends _{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 JO($,Z,O,j=1/0){if(!Number.isInteger(Z)||Z<O||Z>j){let T=j===1/0?`an integer of at least ${O}`:`an integer from ${O} to ${j}`;throw Error(`auth.emailCode.${$} must be ${T}, got ${Z}`)}}function Tj($={}){let Z=$.length??6,O=$.expiresInMinutes??10,j=$.linkExpiresInMinutes??10080,T=$.maxAttempts??5;return JO("length",Z,4,12),JO("expiresInMinutes",O,1),JO("linkExpiresInMinutes",j,1),JO("maxAttempts",T,1),{enabled:$.enabled??!1,createUser:$.createUser??!1,length:Z,expiresInMinutes:O,linkExpiresInMinutes:j,maxAttempts:T,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:J})=>{if(Bun.env.NODE_ENV!=="production")console.info(`[gemi] email code for ${z}: ${J} (set auth.emailCode.send to deliver it)`)})}}async function VW($,Z){if(typeof Z!=="string"||Z==="")return!1;try{return await Bun.password.verify($,Z)}catch{return!1}}function QU($){return $}function Kz($={}){return{basePath:"/auth",verifyEmail:!0,redirectPath:"/dashboard",signInPath:"/auth/sign-in",sessionExpiresInHours:24,sessionAbsoluteExpiresInHours:672,cookieDomain:null,migrateLegacySession:null,signUpRequest:Oj,oauthProviders:{},verifyPassword:VW,hashPassword:async(Z)=>await Bun.password.hash(Z),generateForgotPasswordToken:async()=>jj(32).toString("hex"),generateEmailVerificationToken:()=>{if(!($.verifyEmail??!0))return"";return jj(32).toString("hex")},generateMagicLinkToken:()=>jj(32).toString("hex"),extendSession:()=>({}),onUserCreated:async()=>{},onSignUp:()=>{},onSignIn:()=>{},onSignOut:()=>{},onForgotPassword:()=>{},onResetPassword:()=>{},onMagicLinkCreated:()=>{},emailCode:Tj($.emailCode),generateCode:()=>{return},onAuthenticated:()=>{}}}function zj($){if($&&typeof $==="object")delete $.password;return $}function IW(){return new Proxy({},{get:($,Z)=>Cz(Z)})}var Qz=new WeakMap;function fz($){if($&&typeof $==="object"){for(let Z of Object.values($))fz(Z);Object.freeze($)}return $}var LW={select:{id:!0,publicId:!0,email:!0,name:!0,locale:!0,globalRole:!0,accounts:{select:{id:!0,publicId:!0,organizationRole:!0,organization:!0}}}},MW=fz({token:!0,expiresAt:!0,absoluteExpiresAt:!0,updatedAt:!0,location:!0,userAgent:!0,user:LW});class Jj{models;constructor($=IW()){this.models=$}run($){return this.models.User.asSystem($)}sessionSelect(){return MW}transaction($){return this.models.User.transaction($)}withLegacySessionLock($,Z){let O=this.models.User.$connection??FZ(),j=C(UZ).connection(O),T=()=>this.transaction(async()=>{if(j.dialect==="postgres"){let W=`gemi:legacy-session:${$}`;await DZ()`SELECT pg_advisory_xact_lock(hashtextextended(${W}, 0))`}return Z()});if(j.dialect!=="sqlite"||DZ())return T();let J=(Qz.get(j)??Promise.resolve()).then(T,T);return Qz.set(j,J.catch(()=>{})),J}async createUser($){let Z=await this.run(()=>this.models.User.create({data:$}));return zj(Z)}async updateUserPassword($){let Z=await this.run(()=>this.models.User.update({where:{id:$.id},data:{password:$.password}}));return zj(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=(O)=>typeof O==="string"&&O!=="";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 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 O=await this.run(()=>this.models.SocialAccount.findFirst({where:{provider:$,providerId:Z},include:{user:!0}}));return O?zj(O.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:O}=await this.run(()=>this.models.SocialAccount.updateMany({where:{id:$.id,providerId:$.providerId},data:{providerId:Z}}));return O===1}}import{randomBytes as zX}from"crypto";function _0($,Z,O,j,T){return g0(Z,wz($,Z),O,j,T)}function g0($,Z,O,j,T,z){let J=Fj(Z,O,j);if(T&&Z!==J)throw RangeError(C2($,Z,O,j,z));return J}function wz($,Z){let O=$[Z];if(O===void 0)throw TypeError(p6(Z));return O}function W0($){return $!==null&&/object|function/.test(typeof $)}function A0($,Z=Map){let O=new Z;return(j,...T)=>{if(O.has(j))return O.get(j);let z=$(j,...T);return O.set(j,z),z}}function Vj($){return n1({name:$},1)}function n1($,Z){return h0((O)=>({value:O,configurable:1,writable:!Z}),$)}function qz($){return h0((Z)=>({get:Z,configurable:1}),$)}function MO($){return{[Symbol.toStringTag]:{value:$,configurable:1}}}function A$($,Z){let O={},j=$.length;for(let T of Z)O[$[--j]]=T;return O}function h0($,Z,O){let j={};for(let T in Z)j[T]=$(Z[T],T,O);return j}function LZ($,Z,O){let j={};for(let T=0;T<Z.length;T++){let z=Z[T];j[z]=$(z,T,O)}return j}function SW($,Z,O){let j={};for(let T=0;T<$.length;T++)j[Z[T]]=O[$[T]];return j}function E0($,Z){let O={};for(let j of $)O[j]=Z[j];return O}function Ij($,Z){let O={};for(let j in Z)$.has(j)||(O[j]=Z[j]);return O}function Lj($){$={...$};let Z=Object.keys($);for(let O of Z)$[O]===void 0&&delete $[O];return $}function kz($,Z){for(let O of Z)if(!(O in $))return 0;return 1}function gz($,Z,O){for(let j of $)if(Z[j]!==O[j])return 0;return 1}function yz($,Z,O){let j={...O};for(let T=0;T<Z;T++)j[$[T]]=0;return j}function v($,...Z){return(...O)=>$(...Z,...O)}function Vz($){return $[0].toUpperCase()+$.substring(1)}function MZ($){return $.slice().sort()}function BO($,Z){return String(Z).padStart($,"0")}function M1($,Z){return Math.sign($-Z)}function Fj($,Z,O){return Math.min(Math.max($,Z),O)}function X1($,Z){return[Math.floor($/Z),GZ($,Z)]}function GZ($,Z){return($%Z+Z)%Z}function _1($,Z){return[SO($,Z),Mj($,Z)]}function SO($,Z){return Math.trunc($/Z)||0}function Mj($,Z){return $%Z||0}function WO($){return Math.abs($%1)===0.5}function mz($,Z,O){let j=0,T=0;for(let W=0;W<=Z;W++){let Y=$[O[W]],X=t0[W],D=m/X,[U,F]=_1(Y,D);j+=F*X,T+=U}let[z,J]=_1(j,m);return[T+z,J]}function NO($,Z,O){let j={};for(let T=Z;T>=0;T--){let z=t0[T];j[O[T]]=SO($,z),$=Mj($,z)}return j}function pz($){return $===R?T3:[]}function hz($){return $===R?vZ:[]}function cz($){return $===R?["year","day"]:[]}function lz($){if($!==void 0)return s($)}function dz($){if($!==void 0)return c0($)}function Sj($){if($!==void 0)return SZ($)}function c0($){return sz(SZ($))}function SZ($){return uz(GY($))}function Nj($){if($==null)throw TypeError("Cannot be null or undefined");return $}function iz($,Z){if(Z==null)throw RangeError(p6($));return Z}function F1($){if(!W0($))throw TypeError(Q2);return $}function _O($,Z,O=$){if(typeof Z!==$)throw TypeError(HZ(O,Z));return Z}function uz($,Z="number"){if(!Number.isInteger($))throw RangeError(mW(Z,$));return $||0}function sz($,Z="number"){if($<=0)throw RangeError(pW(Z,$));return $}function _j($){if(typeof $=="symbol")throw TypeError(dW);return String($)}function GO($,Z){return W0($)?String($):s($,Z)}function xO($){if(typeof $=="string")return BigInt($);if(typeof $!="bigint")throw TypeError(lW($));return $}function nz($,Z="number"){if(typeof $=="bigint")throw TypeError(cW(Z));if($=Number($),!Number.isFinite($))throw RangeError(hW(Z,$));return $}function Q0($,Z){return Math.trunc(nz($,Z))||0}function az($,Z){return uz(nz($,Z),Z)}function Iz($,Z){return sz(Q0($,Z),Z)}function xj($,Z){let[O,j]=_1(Z,m),T=$+O,z=Math.sign(T);return z&&z===-Math.sign(j)&&(T-=z,j+=z*m),[T,j]}function S$($,Z,O=1){return xj($[0]+Z[0]*O,$[1]+Z[1]*O)}function N$($,Z){return xj($[0],$[1]+Z)}function w0($,Z){return S$(Z,$,-1)}function f0($,Z){return M1($[0],Z[0])||M1($[1],Z[1])}function oz($,Z,O){return f0($,Z)===-1||f0($,O)===1}function PO($,Z=1){let O=BigInt(m/Z);return[Number($/O),Number($%O)*Z]}function _$($,Z=1){let O=m/Z,[j,T]=_1($,O);return[j,T*Z]}function rz($,Z=1){let[O,j]=$,T=Math.floor(j/Z),z=m/Z;return BigInt(O)*BigInt(z)+BigInt(T)}function q0($,Z=1,O){let[j,T]=$,[z,J]=_1(T,Z);return j*(m/Z)+(z+(O?J/Z:0))}function Pj($,Z,O=X1){let[j,T]=$,[z,J]=O(T,Z);return[j*(m/Z)+z,J]}function Aj($,Z){let O=$.formatToParts(Z),j={};for(let T of O)j[T.type]=T.value;return j}function Hj($){return _0($,"isoYear",IZ,VZ,1),$.isoYear===IZ?_0($,"isoMonth",4,12,1):$.isoYear===VZ&&_0($,"isoMonth",1,9,1),$}function S1($){return U1({...$,...p0,isoHour:12}),$}function U1($){let Z=_0($,"isoYear",IZ,VZ,1),O=Z===IZ?1:Z===VZ?-1:0;return O&&k0(C0({...$,isoDay:$.isoDay+O,isoNanosecond:$.isoNanosecond-O})),$}function k0($){if(!$||oz($,LY,IY))throw RangeError($3);return $}function x1($){return mz($,5,u0)[1]}function AO($){let[Z,O]=X1($,m);return[NO(O,5,u0),Z]}function tz($){return ez($)[0]}function ez($){return Pj($,m0)}function V0($){return H$($.isoYear,$.isoMonth,$.isoDay,$.isoHour,$.isoMinute,$.isoSecond,$.isoMillisecond)}function C0($){let Z=V0($);if(Z!==void 0){let[O,j]=_1(Z,P0);return[O,j*e0+($.isoMicrosecond||0)*j$+($.isoNanosecond||0)]}}function Ej($,Z){let[O,j]=AO(x1($)-Z);return k0(C0({...$,isoDay:$.isoDay+j,...O}))}function KO(...$){return H$(...$)/A2}function H$(...$){let[Z,O]=$8(...$),j=Z.valueOf();if(!isNaN(j))return j-O*P0}function $8($,Z=1,O=1,j=0,T=0,z=0,J=0){let W=$===IZ?1:$===VZ?-1:0,Y=new Date;return Y.setUTCHours(j,T,z,J),Y.setUTCFullYear($,Z-1,O+W),[Y,W]}function A1($,Z){let[O,j]=N$($,Z);j<0&&(j+=m,O-=1);let[T,z]=X1(j,e0),[J,W]=X1(z,j$);return HO(O*P0+T,J,W)}function HO($,Z=0,O=0){let j=Math.ceil(Math.max(0,Math.abs($)-VY)/P0)*Math.sign($),T=new Date($-j*P0);return A$(J3,[T.getUTCFullYear(),T.getUTCMonth()+1,T.getUTCDate()+j,T.getUTCHours(),T.getUTCMinutes(),T.getUTCSeconds(),T.getUTCMilliseconds(),Z,O])}function Z8($){return[$.isoYear,$.isoMonth,$.isoDay]}function O8(){return Y1}function bj($,Z){switch(Z){case 2:return vj($)?29:28;case 4:case 6:case 9:case 11:return 30}return 31}function j8($){return vj($)?366:365}function vj($){return $%4==0&&($%100!=0||$%400==0)}function T8($){let[Z,O]=$8($.isoYear,$.isoMonth,$.isoDay);return GZ(Z.getUTCDay()-O,7)||7}function z8({isoYear:$}){return $<1?["bce",1-$]:["ce",$]}function NW($){let Z=V0($);if(Z<SY)return z8($);let O=Aj(TT(x$),Z),{era:j,eraYear:T}=Q5(O,x$);return[j,T]}function EO($){return a1($),bO($,1),$}function a1($){return J8($,1),$}function Lz($){return gz(o6,$,J8($))}function J8($,Z){let{isoYear:O}=$,j=_0($,"isoMonth",1,O8(),Z);return{isoYear:O,isoMonth:j,isoDay:_0($,"isoDay",1,bj(O,j),Z)}}function bO($,Z){return A$(u0,[_0($,"isoHour",0,23,Z),_0($,"isoMinute",0,59,Z),_0($,"isoSecond",0,59,Z),_0($,"isoMillisecond",0,999,Z),_0($,"isoMicrosecond",0,999,Z),_0($,"isoNanosecond",0,999,Z)])}function q($){return $===void 0?0:i2(F1($))}function NZ($,Z=0){$=l0($);let O=u2($),j=RY($,Z);return[i2($),j,O]}function Rj($){return u2(l0($))}function W8($){return $=l0($),e6($,9,6,1)}function E$($,Z,O,j=9,T=0,z=4){Z=l0(Z);let J=e6(Z,j,T),W=kj(Z),Y=wZ(Z,z),X=RZ(Z,j,T,1);return J==null?J=Math.max(O,X):F8(J,X),W=gj(W,X,1),$&&(Y=((D)=>D<4?(D+2)%4:D)(Y)),[J,X,W,Y]}function vO($,Z=6,O){let j=kj($=yj($,LO)),T=wZ($,7),z=RZ($,Z);return z=iz(LO,z),j=gj(j,z,void 0,O),[z,j,T]}function wj($){return $T(l0($))}function Y8($,Z){return qj(l0($),Z)}function qj($,Z=4){let O=D8($);return[wZ($,4),...X8(RZ($,Z),O)]}function X8($,Z){return $!=null?[t0[$],$<4?9-3*$:-1]:[Z===void 0?1:10**(9-Z),Z]}function kj($){let Z=$[KZ];return Z===void 0?1:Q0(Z,KZ)}function gj($,Z,O,j){let T=j?m:t0[Z+1];if(T){let z=t0[Z];if(T%(($=g0(KZ,$,1,T/z-(j?0:1),1))*z))throw RangeError(HZ(KZ,$))}else $=g0(KZ,$,1,O?1e9:1,1);return $}function D8($){let Z=$[Dj];if(Z!==void 0){if(typeof Z!="number"){if(_j(Z)==="auto")return;throw RangeError(HZ(Dj,Z))}Z=g0(Dj,Math.floor(Z),0,9,1)}return Z}function l0($){return $===void 0?{}:F1($)}function yj($,Z){return typeof $=="string"?{[Z]:$}:F1($)}function t($){if($!==void 0){if(W0($))return Object.assign(Object.create(null),$);throw TypeError(Q2)}}function RO($,Z){return $&&Object.assign(Object.create(null),$,{overflow:_Y[Z]})}function mj($,Z,O=9,j=0,T){let z=Z[$];if(z===void 0)return T?j:void 0;if(z=_j(z),z==="auto")return T?j:null;let J=Kj[z];if(J===void 0&&(J=CY[z]),J===void 0)throw RangeError(I2($,z,Kj));return g0($,J,j,O,1,bZ),J}function o1($,Z,O,j=0){let T=O[$];if(T===void 0)return j;let z=_j(T),J=Z[z];if(J===void 0)throw RangeError(I2($,z,Z));return J}function F8($,Z){if(Z>$)throw RangeError(XY)}function Y0($){return{branding:Y3,epochNanoseconds:$}}function F0($,Z,O){return{branding:Q1,calendar:O,timeZone:Z,epochNanoseconds:$}}function e($,Z=$.calendar){return{branding:z$,calendar:Z,...E0(h2,$)}}function $0($,Z=$.calendar){return{branding:T$,calendar:Z,...E0(r6,$)}}function u1($,Z=$.calendar){return{branding:y$,calendar:Z,...E0(r6,$)}}function QO($,Z=$.calendar){return{branding:m$,calendar:Z,...E0(r6,$)}}function d0($){return{branding:W3,...E0(p2,$)}}function l($){return{branding:X3,sign:H1($),...E0(s6,$)}}function U8($){return tz($.epochNanoseconds)}function wO($){return Pj($.epochNanoseconds,e0)[0]}function B8($){return rz($.epochNanoseconds,j$)}function G8($){return rz($.epochNanoseconds)}function K8($){return $.epochNanoseconds}function X0($){return typeof $=="string"?$:s($.id)}function b$($,Z){return $===Z||X0($)===X0(Z)}function Q8($,Z,O,j,T){let z=s1(j),[J,W]=((Q,f)=>{let L=f((Q=yj(Q,fj))[l2]),V=vY(Q);return V=iz(fj,V),[V,L]})(T,$);if(CZ(Math.max(J,z),W))return Mz(j,J);if(!W)throw RangeError(Z3);let[Y,X,D]=pO(Z,O,W),U=X6(D),F=hO(D),G=D6(D),B=F(X,Y,j),K=G(X,Y,B,J);return CZ(J,W)?Mz(K,J):((Q,f,L,V,x,P,I)=>{let M=H1(Q),[A,E]=pj(V,a6(L,Q),L,M,x,P,I),j0=hj(f,A,E);return Q[k[L]]+j0*M})(K,U(B),J,X,Y,U,F)}function Mz($,Z){return q0(J0($),t0[Z],1)}function pj($,Z,O,j,T,z,J){let W=k[O],Y={...Z,[W]:Z[W]+j},X=J($,T,Z),D=J($,T,Y);return[z(X),z(D)]}function hj($,Z,O){let j=q0(w0(Z,O));if(!j)throw RangeError(EZ);return q0(w0(Z,$))/j}function C8($,Z){let[O,j,T]=vO(Z,5,1);return Y0(kO($.epochNanoseconds,O,j,T,1))}function f8($,Z,O){let{epochNanoseconds:j,timeZone:T,calendar:z}=Z,[J,W,Y]=vO(O);if(J===0&&W===1)return Z;let X=$(T);if(J===6)j=((D,U,F,G)=>{let B=I0(F,U),[K,Q]=D(B),f=F.epochNanoseconds,L=H0(U,K),V=H0(U,Q);if(oz(f,L,V))throw RangeError(EZ);return P8(hj(f,L,V),G)?V:L})(_8,X,Z,Y);else{let D=X.getOffsetNanosecondsFor(j);j=t1(X,S8(A1(j,D),J,W,Y),D,2,0,1)}return F0(j,T,z)}function V8($,Z){return e(S8($,...vO(Z)),$.calendar)}function I8($,Z){let[O,j,T]=vO(Z,5);var z;return d0((z=T,cj($,_Z(O,j),z)[0]))}function L8($,Z){let O=$(Z.timeZone),j=I0(Z,O),[T,z]=_8(j),J=q0(w0(H0(O,T),H0(O,z)),j3,1);if(J<=0)throw RangeError(EZ);return J}function M8($,Z){let{timeZone:O,calendar:j}=Z,T=((z,J,W)=>H0(J,z(I0(W,J))))(x8,$(O),Z);return F0(T,O,j)}function S8($,Z,O,j){return N8($,_Z(Z,O),j)}function N8($,Z,O){let[j,T]=cj($,Z,O);return U1({...e1($,T),...j})}function cj($,Z,O){return AO(P1(x1($),Z,O))}function CO($){return P1($,O3,7)}function _Z($,Z){return t0[$]*Z}function _8($){let Z=x8($);return[Z,e1(Z,1)]}function x8($){return fY(6,$)}function _W($,Z,O){let j=Math.min(s1($),6);return R$(gO(J0($,j),Z,O),j)}function qO($,Z,O,j,T,z,J,W,Y,X){if(j===0&&T===1)return $;let D=CZ(j,W)?cO(W)&&j<6&&O>=6?PW:xW:AW,[U,F,G]=D($,Z,O,j,T,z,J,W,Y,X);return G&&j!==7&&(U=((B,K,Q,f,L,V,x,P)=>{let I=H1(B);for(let M=f+1;M<=Q;M++){if(M===7&&Q!==7)continue;let A=a6(M,B);A[k[M]]+=I;let E=q0(w0(x(P(L,V,A)),K));if(E&&Math.sign(E)!==I)break;B=A}return B})(U,F,O,Math.max(6,j),J,W,Y,X)),U}function kO($,Z,O,j,T){if(Z===6){let z=((J)=>J[0]+J[1]/m)($);return[P1(z,O,j),0]}return gO($,_Z(Z,O),j,T)}function gO($,Z,O,j){let[T,z]=$;j&&z<0&&(z+=m,T-=1);let[J,W]=X1(P1(z,Z,O),m);return xj(T+J,W)}function P1($,Z,O){return P8($/Z,O)*Z}function P8($,Z){return kY[Z]($)}function xW($,Z,O,j,T,z){let J=H1($),W=J0($),Y=kO(W,j,T,z),X=w0(W,Y),D=Math.sign(Y[0]-W[0])===J,U=R$(Y,Math.min(O,6));return[{...$,...U},S$(Z,X),D]}function PW($,Z,O,j,T,z,J,W,Y,X){let D=H1($),U=q0(J0($,5)),F=_Z(j,T),G=P1(U,F,z),[B,K]=pj(J,{...$,...n6},6,D,W,Y,X),Q=G-q0(w0(B,K)),f=0;Q&&Math.sign(Q)!==D?Z=N$(B,G):(f+=D,G=P1(Q,F,z),Z=N$(K,G));let L=dO(G);return[{...$,...L,days:$.days+f},Z,Boolean(f)]}function AW($,Z,O,j,T,z,J,W,Y,X){let D=H1($),U=k[j],F=a6(j,$);j===7&&($={...$,weeks:$.weeks+Math.trunc($.days/7)});let G=SO($[U],T)*T;F[U]=G;let[B,K]=pj(J,F,j,T*D,W,Y,X),Q=G+hj(Z,B,K)*D*T,f=P1(Q,T,z),L=Math.sign(f-Q)===D;return F[U]=f,[F,L?K:B,L]}function lj($,Z,O,j){let[T,z,J,W]=((X)=>{let D=qj(X=l0(X));return[X.timeZone,...D]})(j),Y=T!==void 0;return((X,D,U,F,G,B)=>{U=gO(U,G,F,1);let K=D.getOffsetNanosecondsFor(U);return oj(A1(U,K),B)+(X?r1(CO(K)):"Z")})(Y,Z(Y?$(T):J$),O.epochNanoseconds,z,J,W)}function dj($,Z,O){let[j,T,z,J,W,Y]=((X)=>{X=l0(X);let D=$T(X),U=D8(X),F=qY(X),G=wZ(X,4),B=RZ(X,4);return[D,wY(X),F,G,...X8(B,U)]})(O);return((X,D,U,F,G,B,K,Q,f,L)=>{F=gO(F,f,Q,1);let V=X(U).getOffsetNanosecondsFor(F);return oj(A1(F,V),L)+r1(CO(V),K)+((x,P)=>P!==1?"["+(P===2?"!":"")+X0(x)+"]":"")(U,B)+rj(D,G)})($,Z.calendar,Z.timeZone,Z.epochNanoseconds,j,T,z,J,W,Y)}function ij($,Z){let[O,j,T,z]=((X)=>(X=l0(X),[$T(X),...qj(X)]))(Z);return J=$.calendar,W=O,Y=z,oj(N8($,T,j),Y)+rj(J,W);var J,W,Y}function uj($,Z){return O=$.calendar,j=$,T=wj(Z),fO(j)+rj(O,T);var O,j,T}function sj($,Z){return A8($.calendar,H8,$,wj(Z))}function nj($,Z){return A8($.calendar,HW,$,wj(Z))}function aj($,Z){let[O,j,T]=Y8(Z);return z=T,E8(cj($,j,O)[0],z);var z}function yO($,Z){let[O,j,T]=Y8(Z,3);return j>1&&($={...$,..._W($,j,O)}),((z,J)=>{let{sign:W}=z,Y=W===-1?L0(z):z,{hours:X,minutes:D}=Y,[U,F]=Pj(J0(Y,3),m0,_1);y8(U);let G=tj(F,J),B=J>=0||!W||G;return(W<0?"-":"")+"P"+Sz({Y:i1(Y.years),M:i1(Y.months),W:i1(Y.weeks),D:i1(Y.days)})+(X||D||U||B?"T"+Sz({H:i1(X),M:i1(D),S:i1(U,B)+G}):"")})($,T)}function A8($,Z,O,j){let T=X0($),z=j>1||j===0&&T!==R;return j===1?T===R?Z(O):fO(O):z?fO(O)+b8(T,j===2):Z(O)}function Sz($){let Z=[];for(let O in $){let j=$[O];j&&Z.push(j,O)}return Z.join("")}function oj($,Z){return fO($)+"T"+E8($,Z)}function fO($){return H8($)+"-"+y0($.isoDay)}function H8($){let{isoYear:Z}=$;return(Z<0||Z>9999?v8(Z)+BO(6,Math.abs(Z)):BO(4,Z))+"-"+y0($.isoMonth)}function HW($){return y0($.isoMonth)+"-"+y0($.isoDay)}function E8($,Z){let O=[y0($.isoHour),y0($.isoMinute)];return Z!==-1&&O.push(y0($.isoSecond)+((j,T,z,J)=>tj(j*e0+T*j$+z,J))($.isoMillisecond,$.isoMicrosecond,$.isoNanosecond,Z)),O.join(":")}function r1($,Z=0){if(Z===1)return"";let[O,j]=X1(Math.abs($),j3),[T,z]=X1(j,O3),[J,W]=X1(z,m0);return v8($)+y0(O)+":"+y0(T)+(J||W?":"+y0(J)+tj(W):"")}function rj($,Z){if(Z!==1){let O=X0($);if(Z>1||Z===0&&O!==R)return b8(O,Z===2)}return""}function b8($,Z){return"["+(Z?"!":"")+"u-ca="+$+"]"}function tj($,Z){let O=BO(9,$);return O=Z===void 0?O.replace(mY,""):O.slice(0,Z),O?"."+O:""}function v8($){return $<0?"-":"+"}function i1($,Z){return $||Z?$.toLocaleString("fullwide",{useGrouping:0}):""}function EW($,Z){let{epochNanoseconds:O}=$,j=(Z.getOffsetNanosecondsFor?Z:Z($.timeZone)).getOffsetNanosecondsFor(O),T=A1(O,j);return{calendar:$.calendar,...T,offsetNanoseconds:j}}function R8($,Z){let O=I0(Z,$);return{calendar:Z.calendar,...E0(h2,O),offset:r1(O.offsetNanoseconds),timeZone:Z.timeZone}}function t1($,Z,O,j=0,T=0,z,J){if(O!==void 0&&j===1&&(j===1||J))return Ej(Z,O);let W=$.getPossibleInstantsFor(Z);if(O!==void 0&&j!==3){let Y=((X,D,U,F)=>{let G=C0(D);F&&(U=CO(U));for(let B of X){let K=q0(w0(B,G));if(F&&(K=CO(K)),K===U)return B}})(W,Z,O,z);if(Y!==void 0)return Y;if(j===0)throw RangeError(jY)}return J?C0(Z):H0($,Z,T,W)}function H0($,Z,O=0,j=$.getPossibleInstantsFor(Z)){if(j.length===1)return j[0];if(O===1)throw RangeError(TY);if(j.length)return j[O===3?1:0];let T=C0(Z),z=((W,Y)=>{let X=W.getOffsetNanosecondsFor(N$(Y,-m));return $6(W.getOffsetNanosecondsFor(N$(Y,m))-X)})($,T),J=z*(O===2?-1:1);return(j=$.getPossibleInstantsFor(A1(T,J)))[O===2?0:j.length-1]}function ej($){if(Math.abs($)>=m)throw RangeError(ZY);return $}function $6($){if($>m)throw RangeError(OY);return $}function Z6($,Z,O){return Y0(k0(S$(Z.epochNanoseconds,((j)=>{if(m8(j))throw RangeError(WY);return J0(j,5)})($?L0(O):O))))}function O6($,Z,O,j,T,z=Object.create(null)){let J=Z(j.timeZone),W=$(j.calendar);return{...j,...W6(J,W,j,O?L0(T):T,z)}}function j6($,Z,O,j,T=Object.create(null)){let{calendar:z}=O;return e(Y6($(z),O,Z?L0(j):j,T),z)}function T6($,Z,O,j,T){let{calendar:z}=O;return $0(mO($(z),O,Z?L0(j):j,T),z)}function z6($,Z,O,j,T=Object.create(null)){let z=O.calendar,J=$(z),W=QZ(J,O);Z&&(j=lO(j)),j.sign<0&&(W=J.dateAdd(W,{...D0,months:1}),W=e1(W,-1));let Y=J.dateAdd(W,j,T);return u1(QZ(J,Y),z)}function J6($,Z,O){return d0(w8(Z,$?L0(O):O)[0])}function W6($,Z,O,j,T){let z=J0(j,5),J=O.epochNanoseconds;if(m8(j)){let W=I0(O,$);J=S$(H0($,{...mO(Z,W,{...j,...n6},T),...E0(u0,W)}),z)}else J=S$(J,z),q(T);return{epochNanoseconds:k0(J)}}function Y6($,Z,O,j){let[T,z]=w8(Z,O);return U1({...mO($,Z,{...O,...n6,days:O.days+z},j),...T})}function mO($,Z,O,j){if(O.years||O.months||O.weeks)return $.dateAdd(Z,O,j);q(j);let T=O.days+J0(O,5)[0];return T?S1(e1(Z,T)):Z}function QZ($,Z,O=1){return e1(Z,O-$.day(Z))}function w8($,Z){let[O,j]=J0(Z,5),[T,z]=AO(x1($)+j);return[T,O+z]}function e1($,Z){return Z?{...$,...HO(V0($)+Z*P0)}:$}function pO($,Z,O){let j=$(O.calendar);return cO(O)?[O,j,Z(O.timeZone)]:[{...O,...p0},j]}function X6($){return $?K8:C0}function hO($){return $?v(W6,$):Y6}function D6($){return $?v(vW,$):RW}function cO($){return $&&$.epochNanoseconds}function CZ($,Z){return $<=6-(cO(Z)?1:0)}function F6($,Z,O,j,T,z,J){let W=$(l0(J).relativeTo),Y=Math.max(s1(T),s1(z));if(CZ(Y,W))return l(v$(((K,Q,f,L)=>{let V=S$(J0(K),J0(Q),L?-1:1);if(!Number.isFinite(V[0]))throw RangeError($3);return{...D0,...R$(V,f)}})(T,z,Y,j)));if(!W)throw RangeError(Z3);j&&(z=L0(z));let[X,D,U]=pO(Z,O,W),F=hO(U),G=D6(U),B=F(D,X,T);return l(G(D,X,F(D,B,z),Y))}function q8($,Z,O,j,T){let z=s1(j),[J,W,Y,X,D]=((I,M,A)=>{I=yj(I,LO);let E=e6(I),j0=A(I[l2]),w=kj(I),g=wZ(I,7),i=RZ(I);if(E===void 0&&i===void 0)throw RangeError(YY);return i==null&&(i=0),E==null&&(E=Math.max(i,M)),F8(E,i),w=gj(w,i,1),[E,i,w,g,j0]})(T,z,$),U=Math.max(z,J);if(!cO(D)&&U<=6)return l(v$(((I,M,A,E,j0)=>{let w=kO(J0(I),A,E,j0);return{...D0,...R$(w,M)}})(j,J,W,Y,X)));if(!D)throw RangeError(Z3);let[F,G,B]=pO(Z,O,D),K=X6(B),Q=hO(B),f=D6(B),L=Q(G,F,j),V=f(G,F,L,J),x=j.sign,P=H1(V);if(x&&P&&x!==P)throw RangeError(EZ);return P&&(V=qO(V,K(L),J,W,Y,X,G,F,K,Q)),l(V)}function k8($){return $.sign===-1?lO($):$}function lO($){return l(L0($))}function L0($){let Z={};for(let O of k)Z[O]=-1*$[O]||0;return Z}function g8($){return!$.sign}function H1($,Z=k){let O=0;for(let j of Z){let T=Math.sign($[j]);if(T){if(O&&O!==T)throw RangeError(JY);O=T}}return O}function v$($){for(let Z of QY)g0(Z,$[Z],-Ez,Ez,1);return y8(q0(J0($),m0)),$}function y8($){if(!Number.isSafeInteger($))throw RangeError(zY)}function J0($,Z=6){return mz($,Z,k)}function R$($,Z=6){let[O,j]=$,T=NO(j,Z,k);if(T[k[Z]]+=O*(m/t0[Z]),!Number.isFinite(T[k[Z]]))throw RangeError($3);return T}function dO($,Z=5){return NO($,Z,k)}function m8($){return Boolean(H1($,m2))}function s1($){let Z=9;for(;Z>0&&!$[k[Z]];Z--);return Z}function bW($,Z){return[$,Z]}function Nz($){let Z=Math.floor($/FO)*FO;return[Z,Z+FO]}function p8($){let Z=E1($=GO($));if(!Z)throw RangeError(x0($));let O;if(Z.m)O=0;else{if(!Z.offset)throw RangeError(x0($));O=w$(Z.offset)}return Z.timeZone&&K6(Z.timeZone,1),Y0(Ej(EO(Z),O))}function h8($){let Z=E1(s($));if(!Z)throw RangeError(x0($));if(Z.timeZone)return o8(Z,Z.offset?w$(Z.offset):void 0);if(Z.m)throw RangeError(x0($));return t8(Z)}function c8($,Z){let O=E1(s($));if(!O||!O.timeZone)throw RangeError(x0($));let{offset:j}=O,T=j?w$(j):void 0,[,z,J]=NZ(Z);return o8(O,T,z,J)}function w$($){let Z=K6($);if(Z===void 0)throw RangeError(x0($));return Z}function l8($){let Z=E1(s($));if(!Z||Z.m)throw RangeError(x0($));return e(r8(Z))}function iO($){let Z=E1(s($));if(!Z||Z.m)throw RangeError(x0($));return $0(Z.p?r8(Z):t8(Z))}function d8($,Z){let O=B6(s(Z));if(O)return U6(O),u1(Hj(a1(O)));let j=iO(Z);return u1(QZ($(j.calendar),j))}function U6($){if($.calendar!==R)throw RangeError(D1($.calendar))}function i8($,Z){let O=G6(s(Z));if(O)return U6(O),QO(a1(O));let j=iO(Z),{calendar:T}=j,z=$(T),[J,W,Y]=z.h(j),[X,D]=z.I(J,W),[U,F]=z.N(X,D,Y);return QO(S1(z.P(U,F,Y)),T)}function u8($){let Z,O=((j)=>{let T=dY.exec(j);return T?(uO(T[10]),Z5(T)):void 0})(s($));if(!O){if(O=E1($),!O)throw RangeError(x0($));if(!O.p)throw RangeError(x0($));if(O.m)throw RangeError(D1("Z"));U6(O)}if((Z=B6($))&&Lz(Z))throw RangeError(x0($));if((Z=G6($))&&Lz(Z))throw RangeError(x0($));return d0(bO(O,1))}function s8($){let Z=((O)=>{let j=sY.exec(O);return j?((T)=>{function z(D,U,F){let G=0,B=0;if(F&&([G,Y]=X1(Y,t0[F])),D!==void 0){if(W)throw RangeError(D1(D));B=((K)=>{let Q=parseInt(K);if(!Number.isFinite(Q))throw RangeError(D1(K));return Q})(D),J=1,U&&(Y=Q6(U)*(t0[F]/m0),W=1)}return G+B}let J=0,W=0,Y=0,X={...A$(k,[z(T[2]),z(T[3]),z(T[4]),z(T[5]),z(T[6],T[7],5),z(T[8],T[9],4),z(T[10],T[11],3)]),...NO(Y,2,k)};if(!J)throw RangeError(f2(k));return C6(T[1])<0&&(X=L0(X)),X})(j):void 0})(s($));if(!Z)throw RangeError(x0($));return l(v$(Z))}function n8($){let Z=E1($)||B6($)||G6($);return Z?Z.calendar:$}function a8($){let Z=E1($);return Z&&(Z.timeZone||Z.m&&J$||Z.offset)||$}function o8($,Z,O=0,j=0){let T=sO($.timeZone),z=D3(T);return F0(t1(z,EO($),Z,O,j,!z.v,$.m),T,xZ($.calendar))}function r8($){return e8(U1(EO($)))}function t8($){return e8(S1(a1($)))}function e8($){return{...$,calendar:xZ($.calendar)}}function E1($){let Z=lY.exec($);return Z?((O)=>{let j=O[10],T=(j||"").toUpperCase()==="Z";return{isoYear:$5(O),isoMonth:parseInt(O[4]),isoDay:parseInt(O[5]),...Z5(O.slice(5)),...uO(O[16]),p:Boolean(O[6]),m:T,offset:T?void 0:j}})(Z):void 0}function B6($){let Z=hY.exec($);return Z?((O)=>({isoYear:$5(O),isoMonth:parseInt(O[4]),isoDay:1,...uO(O[5])}))(Z):void 0}function G6($){let Z=cY.exec($);return Z?((O)=>({isoYear:P$,isoMonth:parseInt(O[1]),isoDay:parseInt(O[2]),...uO(O[3])}))(Z):void 0}function K6($,Z){let O=iY.exec($);return O?((j,T)=>{let z=j[4]||j[5];if(T&&z)throw RangeError(D1(z));return ej((M$(j[2])*j3+M$(j[3])*O3+M$(j[4])*m0+Q6(j[5]||""))*C6(j[1]))})(O,Z):void 0}function $5($){let Z=C6($[1]),O=parseInt($[2]||$[3]);if(Z<0&&!O)throw RangeError(D1(-0));return Z*O}function Z5($){let Z=M$($[3]);return{...AO(Q6($[4]||""))[0],isoHour:M$($[1]),isoMinute:M$($[2]),isoSecond:Z===60?59:Z}}function uO($){let Z,O,j=[];if($.replace(uY,(T,z,J)=>{let W=Boolean(z),[Y,X]=J.split("=").reverse();if(X){if(X==="u-ca")j.push(Y),Z||(Z=W);else if(W||/[A-Z]/.test(X))throw RangeError(D1(T))}else{if(O)throw RangeError(D1(T));O=Y}return""}),j.length>1&&Z)throw RangeError(D1($));return{timeZone:O,calendar:j[0]||R}}function Q6($){return parseInt($.padEnd(9,"0"))}function q$($){return new RegExp(`^${$}$`,"i")}function C6($){return $&&$!=="+"?-1:1}function M$($){return $===void 0?0:parseInt($)}function O5($){return sO(s($))}function sO($){let Z=f6($);return typeof Z=="number"?r1(Z):Z?((O)=>{if(aY.test(O))throw RangeError($Y);return O.toLowerCase().split("/").map((j,T)=>(j.length<=3||/\d/.test(j))&&!/etc|yap/.test(j)?j.toUpperCase():j.replace(/baja|dumont|[a-z]+/g,(z,J)=>z.length<=2&&!T||z==="in"||z==="chat"?z.toUpperCase():z.length>2||!J?Vz(z).replace(/island|noronha|murdo|rivadavia|urville/,Vz):z)).join("/")})($):J$}function _z($){let Z=f6($);return typeof Z=="number"?Z:Z?Z.resolvedOptions().timeZone:J$}function f6($){let Z=K6($=$.toUpperCase(),1);return Z!==void 0?Z:$!==J$?nY($):void 0}function V6($,Z){return f0($.epochNanoseconds,Z.epochNanoseconds)}function I6($,Z){return f0($.epochNanoseconds,Z.epochNanoseconds)}function j5($,Z,O,j,T,z){let J=$(l0(z).relativeTo),W=Math.max(s1(j),s1(T));if(gz(k,j,T))return 0;if(CZ(W,J))return f0(J0(j),J0(T));if(!J)throw RangeError(Z3);let[Y,X,D]=pO(Z,O,J),U=X6(D),F=hO(D);return f0(U(F(X,Y,j)),U(F(X,Y,T)))}function L6($,Z){return $$($,Z)||nO($,Z)}function $$($,Z){return M1(V0($),V0(Z))}function nO($,Z){return M1(x1($),x1(Z))}function T5($,Z){return!V6($,Z)}function z5($,Z){return!I6($,Z)&&!!aO($.timeZone,Z.timeZone)&&b$($.calendar,Z.calendar)}function J5($,Z){return!L6($,Z)&&b$($.calendar,Z.calendar)}function W5($,Z){return!$$($,Z)&&b$($.calendar,Z.calendar)}function Y5($,Z){return!$$($,Z)&&b$($.calendar,Z.calendar)}function X5($,Z){return!$$($,Z)&&b$($.calendar,Z.calendar)}function D5($,Z){return!nO($,Z)}function aO($,Z){if($===Z)return 1;let O=X0($),j=X0(Z);if(O===j)return 1;try{return _z(O)===_z(j)}catch(T){}}function M6($,Z,O,j){let T=E$($,t(j),3,5),z=oO(Z.epochNanoseconds,O.epochNanoseconds,...T);return l($?L0(z):z)}function S6($,Z,O,j,T,z){let J=tO(j.calendar,T.calendar),W=t(z),[Y,X,D,U]=E$(O,W,5),F=j.epochNanoseconds,G=T.epochNanoseconds,B=f0(G,F),K;if(B)if(Y<6)K=oO(F,G,Y,X,D,U);else{let Q=Z(((L,V)=>{if(!aO(L,V))throw RangeError(N2);return L})(j.timeZone,T.timeZone)),f=$(J);K=U5(f,Q,j,T,B,Y,W),K=qO(K,G,Y,X,D,U,f,j,K8,v(W6,Q))}else K=D0;return l(O?L0(K):K)}function N6($,Z,O,j,T){let z=tO(O.calendar,j.calendar),J=t(T),[W,Y,X,D]=E$(Z,J,6),U=C0(O),F=C0(j),G=f0(F,U),B;if(G)if(W<=6)B=oO(U,F,W,Y,X,D);else{let K=$(z);B=B5(K,O,j,G,W,J),B=qO(B,F,W,Y,X,D,K,O,C0,Y6)}else B=D0;return l(Z?L0(B):B)}function _6($,Z,O,j,T){let z=tO(O.calendar,j.calendar),J=t(T);return F5(Z,()=>$(z),O,j,...E$(Z,J,6,9,6),J)}function x6($,Z,O,j,T){let z=tO(O.calendar,j.calendar),J=t(T),W=E$(Z,J,9,9,8),Y=$(z);return F5(Z,()=>Y,QZ(Y,O),QZ(Y,j),...W,J)}function F5($,Z,O,j,T,z,J,W,Y){let X=C0(O),D=C0(j),U;if(f0(D,X))if(T===6)U=oO(X,D,T,z,J,W);else{let F=Z();U=F.dateUntil(O,j,T,Y),z===6&&J===1||(U=qO(U,D,T,z,J,W,F,O,C0,mO))}else U=D0;return l($?L0(U):U)}function P6($,Z,O,j){let T=t(j),[z,J,W,Y]=E$($,T,5,5),X=P1(A6(Z,O),_Z(J,W),Y),D={...D0,...dO(X,z)};return l($?L0(D):D)}function vW($,Z,O,j,T,z){let J=f0(j.epochNanoseconds,O.epochNanoseconds);return J?T<6?G5(O.epochNanoseconds,j.epochNanoseconds,T):U5(Z,$,O,j,J,T,z):D0}function RW($,Z,O,j,T){let z=C0(Z),J=C0(O),W=f0(J,z);return W?j<=6?G5(z,J,j):B5($,Z,O,W,j,T):D0}function U5($,Z,O,j,T,z,J){let[W,Y,X]=((F,G,B,K)=>{function Q(){return M={...e1(V,P++*-K),...L},A=H0(F,M),f0(x,A)===-K}let f=I0(G,F),L=E0(u0,f),V=I0(B,F),x=B.epochNanoseconds,P=0,I=A6(f,V),M,A;if(Math.sign(I)===-K&&P++,Q()&&(K===-1||Q()))throw RangeError(EZ);let E=q0(w0(A,x));return[f,M,E]})(Z,O,j,T);var D,U;return{...z===6?(D=W,U=Y,{...D0,days:K5(D,U)}):$.dateUntil(W,Y,z,J),...dO(X)}}function B5($,Z,O,j,T,z){let[J,W,Y]=((X,D,U)=>{let F=D,G=A6(X,D);return Math.sign(G)===-U&&(F=e1(D,-U),G+=m*U),[X,F,G]})(Z,O,j);return{...$.dateUntil(J,W,T,z),...dO(Y)}}function oO($,Z,O,j,T,z){return{...D0,...R$(kO(w0($,Z),j,T,z),O)}}function G5($,Z,O){return{...D0,...R$(w0($,Z),O)}}function K5($,Z){return rO(V0($),V0(Z))}function rO($,Z){return Math.trunc((Z-$)/P0)}function A6($,Z){return x1(Z)-x1($)}function tO($,Z){if(!b$($,Z))throw RangeError(l6);return $}function wW($){function Z(T){return((z,J)=>({...Q5(z,J),F:z.month,day:parseInt(z.day)}))(Aj(O,T),j)}let O=TT($),j=VO($);return{id:$,O:qW(Z),B:kW(Z)}}function qW($){return A0((Z)=>{let O=V0(Z);return $(O)},WeakMap)}function kW($){let Z=$(0).year-MY;return A0((O)=>{let j,T=H$(O-Z),z=[],J=[];do T+=400*P0;while((j=$(T)).year<=O);do T+=(1-j.day)*P0,j.year===O&&(z.push(T),J.push(j.F)),T-=P0;while((j=$(T)).year>=O);return{k:z.reverse(),C:P2(J.reverse())}})}function Q5($,Z){let O,j,T=C5($);if($.era){let z=k2[Z];z!==void 0&&(O=Z==="islamic"?"ah":$.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g,""),O==="bc"||O==="b"?O="bce":O!=="ad"&&O!=="a"||(O="ce"),j=T,T=M5(j,z[O]||0))}return{era:O,eraYear:j,year:T}}function C5($){return parseInt($.relatedYear||$.year)}function Uj($){let{year:Z,F:O,day:j}=this.O($),{C:T}=this.B(Z);return[Z,T[O]+1,j]}function fZ($,Z=1,O=1){return this.B($).k[Z-1]+(O-1)*P0}function YO($){let Z=Pz(this,$),O=Pz(this,$-1),j=Z.length;if(j>O.length){let T=S5(this);if(T<0)return-T;for(let z=0;z<j;z++)if(Z[z]!==O[z])return z+1}}function XO($){return rO(fZ.call(this,$),fZ.call(this,$+1))}function xz($,Z){let{k:O}=this.B($),j=Z+1,T=O;return j>O.length&&(j=1,T=this.B($+1).k),rO(O[Z-1],T[j-1])}function DO($){return this.B($).k.length}function Pz($,Z){return Object.keys($.B(Z).C)}function f5($){return xZ(s($))}function xZ($){if(($=$.toLowerCase())!==R&&$!==z3&&VO($)!==VO(TT($).resolvedOptions().calendar))throw RangeError(eW($));return $}function VO($){return $==="islamicc"&&($="islamic"),$.split("-")[0]}function V5($){return this.R($)[0]}function I5($){return this.R($)[1]}function H6($){let[Z]=this.h($);return rO(this.q(Z),V0($))+1}function L5($){let Z=rY.exec($);if(!Z)throw RangeError(rW($));return[parseInt(Z[1]),Boolean(Z[2])]}function IO($,Z,O){return $+(Z||O&&$>=O?1:0)}function Bj($,Z){return $-(Z&&$>=Z?1:0)}function M5($,Z){return(Z+$)*(Math.sign(Z)||1)||0}function Gj($){return k2[N5($)]}function S5($){return BY[N5($)]}function N5($){return VO($.id||R)}function _5($,Z,O,j){let T=b1(O,j,i0,[],v2);if(T.timeZone!==void 0){let z=O.dateFromFields(T),J=Z$(T),W=$(T.timeZone);return{epochNanoseconds:t1(Z(W),{...z,...J},T.offset!==void 0?w$(T.offset):void 0),timeZone:W}}return{...O.dateFromFields(T),...p0}}function x5($,Z,O,j,T,z){let J=b1(O,T,i0,E2,v2),W=$(J.timeZone),[Y,X,D]=NZ(z),U=O.dateFromFields(J,RO(z,Y)),F=Z$(J,Y);return F0(t1(Z(W),{...U,...F},J.offset!==void 0?w$(J.offset):void 0,X,D),W,j)}function P5($,Z,O){let j=b1($,Z,i0,[],K1),T=q(O);return e(U1({...$.dateFromFields(j,RO(O,T)),...Z$(j,T)}))}function E6($,Z,O,j=[]){let T=b1($,Z,i0,j);return $.dateFromFields(T,O)}function b6($,Z,O,j){let T=b1($,Z,u6,j);return $.yearMonthFromFields(T,O)}function v6($,Z,O,j,T=[]){let z=b1($,O,i0,T);return Z&&z.month!==void 0&&z.monthCode===void 0&&z.year===void 0&&(z.year=P$),$.monthDayFromFields(z,j)}function A5($,Z){let O=q(Z);return d0(Z$(r0($,Qj,[],1),O))}function H5($){let Z=r0($,s6);return l(v$({...D0,...Z}))}function b1($,Z,O,j=[],T=[]){return r0(Z,[...$.fields(O),...T].sort(),j)}function r0($,Z,O,j=!O){let T={},z,J=0;for(let W of Z){if(W===z)throw RangeError(iW(W));if(W==="constructor"||W==="__proto__")throw RangeError(h6(W));let Y=$[W];if(Y!==void 0)J=1,bz[W]&&(Y=bz[W](Y,W)),T[W]=Y;else if(O){if(O.includes(W))throw TypeError(p6(W));T[W]=q2[W]}z=W}if(j&&!J)throw TypeError(f2(Z));return T}function Z$($,Z){return bO(Z9({...q2,...$}),Z)}function E5($,Z,O,j,T,z){let J=t(z),{calendar:W,timeZone:Y}=O;return F0(((X,D,U,F,G)=>{let B=PZ(X,U,F,i0,b2,H2),[K,Q,f]=NZ(G,2);return t1(D,{...X.dateFromFields(B,RO(G,K)),...Z$(B,K)},w$(B.offset),Q,f)})($(W),Z(Y),j,T,J),Y,W)}function b5($,Z,O,j,T){let z=t(T);return e(((J,W,Y,X)=>{let D=PZ(J,W,Y,i0,K1),U=q(X);return U1({...J.dateFromFields(D,RO(X,U)),...Z$(D,U)})})($(Z.calendar),O,j,z))}function v5($,Z,O,j,T){let z=t(T);return((J,W,Y,X)=>{let D=PZ(J,W,Y,i0);return J.dateFromFields(D,X)})($(Z.calendar),O,j,z)}function R5($,Z,O,j,T){let z=t(T);return u1(((J,W,Y,X)=>{let D=PZ(J,W,Y,u6);return J.yearMonthFromFields(D,X)})($(Z.calendar),O,j,z))}function w5($,Z,O,j,T){let z=t(T);return((J,W,Y,X)=>{let D=PZ(J,W,Y,i0);return J.monthDayFromFields(D,X)})($(Z.calendar),O,j,z)}function q5($,Z,O){return d0(((j,T,z)=>{let J=q(z);return Z$({...E0(Qj,j),...r0(T,Qj)},J)})($,Z,O))}function k5($,Z){return l((O=$,j=Z,v$({...O,...r0(j,s6)})));var O,j}function PZ($,Z,O,j,T=[],z=[]){let J=[...$.fields(j),...T].sort(),W=r0(Z,J,z),Y=r0(O,J);return W=$.mergeFields(W,Y),r0(W,J,[])}function R6($,Z){let O=b1($,Z,w2);return $.monthDayFromFields(O)}function w6($,Z,O){let j=b1($,Z,R2);return $.yearMonthFromFields(j,O)}function g5($,Z,O,j,T){Z=E0(O=$.fields(O),Z),j=r0(j,T=$.fields(T),[]);let z=$.mergeFields(Z,j);return z=r0(z,[...O,...T].sort(),[]),$.dateFromFields(z)}function Wj($,Z){let{era:O,eraYear:j,year:T}=Z,z=Gj($);if(O!==void 0||j!==void 0){if(O===void 0||j===void 0)throw TypeError(sW);if(!z)throw RangeError(uW);let J=z[O];if(J===void 0)throw RangeError(aW(O));let W=M5(j,J);if(T!==void 0&&T!==W)throw RangeError(nW);T=W}else if(T===void 0)throw TypeError(oW(z));return T}function Yj($,Z,O,j){let{month:T,monthCode:z}=Z;if(z!==void 0){let J=((W,Y,X,D)=>{let U=W.U(X),[F,G]=L5(Y),B=IO(F,G,U);if(G){let K=S5(W);if(K===void 0)throw RangeError(BZ);if(K>0){if(B>K)throw RangeError(BZ);if(U===void 0){if(D===1)throw RangeError(BZ);B--}}else{if(B!==-K)throw RangeError(BZ);if(U===void 0&&D===1)throw RangeError(BZ)}}return B})($,z,O,j);if(T!==void 0&&T!==J)throw RangeError(M2);T=J,j=1}else if(T===void 0)throw TypeError(tW);return g0("month",T,1,$.L(O),j)}function Az($,Z,O,j,T){return _0(Z,"day",1,$.j(j,O),T)}function Xj($,Z,O,j){let T=0,z=[];for(let J of O)Z[J]!==void 0?T=1:z.push(J);if(Object.assign($,Z),T)for(let J of j||z)delete $[J]}function y5($){return Y0(k0(PO(xO($))))}function m5($,Z,O,j,T=R){return F0(k0(PO(xO(O))),Z(j),$(T))}function p5($,Z,O,j,T=0,z=0,J=0,W=0,Y=0,X=0,D=R){return e(U1(EO(h0(Q0,A$(J3,[Z,O,j,T,z,J,W,Y,X])))),$(D))}function h5($,Z,O,j,T=R){return $0(S1(a1(h0(Q0,{isoYear:Z,isoMonth:O,isoDay:j}))),$(T))}function c5($,Z,O,j=R,T=1){let z=Q0(Z),J=Q0(O),W=$(j);return u1(Hj(a1({isoYear:z,isoMonth:J,isoDay:Q0(T)})),W)}function l5($,Z,O,j=R,T=P$){let z=Q0(Z),J=Q0(O),W=$(j);return QO(S1(a1({isoYear:Q0(T),isoMonth:z,isoDay:J})),W)}function d5($=0,Z=0,O=0,j=0,T=0,z=0){return d0(bO(h0(Q0,A$(u0,[$,Z,O,j,T,z])),1))}function i5($=0,Z=0,O=0,j=0,T=0,z=0,J=0,W=0,Y=0,X=0){return l(v$(h0(az,A$(k,[$,Z,O,j,T,z,J,W,Y,X]))))}function q6($,Z,O=R){return F0($.epochNanoseconds,Z,O)}function u5($){return Y0($.epochNanoseconds)}function k6($,Z){return e(I0(Z,$))}function g6($,Z){return $0(I0(Z,$))}function s5($,Z,O){return w6($(Z.calendar),O)}function n5($,Z,O){return R6($(Z.calendar),O)}function y6($,Z){return d0(I0(Z,$))}function a5($,Z,O,j){let T=((z,J,W,Y)=>{let X=Rj(Y);return H0(z(J),W,X)})($,O,Z,j);return F0(k0(T),O,Z.calendar)}function o5($,Z,O){let j=$(Z.calendar);return u1({...Z,...w6(j,O)})}function r5($,Z,O){return R6($(Z.calendar),O)}function t5($,Z,O,j,T){let z=$(T.timeZone),J=T.plainTime,W=J!==void 0?Z(J):p0;return F0(H0(O(z),{...j,...W}),z,j.calendar)}function e5($,Z=p0){return e(U1({...$,...Z}))}function $2($,Z,O){return w6($(Z.calendar),O)}function Z2($,Z,O){return R6($(Z.calendar),O)}function O2($,Z,O,j){return((T,z,J)=>g5(T,z,R2,F1(J),vZ))($(Z.calendar),O,j)}function j2($,Z,O,j){return((T,z,J)=>g5(T,z,w2,F1(J),T3))($(Z.calendar),O,j)}function T2($,Z,O,j,T){let z=F1(T),J=Z(z.plainDate),W=$(z.timeZone);return F0(H0(O(W),{...J,...j}),W,J.calendar)}function z2($,Z){return e(U1({...$,...Z}))}function J2($){return Y0(k0(_$($,m0)))}function W2($){return Y0(k0(_$($,e0)))}function Y2($){return Y0(k0(PO(xO($),j$)))}function X2($){return Y0(k0(PO(xO($))))}function D2($,Z,O=p0){let j=Z.timeZone,T=$(j),z={...I0(Z,T),...O};return F0(t1(T,z,z.offsetNanoseconds,2),j,Z.calendar)}function F2($,Z,O){let j=Z.timeZone,T=$(j),z={...I0(Z,T),...O},J=K2(Z.calendar,O.calendar);return F0(t1(T,z,z.offsetNanoseconds,2),j,J)}function U2($,Z=p0){return e({...$,...Z})}function B2($,Z){return e({...$,...Z},K2($.calendar,Z.calendar))}function eO($,Z){return{...$,calendar:Z}}function G2($,Z){return{...$,timeZone:Z}}function K2($,Z){if($===Z)return $;let O=X0($),j=X0(Z);if(O===j||O===R)return Z;if(j===R)return $;throw RangeError(l6)}function gW($,Z){return(O)=>O===R?$:O===z3||O===x$?Object.assign(Object.create($),{id:O}):Object.assign(Object.create(Z),oY(O))}function O$($,Z,O){let j=new Set(O);return(T)=>(((z,J)=>{for(let W of J)if(W in z)return 1;return 0})(T=Ij(j,T),$)||Object.assign(T,Z),O&&(T.timeZone=J$,["full","long"].includes(T.timeStyle)&&(T.timeStyle="medium")),T)}function B1($,Z=m6){let[O,,,j]=$;return(T,z=C9,...J)=>{let W=Z(j&&j(...J),T,z,O),Y=W.resolvedOptions();return[W,...yW($,Y,J)]}}function m6($,Z,O,j){if(O=j(O),$){if(O.timeZone!==void 0)throw TypeError(DY);O.timeZone=$}return new v1(Z,O)}function yW($,Z,O){let[,j,T]=$;return O.map((z)=>(z.calendar&&((J,W,Y)=>{if((Y||J!==R)&&J!==W)throw RangeError(l6)})(X0(z.calendar),Z.calendar,T),j(z,Z)))}function k$($){let Z=AZ();return A1(Z,$.getOffsetNanosecondsFor(Z))}function AZ(){return _$(Date.now(),e0)}function G1(){return Rz||(Rz=new v1().resolvedOptions().timeZone)}var mW=($,Z)=>`Non-integer ${$}: ${Z}`,pW=($,Z)=>`Non-positive ${$}: ${Z}`,hW=($,Z)=>`Non-finite ${$}: ${Z}`,cW=($)=>`Cannot convert bigint to ${$}`,lW=($)=>`Invalid bigint: ${$}`,dW="Cannot convert Symbol to string",Q2="Invalid object",C2=($,Z,O,j,T)=>T?C2($,T[Z],T[O],T[j]):HZ($,Z)+`; must be between ${O}-${j}`,HZ=($,Z)=>`Invalid ${$}: ${Z}`,p6=($)=>`Missing ${$}`,h6=($)=>`Invalid field ${$}`,iW=($)=>`Duplicate field ${$}`,f2=($)=>"No valid fields: "+$.join(),V2="Invalid bag",I2=($,Z,O)=>HZ($,Z)+"; must be "+Object.keys(O).join(),L2="Cannot use valueOf",c6="Invalid calling context",uW="Forbidden era/eraYear",sW="Mismatching era/eraYear",nW="Mismatching year/eraYear",aW=($)=>`Invalid era: ${$}`,oW=($)=>"Missing year"+($?"/era/eraYear":""),rW=($)=>`Invalid monthCode: ${$}`,M2="Mismatching month/monthCode",tW="Missing month/monthCode",Hz="Cannot guess year",BZ="Invalid leap month",S2="Invalid protocol",EZ="Invalid protocol results",l6="Mismatching Calendars",eW=($)=>`Invalid Calendar: ${$}`,N2="Mismatching TimeZones",$Y="Forbidden ICU TimeZone",ZY="Out-of-bounds offset",OY="Out-of-bounds TimeZone gap",jY="Invalid TimeZone offset",TY="Ambiguous offset",$3="Out-of-bounds date",zY="Out-of-bounds duration",JY="Cannot mix duration signs",Z3="Missing relativeTo",WY="Cannot use large units",YY="Required smallestUnit or largestUnit",XY="smallestUnit > largestUnit",x0=($)=>`Cannot parse: ${$}`,D1=($)=>`Invalid substring: ${$}`,_2=($)=>`Cannot format ${$}`,x2="Mismatching types for formatting",DY="Cannot specify TimeZone",P2=v(LZ,($,Z)=>Z),g$=v(LZ,($,Z,O)=>O),y0=v(BO,2),Kj={nanosecond:0,microsecond:1,millisecond:2,second:3,minute:4,hour:5,day:6,week:7,month:8,year:9},bZ=Object.keys(Kj),P0=86400000,A2=1000,j$=1000,e0=1e6,m0=1e9,O3=60000000000,j3=3600000000000,m=86400000000000,t0=[1,j$,e0,m0,O3,j3,m],K1=bZ.slice(0,6),Qj=MZ(K1),H2=["offset"],E2=["timeZone"],b2=K1.concat(H2),v2=b2.concat(E2),Cj=["era","eraYear"],FY=Cj.concat(["year"]),T3=["year"],d6=["monthCode"],i6=["month"].concat(d6),vZ=["day"],u6=i6.concat(T3),R2=d6.concat(T3),i0=vZ.concat(u6),UY=vZ.concat(i6),w2=vZ.concat(d6),q2=g$(K1,0),R="iso8601",z3="gregory",x$="japanese",k2={[z3]:{bce:-1,ce:0},[x$]:{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}},BY={chinese:13,dangi:13,hebrew:-6},s=v(_O,"string"),g2=v(_O,"boolean"),GY=v(_O,"number"),y2=v(_O,"function"),k=bZ.map(($)=>$+"s"),s6=MZ(k),KY=k.slice(0,6),m2=k.slice(6),QY=m2.slice(1),CY=P2(k),D0=g$(k,0),n6=g$(KY,0),a6=v(yz,k),u0=["isoNanosecond","isoMicrosecond","isoMillisecond","isoSecond","isoMinute","isoHour"],o6=["isoDay","isoMonth","isoYear"],J3=u0.concat(o6),r6=MZ(o6),p2=MZ(u0),h2=MZ(J3),p0=g$(p2,0),fY=v(yz,J3),v1=Intl.DateTimeFormat,c2="en-GB",t6=1e8,VY=t6*P0,IY=[t6,0],LY=[-t6,0],VZ=275760,IZ=-271821,MY=1970,P$=1972,Y1=12,SY=H$(1868,9,8),NY=A0(NW,WeakMap),LO="smallestUnit",fj="unit",KZ="roundingIncrement",Dj="fractionalSecondDigits",l2="relativeTo",d2={constrain:0,reject:1},_Y=Object.keys(d2),xY={compatible:0,reject:1,earlier:2,later:3},PY={reject:0,use:1,prefer:2,ignore:3},AY={auto:0,never:1,critical:2,always:3},HY={auto:0,never:1,critical:2},EY={auto:0,never:1},bY={floor:0,halfFloor:1,ceil:2,halfCeil:3,trunc:4,halfTrunc:5,expand:6,halfExpand:7,halfEven:8},RZ=v(mj,LO),e6=v(mj,"largestUnit"),vY=v(mj,fj),i2=v(o1,"overflow",d2),u2=v(o1,"disambiguation",xY),RY=v(o1,"offset",PY),$T=v(o1,"calendarName",AY),wY=v(o1,"timeZoneName",HY),qY=v(o1,"offset",EY),wZ=v(o1,"roundingMode",bY),y$="PlainYearMonth",m$="PlainMonthDay",T$="PlainDate",z$="PlainDateTime",W3="PlainTime",Q1="ZonedDateTime",Y3="Instant",X3="Duration",kY=[Math.floor,($)=>WO($)?Math.floor($):Math.round($),Math.ceil,($)=>WO($)?Math.ceil($):Math.round($),Math.trunc,($)=>WO($)?Math.trunc($)||0:Math.round($),($)=>$<0?Math.floor($):Math.ceil($),($)=>Math.sign($)*Math.round(Math.abs($))||0,($)=>WO($)?($=Math.trunc($)||0)+$%2:Math.round($)],J$="UTC",FO=5184000,gY=KO(1847),yY=KO(new Date().getUTCFullYear()+10),mY=/0+$/,I0=A0(EW,WeakMap),Ez=4294967295,D3=A0(($)=>{let Z=f6($);return typeof Z=="object"?new n2(Z):new s2(Z||0)});class s2{constructor($){this.v=$}getOffsetNanosecondsFor(){return this.v}getPossibleInstantsFor($){return[Ej($,this.v)]}l(){}}class n2{constructor($){this.$=((Z)=>{function O(Y){let X=Fj(Y,J,W),[D,U]=Nz(X),F=T(D),G=T(U);return F===G?F:j(z(D,U),F,G,Y)}function j(Y,X,D,U){let F,G;for(;(U===void 0||(F=U<Y[0]?X:U>=Y[1]?D:void 0)===void 0)&&(G=Y[1]-Y[0]);){let B=Y[0]+Math.floor(G/2);Z(B)===D?Y[1]=B:Y[0]=B+1}return F}let T=A0(Z),z=A0(bW),J=gY,W=yY;return{G(Y){let X=O(Y-86400),D=O(Y+86400),U=Y-X,F=Y-D;if(X===D)return[U];let G=O(U);return G===O(F)?[Y-G]:X>D?[U,F]:[]},V:O,l(Y,X){let D=Fj(Y,J,W),[U,F]=Nz(D),G=FO*X,B=X<0?()=>F>J||(J=D,0):()=>U<W||(W=D,0);for(;B();){let K=T(U),Q=T(F);if(K!==Q){let f=z(U,F);j(f,K,Q);let L=f[0];if((M1(L,Y)||1)===X)return L}U+=G,F+=G}}}})(((Z)=>(O)=>{let j=Aj(Z,O*A2);return KO(C5(j),parseInt(j.month),parseInt(j.day),parseInt(j.hour),parseInt(j.minute),parseInt(j.second))-O})($))}getOffsetNanosecondsFor($){return this.$.V(tz($))*m0}getPossibleInstantsFor($){let[Z,O]=[KO((j=$).isoYear,j.isoMonth,j.isoDay,j.isoHour,j.isoMinute,j.isoSecond),j.isoMillisecond*e0+j.isoMicrosecond*j$+j.isoNanosecond];var j;return this.$.G(Z).map((T)=>k0(N$(_$(T,m0),O)))}l($,Z){let[O,j]=ez($),T=this.$.l(O+(Z>0||j?1:0),Z);if(T!==void 0)return _$(T,m0)}}var ZT="([+\u2212-])",UO="(?:[.,](\\d{1,9}))?",a2=`(?:(?:${ZT}(\\d{6}))|(\\d{4}))-?(\\d{2})`,OT="(\\d{2})(?::?(\\d{2})(?::?(\\d{2})"+UO+")?)?",jT=ZT+OT,pY=a2+"-?(\\d{2})(?:[T ]"+OT+"(Z|"+jT+")?)?",o2="\\[(!?)([^\\]]*)\\]",F3=`((?:${o2}){0,9})`,hY=q$(a2+F3),cY=q$("(?:--)?(\\d{2})-?(\\d{2})"+F3),lY=q$(pY+F3),dY=q$("T?"+OT+"(?:"+jT+")?"+F3),iY=q$(jT),uY=new RegExp(o2,"g"),sY=q$(`${ZT}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${UO}H)?(?:(\\d+)${UO}M)?(?:(\\d+)${UO}S)?)?`),nY=A0(($)=>new v1(c2,{timeZone:$,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),aY=/^(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$/,oY=A0(wW),TT=A0(($)=>new v1(c2,{calendar:$,timeZone:J$,era:"short",year:"numeric",month:"short",day:"numeric"})),rY=/^M(\d{2})(L?)$/,tY={era:GO,eraYear:Q0,year:Q0,month:Iz,monthCode:GO,day:Iz},eY=g$(K1,Q0),$9=g$(k,az),bz=Object.assign({},tY,eY,$9,{offset:GO}),Z9=v(SW,K1,u0),vz={dateAdd($,Z,O){let j=q(O),T,{years:z,months:J,weeks:W,days:Y}=Z;if(Y+=J0(Z,5)[0],z||J)T=((X,D,U,F,G)=>{let[B,K,Q]=X.h(D);if(U){let[f,L]=X.I(B,K);B+=U,K=IO(f,L,X.U(B)),K=g0("month",K,1,X.L(B),G)}return F&&([B,K]=X._(B,K,F)),Q=g0("day",Q,1,X.j(B,K),G),X.q(B,K,Q)})(this,$,z,J,j);else{if(!W&&!Y)return $;T=V0($)}return T+=(7*W+Y)*P0,S1(HO(T))},dateUntil($,Z,O){if(O<=7){let Y=0,X=K5({...$,...p0},{...Z,...p0});return O===7&&([Y,X]=_1(X,7)),{...D0,weeks:Y,days:X}}let j=this.h($),T=this.h(Z),[z,J,W]=((Y,X,D,U,F,G,B)=>{let K=F-X,Q=G-D,f=B-U;if(K||Q){let L=Math.sign(K||Q),V=Y.j(F,G),x=0;if(Math.sign(f)===-L){let P=V;[F,G]=Y._(F,G,-L),K=F-X,Q=G-D,V=Y.j(F,G),x=L<0?-P:V}if(f=B-Math.min(U,V)+x,K){let[P,I]=Y.I(X,D),[M,A]=Y.I(F,G);if(Q=M-P||Number(A)-Number(I),Math.sign(Q)===-L){let E=L<0&&-Y.L(F);K=(F-=L)-X,Q=G-IO(P,I,Y.U(F))+(E||Y.L(F))}}}return[K,Q,f]})(this,...j,...T);return O===8&&(J+=this.J(z,j[0]),z=0),{...D0,years:z,months:J,days:W}},dateFromFields($,Z){let O=q(Z),j=Wj(this,$),T=Yj(this,$,j,O),z=Az(this,$,T,j,O);return $0(S1(this.P(j,T,z)),this.id||R)},yearMonthFromFields($,Z){let O=q(Z),j=Wj(this,$),T=Yj(this,$,j,O);return u1(Hj(this.P(j,T,1)),this.id||R)},monthDayFromFields($,Z){let O=q(Z),j=!this.id,{monthCode:T,year:z,month:J}=$,W,Y,X,D,U;if(T!==void 0){[W,Y]=L5(T),U=wz($,"day");let F=this.N(W,Y,U);if(!F)throw RangeError(Hz);if([X,D]=F,J!==void 0&&J!==D)throw RangeError(M2);j&&(D=g0("month",D,1,Y1,1),U=g0("day",U,1,bj(z!==void 0?z:X,D),O))}else{X=z===void 0&&j?P$:Wj(this,$),D=Yj(this,$,X,O),U=Az(this,$,D,X,O);let F=this.U(X);Y=D===F,W=Bj(D,F);let G=this.N(W,Y,U);if(!G)throw RangeError(Hz);[X,D]=G}return QO(S1(this.P(X,D,U)),this.id||R)},fields($){return Gj(this)&&$.includes("year")?[...$,...Cj]:$},mergeFields($,Z){let O=Object.assign(Object.create(null),$);return Xj(O,Z,i6),Gj(this)&&(Xj(O,Z,FY),this.id===x$&&Xj(O,Z,UY,Cj)),O},inLeapYear($){let[Z]=this.h($);return this.K(Z)},monthsInYear($){let[Z]=this.h($);return this.L(Z)},daysInMonth($){let[Z,O]=this.h($);return this.j(Z,O)},daysInYear($){let[Z]=this.h($);return this.X(Z)},dayOfYear:H6,era($){return this.ee($)[0]},eraYear($){return this.ee($)[1]},monthCode($){let[Z,O]=this.h($),[j,T]=this.I(Z,O);return((z,J)=>"M"+y0(z)+(J?"L":""))(j,T)},dayOfWeek:T8,daysInWeek(){return 7}},O9={dayOfYear:H6,h:Z8,q:H$},j9=Object.assign({},O9,{weekOfYear:V5,yearOfWeek:I5,R($){function Z(G){return(7-G<j?7:0)-G}function O(G){let B=j8(F+G),K=G||1,Q=Z(GZ(Y+B*K,7));return D=(B+(Q-X)*K)/7}let j=this.id?1:4,T=T8($),z=this.dayOfYear($),J=GZ(T-1,7),W=z-1,Y=GZ(J-W,7),X=Z(Y),D,U=Math.floor((W-X)/7)+1,F=$.isoYear;return U?U>O(0)&&(U=1,F++):(U=O(-1),F--),[U,F,D]}}),T9={dayOfYear:H6,h:Uj,q:fZ,weekOfYear:V5,yearOfWeek:I5,R(){return[]}},p$=gW(Object.assign({},vz,j9,{h:Z8,ee($){return this.id===z3?z8($):this.id===x$?NY($):[]},I:($,Z)=>[Z,0],N($,Z){if(!Z)return[P$,$]},K:vj,U(){},L:O8,J:($)=>$*Y1,j:bj,X:j8,P:($,Z,O)=>({isoYear:$,isoMonth:Z,isoDay:O}),q:H$,_:($,Z,O)=>($+=SO(O,Y1),(Z+=Mj(O,Y1))<1?($--,Z+=Y1):Z>Y1&&($++,Z-=Y1),[$,Z]),year($){return $.isoYear},month($){return $.isoMonth},day:($)=>$.isoDay}),Object.assign({},vz,T9,{h:Uj,ee($){let Z=this.O($);return[Z.era,Z.eraYear]},I($,Z){let O=YO.call(this,$);return[Bj(Z,O),O===Z]},N($,Z,O){let[j,T,z]=Uj.call(this,{isoYear:P$,isoMonth:Y1,isoDay:31}),J=YO.call(this,j),W=T===J;(M1($,Bj(T,J))||M1(Number(Z),Number(W))||M1(O,z))===1&&j--;for(let Y=0;Y<100;Y++){let X=j-Y,D=YO.call(this,X),U=IO($,Z,D);if(Z===(U===D)&&O<=xz.call(this,X,U))return[X,U]}},K($){let Z=XO.call(this,$);return Z>XO.call(this,$-1)&&Z>XO.call(this,$+1)},U:YO,L:DO,J($,Z){let O=Z+$,j=Math.sign($),T=j<0?-1:0,z=0;for(let J=Z;J!==O;J+=j)z+=DO.call(this,J+T);return z},j:xz,X:XO,P($,Z,O){return HO(fZ.call(this,$,Z,O))},q:fZ,_($,Z,O){if(O){if(Z+=O,!Number.isSafeInteger(Z))throw RangeError($3);if(O<0)for(;Z<1;)Z+=DO.call(this,--$);else{let j;for(;Z>(j=DO.call(this,$));)Z-=j,$++}}return[$,Z]},year($){return this.O($).year},month($){let{year:Z,F:O}=this.O($),{C:j}=this.B(Z);return j[O]+1},day($){return this.O($).day}})),N1="numeric",h$=["timeZoneName"],r2={month:N1,day:N1},zT={year:N1,month:N1},JT=Object.assign({},zT,{day:N1}),WT={hour:N1,minute:N1,second:N1},YT=Object.assign({},JT,WT),z9=Object.assign({},YT,{timeZoneName:"short"}),J9=Object.keys(zT),W9=Object.keys(r2),Y9=Object.keys(JT),X9=Object.keys(WT),XT=["dateStyle"],D9=J9.concat(XT),F9=W9.concat(XT),DT=Y9.concat(XT,["weekday"]),qZ=X9.concat(["dayPeriod","timeStyle"]),FT=DT.concat(qZ),U9=FT.concat(h$),B9=h$.concat(qZ),G9=h$.concat(DT),K9=h$.concat(["day","weekday"],qZ),Q9=h$.concat(["year","weekday"],qZ),C9={},UT=[O$(FT,YT),wO],t2=[O$(U9,z9),wO,0,($,Z)=>{let O=X0($.timeZone);if(Z&&X0(Z.timeZone)!==O)throw RangeError(N2);return O}],BT=[O$(FT,YT,h$),V0],GT=[O$(DT,JT,B9),V0],KT=[O$(qZ,WT,G9),($)=>x1($)/e0],QT=[O$(D9,zT,K9),V0,1],CT=[O$(F9,r2,Q9),V0,1],Rz;function O1($,Z,O,j,T){function z(...Y){if(!(this instanceof z))throw TypeError(c6);O7(this,Z(...Y))}function J(Y,X){return Object.defineProperties(function(...D){return Y.call(this,W(this),...D)},Vj(X))}function W(Y){let X=G0(Y);if(!X||X.branding!==$)throw TypeError(c6);return X}return Object.defineProperties(z.prototype,{...qz(h0(J,O)),...n1(h0(J,j)),...MO("Temporal."+$)}),Object.defineProperties(z,{...n1(T),...Vj($)}),[z,(Y)=>{let X=Object.create(z.prototype);return O7(X,Y),X},W]}function z7($){return $=$.concat("id").sort(),(Z)=>{if(!kz(Z,$))throw TypeError(S2);return Z}}function i$($){if(G0($)||$.calendar!==void 0||$.timeZone!==void 0)throw TypeError(V2);return $}function U3($,Z){let O={};for(let j in $)O[j]=({o:T},z)=>{let J=G0(z)||{},{branding:W}=J,Y=W===T$||Z.includes(W)?J:S0(z);return T[j](Y)};return O}function IT($){let Z={};for(let O in $)Z[O]=(j)=>{let{calendar:T}=j;return(z=T,typeof z=="string"?p$(z):(J=z,Object.assign(Object.create(R9),{i:J})))[O](j);var z,J};return Z}function g1(){throw TypeError(L2)}function gZ({calendar:$}){return typeof $=="string"?new HT($):$}function e2($,Z){if(Z=t(Z),W0($)){let j=G0($);if(j&&j.branding===m$)return q(Z),j;let T=Y7($);return v6(V3(T||R),!T,$,Z)}let O=i8(p$,$);return q(Z),O}function J7($,Z,O){return j=Z.call($,M0(Y0(O))),ej(SZ(j));var j}function B3($,Z=U7){let O=Object.keys(Z).sort(),j={};for(let T of O)j[T]=v(Z[T],$,y2($[T]));return j}function p($,Z){return typeof $=="string"?D3($):B3($,Z)}function O0($){return p($,VT)}function $1($){if(W0($)){let Z=G0($);if(Z)switch(Z.branding){case Y3:return Z;case Q1:return Y0(Z.epochNanoseconds)}}return p8($)}function $7($,Z,O){let j=Z.l($1(O).epochNanoseconds,$);return j?M0(Y0(j)):null}function c($){return W0($)?(G0($)||{}).timeZone||m9($):((Z)=>sO(a8(s(Z))))($)}function R1($,Z){if(W0($)){let O=G0($)||{};switch(O.branding){case W3:return q(Z),O;case z$:return q(Z),d0(O);case Q1:return q(Z),y6(O0,O)}return A5($,Z)}return q(Z),u8($)}function LT($){return $===void 0?void 0:R1($)}function c$($,Z){if(Z=t(Z),W0($)){let j=G0($);return j&&j.branding===y$?(q(Z),j):b6(C3(yZ($)),$,Z)}let O=d8(p$,$);return q(Z),O}function w1($,Z){if(Z=t(Z),W0($)){let j=G0($)||{};switch(j.branding){case z$:return q(Z),j;case T$:return q(Z),e({...j,...p0});case Q1:return q(Z),k6(O0,j)}return P5(f3(yZ($)),$,Z)}let O=l8($);return q(Z),O}function S0($,Z){if(Z=t(Z),W0($)){let j=G0($)||{};switch(j.branding){case T$:return q(Z),j;case z$:return q(Z),$0(j);case Q1:return q(Z),g6(O0,j)}return E6(f3(yZ($)),$,Z)}let O=iO($);return q(Z),O}function W7($,Z,O){return c0(Z.call($,a($0(O,$))))}function j1($){return(Z)=>typeof Z=="string"?p$(Z):((O,j)=>{let T=Object.keys(j).sort(),z={};for(let J of T)z[J]=v(j[J],O,O[J]);return z})(Z,$)}function n($){if(W0($)){let Z=G0($);return Z&&Z.branding===X3?Z:H5($)}return s8($)}function kZ($){if($!==void 0){if(W0($)){let Z=G0($)||{};switch(Z.branding){case Q1:case T$:return Z;case z$:return $0(Z)}let O=yZ($);return{..._5(c,p,f3(O),$),calendar:O}}return h8($)}}function yZ($){return Y7($)||R}function Y7($){let{calendar:Z}=$;if(Z!==void 0)return B0(Z)}function B0($){return W0($)?(G0($)||{}).calendar||$X($):((Z)=>xZ(n8(s(Z))))($)}function l$($,Z){if(Z=t(Z),W0($)){let O=G0($);if(O&&O.branding===Q1)return NZ(Z),O;let j=yZ($);return x5(c,p,f3(j),j,$,Z)}return c8($,Z)}function Z7($){return h0((Z)=>(O)=>Z(fT(O)),$)}function fT($){return I0($,O0)}function f9(){let $=v1.prototype,Z=Object.getOwnPropertyDescriptors($),O=Object.getOwnPropertyDescriptors(v1),j=function(T,z={}){if(!(this instanceof j))return new j(T,z);ET.set(this,((J,W={})=>{let Y=new v1(J,W),X=Y.resolvedOptions(),D=X.locale,U=E0(Object.keys(W),X),F=A0(L9),G=(...B)=>{let K,Q=B.map((f,L)=>{let V=G0(f),x=(V||{}).branding;if(L&&K&&K!==x)throw TypeError(x2);return K=x,V});return K?F(K)(D,U,...Q):[Y,...B]};return G.u=Y,G})(T,z))};for(let T in Z){let z=Z[T],J=T.startsWith("format")&&V9(T);typeof z.value=="function"?z.value=T==="constructor"?j:J||I9(T):J&&(z.get=function(){return J.bind(this)})}return O.prototype.value=Object.create($,Z),Object.defineProperties(j,O),j}function V9($){return function(...Z){let O=ET.get(this),[j,...T]=O(...Z);return j[$](...T)}}function I9($){return function(...Z){return ET.get(this).u[$](...Z)}}function L9($){let Z=M9[$];if(!Z)throw TypeError(_2($));return B1(Z,A0(m6))}var M9={Instant:UT,PlainDateTime:BT,PlainDate:GT,PlainTime:KT,PlainYearMonth:QT,PlainMonthDay:CT},S9=B1(UT),N9=B1(t2),_9=B1(BT),x9=B1(GT),P9=B1(KT),A9=B1(QT),H9=B1(CT),MT={era:lz,eraYear:Sj,year:SZ,month:c0,daysInMonth:c0,daysInYear:c0,inLeapYear:g2,monthsInYear:c0},K3={monthCode:s},ST={day:c0},X7={dayOfWeek:c0,dayOfYear:c0,weekOfYear:dz,yearOfWeek:Sj,daysInWeek:c0},D7=Object.assign({},MT,K3,ST,X7),G3=new WeakMap,G0=G3.get.bind(G3),O7=G3.set.bind(G3),E9={...U3(MT,[y$]),...U3(X7,[]),...U3(K3,[y$,m$]),...U3(ST,[m$])},NT=IT(D7),b9=IT({...MT,...K3}),v9=IT({...K3,...ST}),mZ={calendarId:($)=>X0($.calendar)},R9=h0(($,Z)=>function(O){let{i:j}=this;return $(j[Z](a($0(O,j))))},D7),w9=LZ(($)=>(Z)=>Z[$],k.concat("sign")),_T=LZ(($,Z)=>(O)=>O[u0[Z]],K1),F7={epochSeconds:U8,epochMilliseconds:wO,epochMicroseconds:B8,epochNanoseconds:G8},pZ=v(Ij,new Set(["branding"])),[q9,d$,k9]=O1(m$,v(l5,B0),{...mZ,...v9},{getISOFields:pZ,getCalendar:gZ,with($,Z,O){return d$(w5(r9,$,this,i$(Z),O))},equals:($,Z)=>X5($,e2(Z)),toPlainDate($,Z){return a(j2(hZ,$,this,Z))},toLocaleString($,Z,O){let[j,T]=H9(Z,O,$);return j.format(T)},toString:nj,toJSON:($)=>nj($),valueOf:g1},{from:($,Z)=>d$(e2($,Z))}),U7={getOffsetNanosecondsFor:J7,getPossibleInstantsFor($,Z,O){let j=[...Z.call($,U0(e(O,R)))].map((z)=>y9(z).epochNanoseconds),T=j.length;return T>1&&(j.sort(f0),$6(q0(w0(j[0],j[T-1])))),j}},VT={getOffsetNanosecondsFor:J7},[g9,M0,y9]=O1(Y3,y5,F7,{add:($,Z)=>M0(Z6(0,$,n(Z))),subtract:($,Z)=>M0(Z6(1,$,n(Z))),until:($,Z,O)=>h(M6(0,$,$1(Z),O)),since:($,Z,O)=>h(M6(1,$,$1(Z),O)),round:($,Z)=>M0(C8($,Z)),equals:($,Z)=>T5($,$1(Z)),toZonedDateTime($,Z){let O=F1(Z);return Z0(q6($,c(O.timeZone),B0(O.calendar)))},toZonedDateTimeISO:($,Z)=>Z0(q6($,c(Z))),toLocaleString($,Z,O){let[j,T]=S9(Z,O,$);return j.format(T)},toString:($,Z)=>lj(c,O0,$,Z),toJSON:($)=>lj(c,O0,$),valueOf:g1},{from:($)=>M0($1($)),fromEpochSeconds:($)=>M0(J2($)),fromEpochMilliseconds:($)=>M0(W2($)),fromEpochMicroseconds:($)=>M0(Y2($)),fromEpochNanoseconds:($)=>M0(X2($)),compare:($,Z)=>V6($1($),$1(Z))}),[Q3,_U]=O1("TimeZone",($)=>{let Z=O5($);return{branding:"TimeZone",id:Z,o:D3(Z)}},{id:($)=>$.id},{getPossibleInstantsFor:({o:$},Z)=>$.getPossibleInstantsFor(w1(Z)).map((O)=>M0(Y0(O))),getOffsetNanosecondsFor:({o:$},Z)=>$.getOffsetNanosecondsFor($1(Z).epochNanoseconds),getOffsetStringFor($,Z){let O=$1(Z).epochNanoseconds,j=B3(this,VT).getOffsetNanosecondsFor(O);return r1(j)},getPlainDateTimeFor($,Z,O=R){let j=$1(Z).epochNanoseconds,T=B3(this,VT).getOffsetNanosecondsFor(j);return U0(e(A1(j,T),B0(O)))},getInstantFor($,Z,O){let j=w1(Z),T=Rj(O),z=B3(this);return M0(Y0(H0(z,j,T)))},getNextTransition:({o:$},Z)=>$7(1,$,Z),getPreviousTransition:({o:$},Z)=>$7(-1,$,Z),equals($,Z){return!!aO(this,c(Z))},toString:($)=>$.id,toJSON:($)=>$.id},{from($){let Z=c($);return typeof Z=="string"?new Q3(Z):Z}}),m9=z7(Object.keys(U7)),[p9,q1]=O1(W3,d5,_T,{getISOFields:pZ,with($,Z,O){return q1(q5(this,i$(Z),O))},add:($,Z)=>q1(J6(0,$,n(Z))),subtract:($,Z)=>q1(J6(1,$,n(Z))),until:($,Z,O)=>h(P6(0,$,R1(Z),O)),since:($,Z,O)=>h(P6(1,$,R1(Z),O)),round:($,Z)=>q1(I8($,Z)),equals:($,Z)=>D5($,R1(Z)),toZonedDateTime:($,Z)=>Z0(T2(c,S0,p,$,Z)),toPlainDateTime:($,Z)=>U0(z2($,S0(Z))),toLocaleString($,Z,O){let[j,T]=P9(Z,O,$);return j.format(T)},toString:aj,toJSON:($)=>aj($),valueOf:g1},{from:($,Z)=>q1(R1($,Z)),compare:($,Z)=>nO(R1($),R1(Z))}),[h9,k1,c9]=O1(y$,v(c5,B0),{...mZ,...b9},{getISOFields:pZ,getCalendar:gZ,with($,Z,O){return k1(R5(o9,$,this,i$(Z),O))},add:($,Z,O)=>k1(z6(j7,0,$,n(Z),O)),subtract:($,Z,O)=>k1(z6(j7,1,$,n(Z),O)),until:($,Z,O)=>h(x6(T7,0,$,c$(Z),O)),since:($,Z,O)=>h(x6(T7,1,$,c$(Z),O)),equals:($,Z)=>Y5($,c$(Z)),toPlainDate($,Z){return a(O2(hZ,$,this,Z))},toLocaleString($,Z,O){let[j,T]=A9(Z,O,$);return j.format(T)},toString:sj,toJSON:($)=>sj($),valueOf:g1},{from:($,Z)=>k1(c$($,Z)),compare:($,Z)=>$$(c$($),c$(Z))}),[l9,U0]=O1(z$,v(p5,B0),{...mZ,...NT,..._T},{getISOFields:pZ,getCalendar:gZ,with($,Z,O){return U0(b5(hZ,$,this,i$(Z),O))},withCalendar:($,Z)=>U0(eO($,B0(Z))),withPlainDate:($,Z)=>U0(B2($,S0(Z))),withPlainTime:($,Z)=>U0(U2($,LT(Z))),add:($,Z,O)=>U0(j6(W$,0,$,n(Z),O)),subtract:($,Z,O)=>U0(j6(W$,1,$,n(Z),O)),until:($,Z,O)=>h(N6(Z1,0,$,w1(Z),O)),since:($,Z,O)=>h(N6(Z1,1,$,w1(Z),O)),round:($,Z)=>U0(V8($,Z)),equals:($,Z)=>J5($,w1(Z)),toZonedDateTime:($,Z,O)=>Z0(a5(p,$,c(Z),O)),toPlainDate:($)=>a($0($)),toPlainTime:($)=>q1(d0($)),toPlainYearMonth($){return k1(o5(C3,$,this))},toPlainMonthDay($){return d$(r5(V3,$,this))},toLocaleString($,Z,O){let[j,T]=_9(Z,O,$);return j.format(T)},toString:ij,toJSON:($)=>ij($),valueOf:g1},{from:($,Z)=>U0(w1($,Z)),compare:($,Z)=>L6(w1($),w1(Z))}),[d9,a,B7]=O1(T$,v(h5,B0),{...mZ,...NT},{getISOFields:pZ,getCalendar:gZ,with($,Z,O){return a(v5(hZ,$,this,i$(Z),O))},withCalendar:($,Z)=>a(eO($,B0(Z))),add:($,Z,O)=>a(T6(W$,0,$,n(Z),O)),subtract:($,Z,O)=>a(T6(W$,1,$,n(Z),O)),until:($,Z,O)=>h(_6(Z1,0,$,S0(Z),O)),since:($,Z,O)=>h(_6(Z1,1,$,S0(Z),O)),equals:($,Z)=>W5($,S0(Z)),toZonedDateTime($,Z){let O=!W0(Z)||Z instanceof Q3?{timeZone:Z}:Z;return Z0(t5(c,R1,p,$,O))},toPlainDateTime:($,Z)=>U0(e5($,LT(Z))),toPlainYearMonth($){return k1($2(C3,$,this))},toPlainMonthDay($){return d$(Z2(V3,$,this))},toLocaleString($,Z,O){let[j,T]=x9(Z,O,$);return j.format(T)},toString:uj,toJSON:($)=>uj($),valueOf:g1},{from:($,Z)=>a(S0($,Z)),compare:($,Z)=>$$(S0($),S0(Z))}),xT={fields($,Z,O){return[...Z.call($,O)]}},G7=Object.assign({dateFromFields($,Z,O,j){return B7(Z.call($,Object.assign(Object.create(null),O),j))}},xT),K7=Object.assign({yearMonthFromFields($,Z,O,j){return c9(Z.call($,Object.assign(Object.create(null),O),j))}},xT),Q7=Object.assign({monthDayFromFields($,Z,O,j){return k9(Z.call($,Object.assign(Object.create(null),O),j))}},xT),PT={mergeFields($,Z,O,j){return F1(Z.call($,Object.assign(Object.create(null),O),Object.assign(Object.create(null),j)))}},i9=Object.assign({},G7,PT),u9=Object.assign({},K7,PT),s9=Object.assign({},Q7,PT),AT={dateAdd($,Z,O,j,T){return B7(Z.call($,a($0(O,$)),h(l(j)),T))}},C7=Object.assign({},AT,{dateUntil($,Z,O,j,T,z){return e9(Z.call($,a($0(O,$)),a($0(j,$)),Object.assign(Object.create(null),z,{largestUnit:bZ[T]})))}}),n9=Object.assign({},AT,{day:W7}),a9=Object.assign({},C7,{day:W7}),C3=j1(K7),f3=j1(G7),V3=j1(Q7),o9=j1(u9),hZ=j1(i9),r9=j1(s9),W$=j1(AT),Z1=j1(C7),j7=j1(n9),T7=j1(a9),[t9,h,e9]=O1(X3,i5,{...w9,blank:g8},{with:($,Z)=>h(k5($,Z)),negated:($)=>h(lO($)),abs:($)=>h(k8($)),add:($,Z,O)=>h(F6(kZ,Z1,p,0,$,n(Z),O)),subtract:($,Z,O)=>h(F6(kZ,Z1,p,1,$,n(Z),O)),round:($,Z)=>h(q8(kZ,Z1,p,$,Z)),total:($,Z)=>Q8(kZ,Z1,p,$,Z),toLocaleString($,Z,O){return Intl.DurationFormat?new Intl.DurationFormat(Z,O).format(this):yO($)},toString:yO,toJSON:($)=>yO($),valueOf:g1},{from:($)=>h(n($)),compare:($,Z,O)=>j5(kZ,W$,p,n($),n(Z),O)}),f7={toString:($)=>$.id,toJSON:($)=>$.id,...E9,dateAdd:({id:$,o:Z},O,j,T)=>a($0(Z.dateAdd(S0(O),n(j),T),$)),dateUntil:({o:$},Z,O,j)=>h(l($.dateUntil(S0(Z),S0(O),W8(j)))),dateFromFields:({id:$,o:Z},O,j)=>a(E6(Z,O,j,cz($))),yearMonthFromFields:({id:$,o:Z},O,j)=>k1(b6(Z,O,j,pz($))),monthDayFromFields:({id:$,o:Z},O,j)=>d$(v6(Z,0,O,j,hz($))),fields({o:$},Z){let O=new Set(i0),j=[];for(let T of Z){if(s(T),!O.has(T))throw RangeError(h6(T));O.delete(T),j.push(T)}return $.fields(j)},mergeFields:({o:$},Z,O)=>$.mergeFields(Lj(Nj(Z)),Lj(Nj(O)))},[HT]=O1("Calendar",($)=>{let Z=f5($);return{branding:"Calendar",id:Z,o:p$(Z)}},{id:($)=>$.id},f7,{from($){let Z=B0($);return typeof Z=="string"?new HT(Z):Z}}),$X=z7(Object.keys(f7).slice(4)),[ZX,Z0]=O1(Q1,v(m5,B0,c),{...F7,...mZ,...Z7(NT),...Z7(_T),offset:($)=>r1(fT($).offsetNanoseconds),offsetNanoseconds:($)=>fT($).offsetNanoseconds,timeZoneId:($)=>X0($.timeZone),hoursInDay:($)=>L8(p,$)},{getISOFields:($)=>R8(O0,$),getCalendar:gZ,getTimeZone:({timeZone:$})=>typeof $=="string"?new Q3($):$,with($,Z,O){return Z0(E5(hZ,p,$,this,i$(Z),O))},withCalendar:($,Z)=>Z0(eO($,B0(Z))),withTimeZone:($,Z)=>Z0(G2($,c(Z))),withPlainDate:($,Z)=>Z0(F2(p,$,S0(Z))),withPlainTime:($,Z)=>Z0(D2(p,$,LT(Z))),add:($,Z,O)=>Z0(O6(W$,p,0,$,n(Z),O)),subtract:($,Z,O)=>Z0(O6(W$,p,1,$,n(Z),O)),until:($,Z,O)=>h(l(S6(Z1,p,0,$,l$(Z),O))),since:($,Z,O)=>h(l(S6(Z1,p,1,$,l$(Z),O))),round:($,Z)=>Z0(f8(p,$,Z)),startOfDay:($)=>Z0(M8(p,$)),equals:($,Z)=>z5($,l$(Z)),toInstant:($)=>M0(u5($)),toPlainDateTime:($)=>U0(k6(O0,$)),toPlainDate:($)=>a(g6(O0,$)),toPlainTime:($)=>q1(y6(O0,$)),toPlainYearMonth($){return k1(s5(C3,$,this))},toPlainMonthDay($){return d$(n5(V3,$,this))},toLocaleString($,Z,O={}){let[j,T]=N9(Z,O,$);return j.format(T)},toString:($,Z)=>dj(O0,$,Z),toJSON:($)=>dj(O0,$),valueOf:g1},{from:($,Z)=>Z0(l$($,Z)),compare:($,Z)=>I6(l$($),l$(Z))}),OX=Object.defineProperties({},{...MO("Temporal.Now"),...n1({timeZoneId:()=>G1(),instant:()=>M0(Y0(AZ())),zonedDateTime:($,Z=G1())=>Z0(F0(AZ(),c(Z),B0($))),zonedDateTimeISO:($=G1())=>Z0(F0(AZ(),c($),R)),plainDateTime:($,Z=G1())=>U0(e(k$(O0(c(Z))),B0($))),plainDateTimeISO:($=G1())=>U0(e(k$(O0(c($))),R)),plainDate:($,Z=G1())=>a($0(k$(O0(c(Z))),B0($))),plainDateISO:($=G1())=>a($0(k$(O0(c($))),R)),plainTimeISO:($=G1())=>q1(d0(k$(O0(c($)))))})}),u$=Object.defineProperties({},{...MO("Temporal"),...n1({PlainYearMonth:h9,PlainMonthDay:q9,PlainDate:d9,PlainTime:p9,PlainDateTime:l9,ZonedDateTime:ZX,Instant:g9,Calendar:HT,TimeZone:Q3,Duration:t9,Now:OX})}),jX=f9(),ET=new WeakMap,TX=Object.defineProperties(Object.create(Intl),n1({DateTimeFormat:jX}));var bT=new WeakMap;function JX($){let Z=bT.get($);if(!Z)Z=$(zX(32).toString("hex")),bT.set($,Z),Z.catch(()=>bT.delete($));return Z}async function vT($,Z,O){if(typeof O==="string"&&O!=="")return await $.verifyPassword(Z,O);try{await $.verifyPassword(Z,await JX($.hashPassword))}catch{}return!1}async function Y$($,Z){let O=Z.user??Z.session?.user;if(!O||!$.onAuthenticated)return;let{password:j,...T}=O;await $.onAuthenticated({...Z,user:T})}class qT extends Error{}function RT($){return typeof $==="string"&&$!==""?$:null}function V7($){return XZ($)}var WX=256;function I7($){return typeof $==="string"&&$!==""&&$.length<=WX?$:null}var wT="intended_url";class kT extends _{schema={email:{required:"Email is required",string:"Invalid email",email:"Invalid email"},password:{required:"Password is required"}}}class L7 extends _{schema={email:{required:"Email is required",email:"Invalid email"}}}class M7 extends _{schema={password:{required:"Password is required",password:"Invalid password"}}}class d extends s3{async me(){let $=await X$.user();if(!$)throw new n3;return $}async verifyEmail($=new _){let Z=await $.input(),{userProvider:O}=C(H),j=RT(Z.get("token"));if(!j)return{email:null};let T=await O.findUserByVerificationToken(j);if(!T)return{email:null};return await O.verifyUser(T.email),{email:T.email}}async signInWithMagicLink($=new _){let Z=C(H),{userProvider:O}=Z,j=RT($.search.get("token")),T=null;try{T=XZ(decodeURIComponent($.search.get("email")??""))}catch{}if(await L$("link",null,$,{perIp:Z.config.emailCode.verifyLimit.perIp}),!T||!j||!await Z.verifyMagicLinkToken(T,j))return{error:"Invalid token"};await O.verifyUser(T);let z=await Z.createOrUpdateSession({email:T});return $.ctx().setCookie("access_token",z.token,C(H).accessTokenCookieOptions($,z.expiresAt)),await Z.config.onSignIn(z,$.search.toJSON()),await Y$(Z.config,{session:z,isNewUser:!1,method:"magic-link",req:$}),{session:z}}async verifyPinRequest($){let Z=C(H),O=await $.input(),{email:j,pin:T}=O.toJSON(),z=XZ(j),J=I7(T);if(await L$("verify",z,$,Z.config.emailCode.verifyLimit),!z||!J)throw new y({pin:["Invalid pin"]});let W=await Z.verifyOneTimeCode(z,J);if(W.status==="too_many_attempts")throw new y({pin:["Too many attempts"]});if(W.status!=="ok")throw new y({pin:["Invalid pin"]});return await Z.userProvider.verifyUser(z),z}async signInWithPinV2($=new _){let Z=C(H),O=await this.verifyPinRequest($),j=await Z.createOrUpdateSessionV2({email:O});return $.ctx().setCookie("access_token",j.token,C(H).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await Y$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),j}async signInWithPin($=new _){let Z=C(H),O=await this.verifyPinRequest($),j=await Z.createOrUpdateSession({email:O});return $.ctx().setCookie("access_token",j.token,C(H).accessTokenCookieOptions($,j.expiresAt)),await Z.config.onSignIn(j,$.search.toJSON()),await Y$(Z.config,{session:j,isNewUser:!1,method:"magic-link",req:$}),{session:j}}async signInV2($=new kT){let Z=await $.input(),{email:O,password:j}=Z.toJSON(),T=O.toLowerCase().trim(),z=C(H),J=await z.userProvider.findUserByEmailAddress(T,z.config.verifyEmail),W=typeof j==="string"&&await vT(z.config,j,J?.password);if(!J||!W)throw new y({invalid_credentials:["Invalid credentials"]});let Y=await z.createOrUpdateSessionV2({email:J.email,id:J.id});$.ctx().setCookie("access_token",Y.token,C(H).accessTokenCookieOptions($,Y.expiresAt)),await z.config.onSignIn(J,$.search.toJSON()),await Y$(z.config,{session:Y,user:J,isNewUser:!1,method:"password",req:$});let{password:X,...D}=J;return D}async signIn($=new kT){let Z=await $.input(),{email:O,password:j}=Z.toJSON(),T=O.toLowerCase().trim(),z=C(H),J=await z.userProvider.findUserByEmailAddress(T,z.config.verifyEmail),W=typeof j==="string"&&await vT(z.config,j,J?.password);if(!J||!W)throw new y({invalid_credentials:["Invalid credentials"]});let Y=await z.createOrUpdateSession({email:J.email,id:J.id});$.ctx().setCookie("access_token",Y.token,C(H).accessTokenCookieOptions($,Y.expiresAt)),await z.config.onSignIn(J,$.search.toJSON()),await Y$(z.config,{session:Y,user:J,isNewUser:!1,method:"password",req:$});let{password:X,...D}=J;return D}async signUp(){let $=C(H),{userProvider:Z,config:O}=$,j=new O.signUpRequest,T=await j.input(),{email:z,password:J,name:W,invitationId:Y}=T.toJSON(),X=V7(z);if(!X)throw new y({email:["Invalid email"]});if(J!=null&&typeof J!=="string")throw new y({password:["Invalid password"]});if(Y!=null&&typeof Y!=="string")throw new y({invitationId:["Invalid invitation"]});if(await Z.findUserByEmailAddress(X,!1))throw new y({email:["Email address already exists"]});let U=await O.hashPassword(J),F=C(u).detectLocale(j),G;if(Y)G=await Z.findInvitation(Y,X);let B,K="";if(G)B=await Z.transaction(async()=>{await Z.deleteInvitationById(Y);let Q=await Z.createUser({email:X,name:W,password:U,emailVerifiedAt:new Date,locale:F});return await Z.createAccount({organizationId:G.organizationId,userId:Q.id,organizationRole:G.role}),await O.onUserCreated(Q),Q});else K=await O.generateEmailVerificationToken(X),B=await Z.transaction(async()=>{let Q=await Z.createUser({email:X,name:W,password:U,verificationToken:K,locale:F});return await O.onUserCreated(Q),Q});return await O.onSignUp(B,K,j.search.toJSON()),B}async signOut($=new _){let Z=i3($),O=C(H),{config:j}=O,T=await O.revokeSession(Z,$.headers.get("User-Agent"));if($.ctx().setCookie("access_token","",C(H).accessTokenCookieOptions($,new Date(0))),C(H).cookieDomain($))$.ctx().setCookie("access_token","",{...C(H).accessTokenCookieOptions($,new Date(0)),domain:void 0});if(T?.user)T.user.extension=await j.extendSession(T.user),await j.onSignOut(T.user);return{}}async forgotPassword($=new L7){let Z=await $.input(),O=V7(Z.get("email"));if(!O)return{};let{userProvider:j,config:T}=C(H),z=await j.findUserByEmailAddress(O,T.verifyEmail);if(!z)return{};let J=await T.generateForgotPasswordToken(z);return await j.createPasswordResetToken({user:z,token:J}),await T.onForgotPassword(z,J),{}}async resetPassword($=new M7){let{userProvider:Z,config:O}=C(H),j=await $.input(),{password:T,token:z}=j.toJSON(),J=RT(z),W=J?await Z.findPasswordResetToken({token:J}):null;if(!W)throw new y({token:["Invalid token"]});if(u$.Instant.from(W.createdAt.toISOString()).add({hours:24}).until(u$.Now.instant()).sign>=0)throw new y({token:["Token expired"]});await Z.deletePasswordResetToken({token:J});let X=await Z.findUserByEmailAddress(W.user.email,O.verifyEmail);if(!X)throw new y({email:["User not found"]});let D=await O.hashPassword(T);return await Z.updateUserPassword({id:X.id,password:D}),await Z.deleteAllUserSessions(X.id),await O.onResetPassword(X),{}}async changePassword($=new _){let{userProvider:Z,config:O}=C(H),j=await X$.user(),T=await $.input(),{oldPassword:z,newPassword:J}=T.toJSON();if(typeof J!=="string")throw new y({newPassword:["Invalid password"]});let W=await Z.findUserByEmailAddress(j.email,O.verifyEmail);if(!(typeof z==="string"&&await vT(O,z,W?.password)))throw new y({oldPassword:["Incorrect password"]});let X=await O.hashPassword(J);return await Z.updateUserPassword({id:j.id,password:X}),await Z.deleteAllUserSessions(j.id),{}}async oauthRedirect($=new _){let{provider:Z}=$.params,O=C(H).config.oauthProviders[Z];if(!O)throw Error(`Invalid provider: ${Z}`);let j=JZ($.search.get(V$),"");if(j)$.ctx().setCookie(wT,encodeURIComponent(j),{httpOnly:!0,sameSite:"Lax",secure:d4($.rawRequest),maxAge:600});return{destination:await O.getRedirectUrl($)}}async oauthCallback($=new _){let{provider:Z}=$.params,O=C(H),{userProvider:j,config:T}=O,z=T.oauthProviders[Z],{email:J,name:W,username:Y,providerId:X}=await z.onCallback($),D=X?await j.findUserBySocialAccount(Z,X):null,U="signin";if(!D){if(!J)return console.error("Authentication error: No email returned from OAuth provider callback"),{session:null};let K=C(u).detectLocale($);try{let Q=await this.linkOAuthAccount({provider:Z,providerId:X,email:J,name:W,username:Y,locale:K});if(Q)D=Q.user,U=Q.action}catch(Q){let f=X?await j.findUserBySocialAccount(Z,X):null;if(!f)throw Q;D=f}if(!D)return{session:null}}let F=await O.createOrUpdateSessionV2({email:D.email,id:D.id});if($.ctx().setCookie("access_token",F.token,C(H).accessTokenCookieOptions($,F.expiresAt)),U==="signup")await T.onSignUp(D,"",$.search.toJSON());else await T.onSignIn(D,$.search.toJSON());await Y$(O.config,{session:F,user:D,isNewUser:U==="signup",method:"oauth",req:$});let G=$.cookies.get(wT),B=T.redirectPath;if(G){try{B=JZ(decodeURIComponent(G),B)}catch{}$.ctx().setCookie(wT,"",{maxAge:-1})}return{session:F,redirectTo:B}}async linkOAuthAccount($){let{provider:Z,providerId:O,email:j,name:T,username:z,locale:J}=$,{userProvider:W,config:Y}=C(H),X=(F)=>({provider:Z,userId:F,email:j,username:z,providerId:O,expiresAt:new Date,accessToken:"",refreshToken:""}),D=await W.findUserByEmailAddress(j,!1);if(D){if(!O)return{user:D,action:"signin"};let F=await W.findSocialAccounts(D.id,Z);if(F.some((B)=>B.providerId===O))return{user:D,action:"signin"};if(F.some((B)=>B.providerId))return console.error(`Authentication error: user ${D.id} is already linked to a different ${Z} account`),null;let G=F[0];if(G){if(!await W.claimSocialAccount(G,O))throw Error(`${Z} account link changed concurrently`)}else await W.createSocialAccount(X(D.id));return{user:D,action:"signin"}}return{user:await W.transaction(async()=>{let F=await W.createUser({email:j,name:T,locale:J,emailVerifiedAt:new Date});if(O)await W.createSocialAccount(X(F.id));return await Y.onUserCreated(F),F}),action:"signup"}}async createMagicLinkToken($=new _){let Z=await $.input(),O=XZ(Z.get("email")),j=C(H),{uniformMagicLinkResponse:T,requestLimit:z}=j.config.emailCode;if(await L$("request",O,$,z),!O)return{email:null};let{user:J,pin:W,token:Y}=await j.createMagicLinkToken(O);if(J)return await j.config.onMagicLinkCreated(J,{email:O,pin:W,token:Y}),{email:O};return{email:T?O:null}}async requestEmailCode($=new _){let Z=C(H),O=Z.config.emailCode;if(!O.enabled)throw new a0("Not found",{status:404});let j=await $.input(),T=Zj(j.get("email"));if(await L$("request",T,$,O.requestLimit),!T)throw new y({email:["Invalid email"]});let z=await Z.userProvider.findUserByEmailAddress(T,!1);if(z||O.createUser){let{pin:J,token:W}=await Z.issueOneTimeCode(T,O.length);await O.send({email:T,code:J,token:W,isNewUser:!z,req:$})}return{ok:!0}}async verifyEmailCode($=new _){let Z=C(H),{userProvider:O,config:j}=Z;if(!j.emailCode.enabled)throw new a0("Not found",{status:404});let T=await $.input(),{email:z,code:J,name:W}=T.toJSON(),Y=Zj(z),X=I7(J);if(await L$("verify",Y,$,j.emailCode.verifyLimit),!Y||!X)throw new y({code:["invalid_code"]});let D=await Z.verifyOneTimeCode(Y,X,{claim:!1});if(D.status==="too_many_attempts")throw new y({code:["too_many_attempts"]});if(D.status!=="ok")throw new y({code:["invalid_code"]});let U=D.row,F=await O.findUserByEmailAddress(Y,!1),G=!1;if(F){if(!await O.claimMagicLinkToken(U.id))throw new y({code:["invalid_code"]});await O.verifyUser(Y)}else if(j.emailCode.createUser){let K=C(u).detectLocale($);try{F=await O.transaction(async()=>{if(!await O.claimMagicLinkToken(U.id))throw new qT;let Q=await O.createUser({email:Y,name:typeof W==="string"?W.trim():"",emailVerifiedAt:new Date,locale:K});return await j.onUserCreated(Q),Q}),G=!0}catch(Q){if(Q instanceof qT)throw new y({code:["invalid_code"]});throw Q}}else throw await O.claimMagicLinkToken(U.id),new y({code:["invalid_code"]});let B=await Z.createOrUpdateSessionV2({email:Y,id:F.id});return $.ctx().setCookie("access_token",B.token,C(H).accessTokenCookieOptions($,B.expiresAt)),await j.onSignIn(B,$.search.toJSON()),await Y$(Z.config,{session:B,isNewUser:G,method:"email-code",req:$}),{session:B,isNewUser:G}}}class S7 extends V1{middlewares=["cache:private"];routes={"/:provider":this.view("_Redirect",[d,"oauthRedirect"]),"/:provider/callback":this.view("auth/OauthCallback",[d,"oauthCallback"])}}class gT extends V1{middlewares=["cache:private"];routes={"/sign-in/magic-link":this.view("auth/MagicLinkSignIn",[d,"signInWithMagicLink"]),"/oauth":S7}}class yT extends N0{middlewares=["cache:private"];routes={"/sign-in":this.post(d,"signIn"),"/sign-in-v2":this.post(d,"signInV2"),"/sign-up":this.post(d,"signUp"),"/sign-out":this.post(d,"signOut"),"/forgot-password":this.post(d,"forgotPassword"),"/reset-password":this.post(d,"resetPassword"),"/change-password":this.post(d,"changePassword"),"/verify-email":this.post(d,"verifyEmail"),"/me":this.get(d,"me").middleware(["auth"]),"/magic-link":this.post(d,"createMagicLinkToken"),"/sign-in-with-pin":this.post(d,"signInWithPin"),"/sign-in-with-pin-v2":this.post(d,"signInWithPinV2"),"/email-code":this.post(d,"requestEmailCode"),"/email-code/verify":this.post(d,"verifyEmailCode")}}class mT extends N0{middlewares=["cache:private,0,no-store"];routes={"/set-locale/:locale":this.get(async()=>{let Z=new _().params.locale;return await C(u).onLocaleChange(Z),{locale:Z}}),"/translations/:locale/:scope*":this.get(async()=>{let $=new _,Z=`/${$.params.scope??""}`,O=$.params.locale,j=C(u),T=O??j.detectLocale($),z=j.getPageTranslations(T,Z);return $.ctx().setCookie("i18n-locale",T,{expires:new Date(Date.now()+31536000000)}),{[T]:z}})}}class pT{}class hT extends pT{async resize($,Z){let{height:O,width:j,quality:T,fit:z}=Z;return await(await I3("The Sharp image optimization driver"))($).resize(j>0?j:void 0,O>0?O:void 0,{fit:z}).webp({quality:T>0?T:80,force:!0}).toBuffer()}}function TB($){return $}function N7(){return{driver:new hT}}class cT extends N0{routes={"/resize":this.file(async()=>{let $=new _,Z=new URL($.rawRequest.url),O=Z.searchParams.get("url"),j=Number(Z.searchParams.get("w")),T=Number(Z.searchParams.get("h")),z=Z.searchParams.get("fit")??"cover",J=Number(Z.searchParams.get("q"));if(!O)return new Response(JSON.stringify({error:"url query parameter is required"}),{headers:{"Content-Type":"application/json"},status:404});let Y=`${O.startsWith("http")?"":`http://localhost:${process.env.PORT||5173}`}${O}`,X=await fetch(Y);if(!X.ok)return new Response(JSON.stringify({error:"Image not found",info:Y}),{headers:{"Content-Type":"application/json"},status:404});let D=Buffer.from(await X.arrayBuffer()),U=await C(_7).resize(D,{height:T,width:j,fit:z,quality:J});X.headers.delete("Content-Type"),X.headers.delete("Content-Length");let F=new Headers(X.headers);return F.set("Content-Type","image/webp"),F.set("Content-Length",`${U.byteLength}`),new Response(new Uint8Array(U),{headers:F})})}}class _7{static token="image";driver;constructor($={}){this.driver=$.driver??N7().driver}resize($,Z){return this.driver.resize($,Z)}}class lT extends N0{middlewares=["cache:private,0"];routes={"/live":this.get(async()=>{let $=Bun.file(C(x7).currentLogFilePath);return new Response(await $.text(),{headers:{"Content-Type":"text/plain"}})})}}function YX($){let Z=new Map;for(let O of $)if(typeof O==="string"){let[j,T=""]=O.split(":");if(j.startsWith("-")){if(Z.has(j.replace("-","")))Z.delete(j.replace("-",""))}else Z.set(j,T.split(",").filter(Boolean))}else Z.set(O,[]);return Z}class cZ{config;static token="middleware";constructor($){this.config=$}get aliases(){return this.config.aliases}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 _;return Array.from(YX($).entries()).map(([O,j])=>{if(typeof O==="string"){let T=this.aliases[O];if(T){let z=new T(Z);return()=>z.run.call(z,...j)}}else{if(tZ(O)){let T=new O(Z);return T.run.bind(T)}return O}}).filter(Boolean).reduce((O,j)=>{return async()=>{return{...await O(),...await j()}}},()=>Promise.resolve({}))()}}function fB($){return $}function P7(){return{onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{}}}function A7(){return{partialRendering:!0,onRequestStart:()=>{},onRequestEnd:()=>{},onRequestFail:()=>{},onStreamComplete:()=>{}}}function XX($){return"run"in $}function DX($){return Object.hasOwn($,"get")||Object.hasOwn($,"post")||Object.hasOwn($,"put")||Object.hasOwn($,"patch")||Object.hasOwn($,"delete")}function FX($){return Object.hasOwn($,"first")&&Object.hasOwn($,"second")}function UX($){if("__brand"in $)return $.__brand==="ApiRouter";return!1}function BX($){if("__internal_brand"in $)return $.__internal_brand==="ProxyHandler";return!1}function H7($){if("__internal_brand"in $)return $.__internal_brand==="StreamHandler";return!1}function dT($,Z="",O=[]){let j={};function T(z,J,W,Y,X){let D=z==="/"?"":z,U=Z==="/"?"":Z,F=(`${U}${D}`===""?"/":`${U}${D}`).replaceAll("//","/");if(!j[F])j[F]={};j[F][J.toUpperCase()]={exec:W,middleware:[...O,...Y],...X?{source:X}:{}},j[F].OPTIONS={exec:()=>{let B=new _().ctx().headers;return new Response(null,{headers:B,status:204})},middleware:[]}}for(let[z,J]of Object.entries($)){if(BX(J)){let W=J;for(let Y of["GET","POST","PUT","DELETE"])T(z,Y,W.run.bind(W),W.middlewares);continue}if(XX(J)){let W=J,Y=W.method,X=W.middlewares,D=W.run.bind(W);if(T(z,Y,D,X,W.source),H7(J))T(z,"HEAD",D,X,W.source)}if(DX(J))for(let[W,Y]of Object.entries(J)){let X=Y,D=X.middlewares,U=X.run.bind(X);if(T(z,W,U,D,X.source),W==="get"&&H7(X))T(z,"HEAD",U,D,X.source)}if(UX(J)){let W=new J,Y=dT(W.routes,`${Z}${z}`,W.middlewares);for(let[X,D]of Object.entries(Y))j[X.replaceAll("//","/")]=D}if(FX(J)){let{first:W,second:Y}=J;for(let[X,D]of Object.entries(W)){let U=D.middlewares,F=D.run.bind(D),[G,...B]=z.split("/").reverse();if(!G.startsWith(":"))throw Error("Resource route must end with a dynamic segment");T(B.reverse().join("/"),X,F,U,D.source)}for(let[X,D]of Object.entries(Y)){let U=D.middlewares,F=D.run.bind(D);T(z,X,F,U,D.source)}}}return Object.fromEntries(Object.entries(j).sort(([z],[J])=>{let W=z.split("/").length+z.split(":").length,Y=J.split("/").length+J.split(":").length;return W-Y}))}function L3($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function iT($,Z){if($==="/")return Z;if(Z==="/")return $;return`${$}${Z}`}function uT($){let Z=L3($);return Z.length>1?Z.replace(/\/$/,""):Z}function E7($,Z){return Z.map((O)=>({...O,path:uT(iT($,O.path))}))}function M3($){let Z={};for(let[O,j]of Object.entries($))if("run"in j){let T=j;if("children"in T){let z=new T.children,J=M3(z.routes);for(let[W,{exec:Y,middleware:X,segments:D,features:U}]of Object.entries(J)){let F=iT(O,W),G=(B)=>T.run.call(T,B,O);Z[L3(F)]={exec:[G,...Y],middleware:[...T.middlewares,...X],features:[...T.featureGates,...U],viewPath:T.viewPath,segments:[{path:uT(O),viewPath:T.viewPath,...T.alwaysRuns?{alwaysRun:!0}:{}},...E7(O,D)]}}}else{let z=(J)=>T.run.call(T,J,O);Z[L3(O)]={exec:[z],middleware:T.middlewares,features:T.featureGates,viewPath:T.viewPath,segments:[{path:uT(O),viewPath:T.viewPath}]}}}else{let T=new j,z=M3(T.routes);for(let[J,{exec:W,middleware:Y,viewPath:X,segments:D,features:U}]of Object.entries(z)){let F=iT(O,J);Z[L3(F)]={exec:W,middleware:[...T.middlewares,...Y],features:[...T.featureGates,...U],viewPath:X,segments:E7(O,D)}}}return Object.fromEntries(Object.entries(Z).sort(([O],[j])=>{let T=O.split("/").length+O.split(":").length,z=j.split("/").length+j.split(":").length;return T-z}))}var GX=Object.defineProperty,S=($,Z)=>GX($,"name",{value:Z,configurable:!0}),a$=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor($,Z,O,j,T,z){this.type=$,this.name=Z,this.prefix=O,this.value=j,this.suffix=T,this.modifier=z}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};S(a$,"Part");var KX=/[$_\p{ID_Start}]/u,QX=/[$_\u200C\u200D\p{ID_Continue}]/u,nT=".*";function b7($,Z){return(Z?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test($)}S(b7,"isASCII");function rT($,Z=!1){let O=[],j=0;for(;j<$.length;){let T=$[j],z=S(function(J){if(!Z)throw TypeError(J);O.push({type:"INVALID_CHAR",index:j,value:$[j++]})},"ErrorOrInvalid");if(T==="*"){O.push({type:"ASTERISK",index:j,value:$[j++]});continue}if(T==="+"||T==="?"){O.push({type:"OTHER_MODIFIER",index:j,value:$[j++]});continue}if(T==="\\"){O.push({type:"ESCAPED_CHAR",index:j++,value:$[j++]});continue}if(T==="{"){O.push({type:"OPEN",index:j,value:$[j++]});continue}if(T==="}"){O.push({type:"CLOSE",index:j,value:$[j++]});continue}if(T===":"){let J="",W=j+1;for(;W<$.length;){let Y=$.substr(W,1);if(W===j+1&&KX.test(Y)||W!==j+1&&QX.test(Y)){J+=$[W++];continue}break}if(!J){z(`Missing parameter name at ${j}`);continue}O.push({type:"NAME",index:j,value:J}),j=W;continue}if(T==="("){let J=1,W="",Y=j+1,X=!1;if($[Y]==="?"){z(`Pattern cannot start with "?" at ${Y}`);continue}for(;Y<$.length;){if(!b7($[Y],!1)){z(`Invalid character '${$[Y]}' at ${Y}.`),X=!0;break}if($[Y]==="\\"){W+=$[Y++]+$[Y++];continue}if($[Y]===")"){if(J--,J===0){Y++;break}}else if($[Y]==="("&&(J++,$[Y+1]!=="?")){z(`Capturing groups are not allowed at ${Y}`),X=!0;break}W+=$[Y++]}if(X)continue;if(J){z(`Unbalanced pattern at ${j}`);continue}if(!W){z(`Missing pattern at ${j}`);continue}O.push({type:"REGEX",index:j,value:W}),j=Y;continue}O.push({type:"CHAR",index:j,value:$[j++]})}return O.push({type:"END",index:j,value:""}),O}S(rT,"lexer");function tT($,Z={}){let O=rT($);Z.delimiter??="/#?",Z.prefixes??="./";let j=`[^${b0(Z.delimiter)}]+?`,T=[],z=0,J=0,W="",Y=new Set,X=S((V)=>{if(J<O.length&&O[J].type===V)return O[J++].value},"tryConsume"),D=S(()=>X("OTHER_MODIFIER")??X("ASTERISK"),"tryConsumeModifier"),U=S((V)=>{let x=X(V);if(x!==void 0)return x;let{type:P,index:I}=O[J];throw TypeError(`Unexpected ${P} at ${I}, expected ${V}`)},"mustConsume"),F=S(()=>{let V="",x;for(;x=X("CHAR")??X("ESCAPED_CHAR");)V+=x;return V},"consumeText"),G=S((V)=>V,"DefaultEncodePart"),B=Z.encodePart||G,K="",Q=S((V)=>{K+=V},"appendToPendingFixedValue"),f=S(()=>{K.length&&(T.push(new a$(3,"","",B(K),"",3)),K="")},"maybeAddPartFromPendingFixedValue"),L=S((V,x,P,I,M)=>{let A=3;switch(M){case"?":A=1;break;case"*":A=0;break;case"+":A=2;break}if(!x&&!P&&A===3){Q(V);return}if(f(),!x&&!P){if(!V)return;T.push(new a$(3,"","",B(V),"",A));return}let E;P?P==="*"?E=nT:E=P:E=j;let j0=2;E===j?(j0=1,E=""):E===nT&&(j0=0,E="");let w;if(x?w=x:P&&(w=z++),Y.has(w))throw TypeError(`Duplicate name '${w}'.`);Y.add(w),T.push(new a$(j0,w,B(V),E,B(I),A))},"addPart");for(;J<O.length;){let V=X("CHAR"),x=X("NAME"),P=X("REGEX");if(!x&&!P&&(P=X("ASTERISK")),x||P){let M=V??"";Z.prefixes.indexOf(M)===-1&&(Q(M),M=""),f();let A=D();L(M,x,P,"",A);continue}let I=V??X("ESCAPED_CHAR");if(I){Q(I);continue}if(X("OPEN")){let M=F(),A=X("NAME"),E=X("REGEX");!A&&!E&&(E=X("ASTERISK"));let j0=F();U("CLOSE");let w=D();L(M,A,E,j0,w);continue}f(),U("END")}return T}S(tT,"parse");function b0($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}S(b0,"escapeString");function aT($){return $&&$.ignoreCase?"ui":"u"}S(aT,"flags");function v7($,Z,O){return eT(tT($,O),Z,O)}S(v7,"stringToRegexp");function D$($){switch($){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}S(D$,"modifierToString");function eT($,Z,O={}){O.delimiter??="/#?",O.prefixes??="./",O.sensitive??=!1,O.strict??=!1,O.end??=!0,O.start??=!0,O.endsWith="";let j=O.start?"^":"";for(let W of $){if(W.type===3){W.modifier===3?j+=b0(W.value):j+=`(?:${b0(W.value)})${D$(W.modifier)}`;continue}Z&&Z.push(W.name);let Y=`[^${b0(O.delimiter)}]+?`,X=W.value;if(W.type===1?X=Y:W.type===0&&(X=nT),!W.prefix.length&&!W.suffix.length){W.modifier===3||W.modifier===1?j+=`(${X})${D$(W.modifier)}`:j+=`((?:${X})${D$(W.modifier)})`;continue}if(W.modifier===3||W.modifier===1){j+=`(?:${b0(W.prefix)}(${X})${b0(W.suffix)})`,j+=D$(W.modifier);continue}j+=`(?:${b0(W.prefix)}`,j+=`((?:${X})(?:`,j+=b0(W.suffix),j+=b0(W.prefix),j+=`(?:${X}))*)${b0(W.suffix)})`,W.modifier===0&&(j+="?")}let T=`[${b0(O.endsWith)}]|$`,z=`[${b0(O.delimiter)}]`;if(O.end)return O.strict||(j+=`${z}?`),O.endsWith.length?j+=`(?=${T})`:j+="$",new RegExp(j,aT(O));O.strict||(j+=`(?:${z}(?=${T}))?`);let J=!1;if($.length){let W=$[$.length-1];W.type===3&&W.modifier===3&&(J=O.delimiter.indexOf(W)>-1)}return J||(j+=`(?=${z}|${T})`),new RegExp(j,aT(O))}S(eT,"partsToRegexp");var m1={delimiter:"",prefixes:"",sensitive:!0,strict:!0},CX={delimiter:".",prefixes:"",sensitive:!0,strict:!0},fX={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function R7($,Z){return $.length?$[0]==="/"?!0:!Z||$.length<2?!1:($[0]=="\\"||$[0]=="{")&&$[1]=="/":!1}S(R7,"isAbsolutePathname");function $4($,Z){return $.startsWith(Z)?$.substring(Z.length,$.length):$}S($4,"maybeStripPrefix");function w7($,Z){return $.endsWith(Z)?$.substr(0,$.length-Z.length):$}S(w7,"maybeStripSuffix");function Z4($){return!$||$.length<2?!1:$[0]==="["||($[0]==="\\"||$[0]==="{")&&$[1]==="["}S(Z4,"treatAsIPv6Hostname");var q7=["ftp","file","http","https","ws","wss"];function O4($){if(!$)return!0;for(let Z of q7)if($.test(Z))return!0;return!1}S(O4,"isSpecialScheme");function k7($,Z){if($=$4($,"#"),Z||$==="")return $;let O=new URL("https://example.com");return O.hash=$,O.hash?O.hash.substring(1,O.hash.length):""}S(k7,"canonicalizeHash");function g7($,Z){if($=$4($,"?"),Z||$==="")return $;let O=new URL("https://example.com");return O.search=$,O.search?O.search.substring(1,O.search.length):""}S(g7,"canonicalizeSearch");function y7($,Z){return Z||$===""?$:Z4($)?z4($):T4($)}S(y7,"canonicalizeHostname");function m7($,Z){if(Z||$==="")return $;let O=new URL("https://example.com");return O.password=$,O.password}S(m7,"canonicalizePassword");function p7($,Z){if(Z||$==="")return $;let O=new URL("https://example.com");return O.username=$,O.username}S(p7,"canonicalizeUsername");function h7($,Z,O){if(O||$==="")return $;if(Z&&!q7.includes(Z))return new URL(`${Z}:${$}`).pathname;let j=$[0]=="/";return $=new URL(j?$:"/-"+$,"https://example.com").pathname,j||($=$.substring(2,$.length)),$}S(h7,"canonicalizePathname");function c7($,Z,O){return j4(Z)===$&&($=""),O||$===""?$:J4($)}S(c7,"canonicalizePort");function l7($,Z){return $=w7($,":"),Z||$===""?$:S3($)}S(l7,"canonicalizeProtocol");function j4($){switch($){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}S(j4,"defaultPortForProtocol");function S3($){if($==="")return $;if(/^[-+.A-Za-z0-9]*$/.test($))return $.toLowerCase();throw TypeError(`Invalid protocol '${$}'.`)}S(S3,"protocolEncodeCallback");function d7($){if($==="")return $;let Z=new URL("https://example.com");return Z.username=$,Z.username}S(d7,"usernameEncodeCallback");function i7($){if($==="")return $;let Z=new URL("https://example.com");return Z.password=$,Z.password}S(i7,"passwordEncodeCallback");function T4($){if($==="")return $;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test($))throw TypeError(`Invalid hostname '${$}'`);let Z=new URL("https://example.com");return Z.hostname=$,Z.hostname}S(T4,"hostnameEncodeCallback");function z4($){if($==="")return $;if(/[^0-9a-fA-F[\]:]/g.test($))throw TypeError(`Invalid IPv6 hostname '${$}'`);return $.toLowerCase()}S(z4,"ipv6HostnameEncodeCallback");function J4($){if($===""||/^[0-9]*$/.test($)&&parseInt($)<=65535)return $;throw TypeError(`Invalid port '${$}'.`)}S(J4,"portEncodeCallback");function u7($){if($==="")return $;let Z=new URL("https://example.com");return Z.pathname=$[0]!=="/"?"/-"+$:$,$[0]!=="/"?Z.pathname.substring(2,Z.pathname.length):Z.pathname}S(u7,"standardURLPathnameEncodeCallback");function s7($){return $===""?$:new URL(`data:${$}`).pathname}S(s7,"pathURLPathnameEncodeCallback");function n7($){if($==="")return $;let Z=new URL("https://example.com");return Z.search=$,Z.search.substring(1,Z.search.length)}S(n7,"searchEncodeCallback");function a7($){if($==="")return $;let Z=new URL("https://example.com");return Z.hash=$,Z.hash.substring(1,Z.hash.length)}S(a7,"hashEncodeCallback");var o7=class{#z;#j=[];#Z={};#$=0;#T=1;#X=0;#W=0;#B=0;#G=0;#K=!1;constructor($){this.#z=$}get result(){return this.#Z}parse(){for(this.#j=rT(this.#z,!0);this.#$<this.#j.length;this.#$+=this.#T){if(this.#T=1,this.#j[this.#$].type==="END"){if(this.#W===0){this.#V(),this.#D()?this.#O(9,1):this.#F()?this.#O(8,1):this.#O(7,0);continue}else if(this.#W===2){this.#U(5);continue}this.#O(10,0);break}if(this.#B>0)if(this.#x())this.#B-=1;else continue;if(this.#_()){this.#B+=1;continue}switch(this.#W){case 0:this.#I()&&this.#U(1);break;case 1:if(this.#I()){this.#H();let $=7,Z=1;this.#M()?($=2,Z=3):this.#K&&($=2),this.#O($,Z)}break;case 2:this.#C()?this.#U(3):(this.#f()||this.#F()||this.#D())&&this.#U(5);break;case 3:this.#S()?this.#O(4,1):this.#C()&&this.#O(5,1);break;case 4:this.#C()&&this.#O(5,1);break;case 5:this.#P()?this.#G+=1:this.#A()&&(this.#G-=1),this.#N()&&!this.#G?this.#O(6,1):this.#f()?this.#O(7,0):this.#F()?this.#O(8,1):this.#D()&&this.#O(9,1);break;case 6:this.#f()?this.#O(7,0):this.#F()?this.#O(8,1):this.#D()&&this.#O(9,1);break;case 7:this.#F()?this.#O(8,1):this.#D()&&this.#O(9,1);break;case 8:this.#D()&&this.#O(9,1);break;case 9:break;case 10:break}}this.#Z.hostname!==void 0&&this.#Z.port===void 0&&(this.#Z.port="")}#O($,Z){switch(this.#W){case 0:break;case 1:this.#Z.protocol=this.#Y();break;case 2:break;case 3:this.#Z.username=this.#Y();break;case 4:this.#Z.password=this.#Y();break;case 5:this.#Z.hostname=this.#Y();break;case 6:this.#Z.port=this.#Y();break;case 7:this.#Z.pathname=this.#Y();break;case 8:this.#Z.search=this.#Y();break;case 9:this.#Z.hash=this.#Y();break;case 10:break}this.#W!==0&&$!==10&&([1,2,3,4].includes(this.#W)&&[6,7,8,9].includes($)&&(this.#Z.hostname??=""),[1,2,3,4,5,6].includes(this.#W)&&[8,9].includes($)&&(this.#Z.pathname??=this.#K?"/":""),[1,2,3,4,5,6,7].includes(this.#W)&&$===9&&(this.#Z.search??="")),this.#L($,Z)}#L($,Z){this.#W=$,this.#X=this.#$+Z,this.#$+=Z,this.#T=0}#V(){this.#$=this.#X,this.#T=0}#U($){this.#V(),this.#W=$}#Q($){return $<0&&($=this.#j.length-$),$<this.#j.length?this.#j[$]:this.#j[this.#j.length-1]}#J($,Z){let O=this.#Q($);return O.value===Z&&(O.type==="CHAR"||O.type==="ESCAPED_CHAR"||O.type==="INVALID_CHAR")}#I(){return this.#J(this.#$,":")}#M(){return this.#J(this.#$+1,"/")&&this.#J(this.#$+2,"/")}#C(){return this.#J(this.#$,"@")}#S(){return this.#J(this.#$,":")}#N(){return this.#J(this.#$,":")}#f(){return this.#J(this.#$,"/")}#F(){if(this.#J(this.#$,"?"))return!0;if(this.#j[this.#$].value!=="?")return!1;let $=this.#Q(this.#$-1);return $.type!=="NAME"&&$.type!=="REGEX"&&$.type!=="CLOSE"&&$.type!=="ASTERISK"}#D(){return this.#J(this.#$,"#")}#_(){return this.#j[this.#$].type=="OPEN"}#x(){return this.#j[this.#$].type=="CLOSE"}#P(){return this.#J(this.#$,"[")}#A(){return this.#J(this.#$,"]")}#Y(){let $=this.#j[this.#$],Z=this.#Q(this.#X).index;return this.#z.substring(Z,$.index)}#H(){let $={};Object.assign($,m1),$.encodePart=S3;let Z=v7(this.#Y(),void 0,$);this.#K=O4(Z)}};S(o7,"Parser");var sT=["protocol","username","password","hostname","port","pathname","search","hash"],y1="*";function oT($,Z){if(typeof $!="string")throw TypeError("parameter 1 is not of type 'string'.");let O=new URL($,Z);return{protocol:O.protocol.substring(0,O.protocol.length-1),username:O.username,password:O.password,hostname:O.hostname,port:O.port,pathname:O.pathname,search:O.search!==""?O.search.substring(1,O.search.length):void 0,hash:O.hash!==""?O.hash.substring(1,O.hash.length):void 0}}S(oT,"extractValues");function T1($,Z){return Z?n$($):$}S(T1,"processBaseURLString");function s$($,Z,O){let j;if(typeof Z.baseURL=="string")try{j=new URL(Z.baseURL),Z.protocol===void 0&&($.protocol=T1(j.protocol.substring(0,j.protocol.length-1),O)),!O&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&($.username=T1(j.username,O)),!O&&Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.username===void 0&&Z.password===void 0&&($.password=T1(j.password,O)),Z.protocol===void 0&&Z.hostname===void 0&&($.hostname=T1(j.hostname,O)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&($.port=T1(j.port,O)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&($.pathname=T1(j.pathname,O)),Z.protocol===void 0&&Z.hostname===void 0&&Z.port===void 0&&Z.pathname===void 0&&Z.search===void 0&&($.search=T1(j.search.substring(1,j.search.length),O)),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(j.hash.substring(1,j.hash.length),O))}catch{throw TypeError(`invalid baseURL '${Z.baseURL}'.`)}if(typeof Z.protocol=="string"&&($.protocol=l7(Z.protocol,O)),typeof Z.username=="string"&&($.username=p7(Z.username,O)),typeof Z.password=="string"&&($.password=m7(Z.password,O)),typeof Z.hostname=="string"&&($.hostname=y7(Z.hostname,O)),typeof Z.port=="string"&&($.port=c7(Z.port,$.protocol,O)),typeof Z.pathname=="string"){if($.pathname=Z.pathname,j&&!R7($.pathname,O)){let T=j.pathname.lastIndexOf("/");T>=0&&($.pathname=T1(j.pathname.substring(0,T+1),O)+$.pathname)}$.pathname=h7($.pathname,$.protocol,O)}return typeof Z.search=="string"&&($.search=g7(Z.search,O)),typeof Z.hash=="string"&&($.hash=k7(Z.hash,O)),$}S(s$,"applyInit");function n$($){return $.replace(/([+*?:{}()\\])/g,"\\$1")}S(n$,"escapePatternString");function r7($){return $.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}S(r7,"escapeRegexpString");function t7($,Z){Z.delimiter??="/#?",Z.prefixes??="./",Z.sensitive??=!1,Z.strict??=!1,Z.end??=!0,Z.start??=!0,Z.endsWith="";let O=".*",j=`[^${r7(Z.delimiter)}]+?`,T=/[$_\u200C\u200D\p{ID_Continue}]/u,z="";for(let J=0;J<$.length;++J){let W=$[J];if(W.type===3){if(W.modifier===3){z+=n$(W.value);continue}z+=`{${n$(W.value)}}${D$(W.modifier)}`;continue}let Y=W.hasCustomName(),X=!!W.suffix.length||!!W.prefix.length&&(W.prefix.length!==1||!Z.prefixes.includes(W.prefix)),D=J>0?$[J-1]:null,U=J<$.length-1?$[J+1]:null;if(!X&&Y&&W.type===1&&W.modifier===3&&U&&!U.prefix.length&&!U.suffix.length)if(U.type===3){let F=U.value.length>0?U.value[0]:"";X=T.test(F)}else X=!U.hasCustomName();if(!X&&!W.prefix.length&&D&&D.type===3){let F=D.value[D.value.length-1];X=Z.prefixes.includes(F)}X&&(z+="{"),z+=n$(W.prefix),Y&&(z+=`:${W.name}`),W.type===2?z+=`(${W.value})`:W.type===1?Y||(z+=`(${j})`):W.type===0&&(!Y&&(!D||D.type===3||D.modifier!==3||X||W.prefix!=="")?z+="*":z+=`(${O})`),W.type===1&&Y&&W.suffix.length&&T.test(W.suffix[0])&&(z+="\\"),z+=n$(W.suffix),X&&(z+="}"),W.modifier!==3&&(z+=D$(W.modifier))}return z}S(t7,"partsToPattern");var W4=class{#z;#j={};#Z={};#$={};#T={};#X=!1;constructor($={},Z,O){try{let j;if(typeof Z=="string"?j=Z:O=Z,typeof $=="string"){let W=new o7($);if(W.parse(),$=W.result,j===void 0&&typeof $.protocol!="string")throw TypeError("A base URL must be provided for a relative constructor string.");$.baseURL=j}else{if(!$||typeof $!="object")throw TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(j)throw TypeError("parameter 1 is not of type 'string'.")}typeof O>"u"&&(O={ignoreCase:!1});let T={ignoreCase:O.ignoreCase===!0},z={pathname:y1,protocol:y1,username:y1,password:y1,hostname:y1,port:y1,search:y1,hash:y1};this.#z=s$(z,$,!0),j4(this.#z.protocol)===this.#z.port&&(this.#z.port="");let J;for(J of sT){if(!(J in this.#z))continue;let W={},Y=this.#z[J];switch(this.#Z[J]=[],J){case"protocol":Object.assign(W,m1),W.encodePart=S3;break;case"username":Object.assign(W,m1),W.encodePart=d7;break;case"password":Object.assign(W,m1),W.encodePart=i7;break;case"hostname":Object.assign(W,CX),Z4(Y)?W.encodePart=z4:W.encodePart=T4;break;case"port":Object.assign(W,m1),W.encodePart=J4;break;case"pathname":O4(this.#j.protocol)?(Object.assign(W,fX,T),W.encodePart=u7):(Object.assign(W,m1,T),W.encodePart=s7);break;case"search":Object.assign(W,m1,T),W.encodePart=n7;break;case"hash":Object.assign(W,m1,T),W.encodePart=a7;break}try{this.#T[J]=tT(Y,W),this.#j[J]=eT(this.#T[J],this.#Z[J],W),this.#$[J]=t7(this.#T[J],W),this.#X=this.#X||this.#T[J].some((X)=>X.type===2)}catch{throw TypeError(`invalid ${J} pattern '${this.#z[J]}'.`)}}}catch(j){throw TypeError(`Failed to construct 'URLPattern': ${j.message}`)}}get[Symbol.toStringTag](){return"URLPattern"}test($={},Z){let O={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"?O=s$(O,$,!1):O=s$(O,oT($,Z),!1)}catch{return!1}let j;for(j of sT)if(!this.#j[j].exec(O[j]))return!1;return!0}exec($={},Z){let O={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"?O=s$(O,$,!1):O=s$(O,oT($,Z),!1)}catch{return null}let j={};Z?j.inputs=[$,Z]:j.inputs=[$];let T;for(T of sT){let z=this.#j[T].exec(O[T]);if(!z)return null;let J={};for(let[W,Y]of this.#Z[T].entries())if(typeof Y=="string"||typeof Y=="number"){let X=z[W+1];J[Y]=X}j[T]={input:O[T]??"",groups:J}}return j}static compareComponent($,Z,O){let j=S((W,Y)=>{for(let X of["type","modifier","prefix","value","suffix"]){if(W[X]<Y[X])return-1;if(W[X]===Y[X])continue;return 1}return 0},"comparePart"),T=new a$(3,"","","","",3),z=new a$(0,"","","","",3),J=S((W,Y)=>{let X=0;for(;X<Math.min(W.length,Y.length);++X){let D=j(W[X],Y[X]);if(D)return D}return W.length===Y.length?0:j(W[X]??T,Y[X]??T)},"comparePartList");return!Z.#$[$]&&!O.#$[$]?0:Z.#$[$]&&!O.#$[$]?J(Z.#T[$],[z]):!Z.#$[$]&&O.#$[$]?J([z],O.#T[$]):J(Z.#T[$],O.#T[$])}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.#X}};S(W4,"URLPattern");function lZ($,Z){for(let[O,j]of Object.entries($)){let T=new W4({pathname:O});if(T.test({pathname:Z}))return{routePath:O,params:T.exec({pathname:Z})?.pathname.groups??{},route:j}}return null}var F$={startIndex:0,carriedViews:[]};function e7($,Z){let O=z0($.path,Z);return O.includes("*")?null:O}function VX($,Z){if(!$)return F$;if($.search!==Z.search)return F$;let O=Math.min($.segments.length,Z.segments.length-1),j=0;while(j<O){let T=$.segments[j],z=Z.segments[j];if(z.alwaysRun)break;if(T.viewPath!==z.viewPath)break;let J=e7(T,$.params),W=e7(z,Z.params);if(J===null||W===null||J!==W)break;j++}if(j===0)return F$;return{startIndex:j,carriedViews:Z.segments.slice(0,j).map(({viewPath:T})=>T)}}function IX($,Z){let[,O,...j]=$.split("/");if(!Z.includes(O))return $;let T=`/${j.join("/")}`;return T==="/"?"/":T.replace(/\/$/,"")}function $J($){let{flatViewRoutes:Z,supportedLocales:O,from:j,origin:T,to:z}=$;if(!j)return F$;let J;try{J=new URL(j,T)}catch{return F$}if(J.origin!==T)return F$;let W=lZ(Z,IX(J.pathname,O));if(!W)return F$;return VX({segments:W.route.segments,params:W.params,search:J.search},z)}var Y4="x-gemi-from";import{createElement as ZZ,Fragment as lX}from"react";function LX($){return $.replace(/\([^)]*\)/g,"").replace(/\/\//g,"/")}function N3($){let Z={};for(let[O,j]of Object.entries($))if("run"in j){let T=j.viewPath;if("children"in j){Z[O]=[T];let z=new j.children,J=N3(z.routes);for(let[W,Y]of Object.entries(J)){let X=O==="/"?W:`${O}${W}`,D=W==="/"&&O!=="/"?O:X;Z[D]=[T,...Y]}if(Z[O].length===1)delete Z[O]}else Z[O]=[T]}else{let T=new j,z=N3(T.routes);for(let[J,W]of Object.entries(z)){let Y=O==="/"?J:`${O}${J}`,X=J==="/"&&O!=="/"?O:Y;Z[X]=W}}return Object.fromEntries(Object.entries(Z).map(([O,j])=>[LX(O),j]))}function _3($){let Z=[];for(let[O,j]of Object.entries($))if("run"in j){let T=j.viewPath;if(T==="__")continue;if(T==="REDIRECT")continue;if(T==="FILE")continue;if("children"in j){let z=new j.children,J=_3(z.routes);Z.push([T,J])}else Z.push([T,[]])}else{let T=new j,z=_3(T.routes);Z.push(...z)}return Z}function X4($){let Z=[];for(let[O,j]of $)Z.push(O,...X4(j).flat());return Array.from(new Set(Z))}class p1 extends K0{static getFacadeAccessor(){return u}static getSupportedLocales(){return this.getFacadeRoot().supportedLocales}static getDefaultLocale(){return this.getFacadeRoot().defaultLocale}static locale(){let $=this.getFacadeRoot(),Z=N.getStore();if(Z)return Z.locale??$.detectLocale(Z.req);return $.defaultLocale}static timeZone(){return this.getFacadeRoot().detectTimeZone(N.getStore()?.req)}static formatter($={}){return this.getFacadeRoot().formatter($.locale??p1.locale(),$.timeZone??p1.timeZone())}static setLocale($=p1.locale()){let Z=this.getFacadeRoot(),O=$;if(!Z.supportedLocales.includes($))O=Z.defaultLocale;let j=N.getStore();return j.setCookie("i18n-locale",O,{expires:new Date(Date.now()+31536000000),secure:!1,httpOnly:!1}),j.setLocale(O),O}}class D4{id;static token="kernel.id";constructor($=crypto.randomUUID()){this.id=$}}var MX=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript"]),SX=new Set(["svg","math"]);function ZJ($){return $===32||$===9||$===10||$===12||$===13}function OJ($){return $>=65&&$<=90||$>=97&&$<=122}function x3($){return $>=65&&$<=90?$+32:$}function jJ(){let $="data",Z="",O=!1,j="",T=0,z=0,J=!1,W=0,Y=0,X=()=>$==="data"&&W===0&&Y===0,D=()=>{if(!O&&MX.has(Z)){$="rawText",j=`</${Z}`,T=0,Z="";return}if($="data",Z==="template")if(O)W=Math.max(0,W-1);else W+=1;else if(SX.has(Z)){if(O)Y=Math.max(0,Y-1);else if(!J)Y+=1}Z=""},U=(F)=>{switch($){case"data":if(F===60)$="tagOpen";return;case"tagOpen":if(F===33)$="bang",z=0;else if(F===47)$="endTagOpen";else if(OJ(F))$="tagName",O=!1,J=!1,Z=String.fromCharCode(x3(F));else if(F===63)$="bogus";else if(F===60)$="tagOpen";else $="data";return;case"endTagOpen":if(OJ(F))$="tagName",O=!0,J=!1,Z=String.fromCharCode(x3(F));else if(F===62)$="data";else $="bogus";return;case"tagName":if(ZJ(F)||F===47)$="inTag",J=F===47;else if(F===62)D();else Z+=String.fromCharCode(x3(F));return;case"inTag":if(F===62){D();return}if(J=F===47,F===34)$="attrDouble";else if(F===39)$="attrSingle";return;case"attrDouble":if(F===34)$="inTag";J=!1;return;case"attrSingle":if(F===39)$="inTag";J=!1;return;case"bang":if(F===45){if(z+=1,z===2)$="comment",z=0}else if(F===62)$="data";else $="bogus";return;case"bogus":if(F===62)$="data";return;case"comment":if(F===45)z=z<2?z+1:2;else if(F===62&&z>=2)$="data",z=0;else z=0;return;case"rawText":{if(T<j.length){if(x3(F)===j.charCodeAt(T))T+=1;else T=F===60?1:0;return}if(F===62)$="data",Z="";else if(ZJ(F)||F===47)$="inTag",Z="";else T=F===60?1:0;return}}};return{scanToInsertionPoint(F){for(let G=0;G<F.length;G++){if(X())return G;U(F[G])}return F.length},write(F){for(let G=0;G<F.length;G++)U(F[G])},isSafe:X}}function U$($){let Z=JSON.stringify($);if(Z===void 0)return"undefined";return Z.replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function NX($){return`<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${U$([$.path,$.variantKey,$.data])})</script>`}function _X($){return`<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${U$([$.id,$.locale,$.strings])})</script>`}function F4($,Z,O={},j){let T=new TextEncoder,z=[],J=!1,W=!1,Y=()=>{if(W)return;W=!0,O.onClose?.()};Z.onSettle((B)=>{if(B.status!=="resolved")return;z.push(NX(B))}),j?.onUse((B)=>{z.push(_X(B))});let X=$.getReader(),D=jJ(),U=(B,K)=>{B.enqueue(K),O.onChunk?.(K)},F=(B)=>{while(z.length>0){let K=T.encode(z.shift());D.write(K),U(B,K)}},G=(B,K)=>{if(z.length===0){D.write(K),U(B,K);return}let Q=D.scanToInsertionPoint(K);if(Q>0)U(B,K.subarray(0,Q));if(D.isSafe())F(B);let f=K.subarray(Q);if(f.length>0)D.write(f),U(B,f)};return new ReadableStream({async pull(B){let K;try{K=await X.read()}catch(L){throw Y(),L}let{done:Q,value:f}=K;if(Q){F(B),B.close(),Y();return}if(!J){if(J=!0,D.write(f),U(B,f),O.onShell?.(),D.isSafe())F(B);return}G(B,f)},cancel(B){return Y(),X.cancel(B)}})}var xX=/bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;function P3($){if(!$)return!1;return xX.test($)}async function zJ($,Z=()=>{}){let O=N.getStore(),j=O?.req??null,T=null;if(j?.rawRequest?.url)try{T=new URL(j.rawRequest.url).pathname}catch{T=null}return{user:O?.user??null,attributes:await PX($,Z),request:{path:T,routePath:j?.routePath??null,locale:O?.locale??null},anonymousId:TJ(),isBot:P3(j?.rawRequest?.headers?.get("user-agent")??null),now:new Date}}function JJ($){return{user:$.user??null,attributes:$.attributes??{},request:{path:null,routePath:null,locale:null},anonymousId:$.subjectId??null,isBot:!1,now:new Date}}async function PX($,Z){if(!$.context)return{};try{let O=N.getStore();return await $.context(O?.req??null)??{}}catch(O){return Z(`The \`context\` hook in app/config/features.ts threw; evaluating with no attributes. ${O instanceof Error?O.message:String(O)}`),{}}}function WJ($,Z){return`${$}:${Z}`}function U4($){let Z=new Bun.CryptoHasher("sha1").update($).digest("hex"),O=Number.parseInt(Z.slice(0,8),16);return Math.floor(O/4294967296*1e4)}function YJ($,Z){if(Z>=100)return!0;if(Z<=0)return!1;return $<Math.round(Z*100)}function XJ($,Z,O,j){if(j.unavailable)return{value:!1,reason:"unavailable"};if(j.active!==!0)return{value:!1,reason:"inactive"};if(Z.when){let z;try{z=Z.when(O)}catch(J){return j.warn?.(`The \`when\` for feature "${$}" threw; treating it as off. ${J instanceof Error?J.message:String(J)}`),{value:!1,reason:"error"}}if(typeof z==="boolean")return{value:z,reason:"attributed"}}if(Z.rollout===void 0)return{value:!0,reason:"on"};if(O.isBot)return{value:!1,reason:"bot"};let T=HX($,Z,O,j.buckets);return YJ(T,Z.rollout)?{value:!0,reason:"rollout"}:{value:!1,reason:"excluded"}}function AX($){let Z=$.user?.publicId??$.user?.id;if(Z!==void 0&&Z!==null)return String(Z);return $.anonymousId??""}function HX($,Z,O,j){let T=WJ(Z.salt??$,AX(O));if(!j)return U4(T);let z=j.get(T);if(z!==void 0)return z;let J=U4(T);return j.set(T,J),J}class DJ 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 B4{source;declared;ttlMs;warn;snapshot=null;inflight=null;lastFailureLoggedAt=0;generation=0;lastError=null;retryAfter=0;constructor($,Z,O,j=()=>{}){this.source=$;this.declared=Z;this.ttlMs=O;this.warn=j}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 DJ(this.lastError);return Z}peek(){return this.snapshot}async load(){try{let $=await this.source.load(),{active:Z,audit:O}=this.readRows($);return this.snapshot={active:Z,audit:O,loadedAt:Date.now(),unavailable:!1},this.generation++,this.lastError=null,this.retryAfter=0,this.snapshot}catch($){return this.handleFailure($)}}readRows($){let Z=new Map,O=new Map;for(let j of $??[]){let T=typeof j?.key==="string"?j.key:null;if(!T){this.warn("Ignoring a feature row with no `key`.");continue}if(!(T in this.declared)){this.warn(`Feature row "${T}" is not declared in app/features, so it is ignored. Delete the row, or declare the feature.`);continue}Z.set(T,j.active===!0);let z=EX(j);if(z)O.set(T,z)}return{active:Z,audit:O}}handleFailure($){let Z=$ instanceof Error?$.message:String($),O=Date.now();if(this.lastError=$,this.retryAfter=O+this.ttlMs,O-this.lastFailureLoggedAt>=this.ttlMs)this.lastFailureLoggedAt=O,this.warn(`Could not load feature switches: ${Z}`);if(this.snapshot)return this.snapshot;return this.snapshot={active:new Map,audit:new Map,loadedAt:O,unavailable:!0},this.snapshot}}function EX($){let Z={},O=$.updatedBy;if(typeof O==="string")Z.updatedBy=O;else if(O===null)Z.updatedBy=null;let j=$.updatedAt;if(j instanceof Date||typeof j==="string"||typeof j==="number"){let T=j instanceof Date?j:new Date(j);if(!Number.isNaN(T.getTime()))Z.updatedAt=T}return"updatedBy"in Z||"updatedAt"in Z?Z:null}class bX{}class vX 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 G4 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 FJ 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 UJ{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 o${config;log;static token="features";store;declared;warnedAboutSize=!1;warnedAboutActor=!1;constructor($,Z=()=>{}){this.config=$;this.log=Z;this.declared=$.features??{},this.store=new B4($.source,this.declared,Math.max(0,$.ttl)*1000,this.log)}declarations(){return this.declared}async list(){let{active:$,audit:Z,unavailable:O}=await this.switches();return{unavailable:O,features:Object.entries(this.declared).map(([j,T])=>({key:j,describe:T.describe,rollout:T.rollout,targeted:T.when!==void 0,serverOnly:T.serverOnly,salt:T.salt,active:$.get(j),...Z.get(j)}))}}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{N.getStore()?.featureEvaluations?.clear()}}async set($,Z,O={}){if(typeof $!=="string"||!Object.hasOwn(this.declared,$))throw new FJ(String($));if(typeof Z!=="boolean")throw TypeError(`Features.set("${$}", \u2026) takes a boolean, not ${Z===null?"null":typeof Z}.`);let j=RX(O.actor),T=this.config.source;if(typeof T.write!=="function")throw new G4(T.constructor?.name||"an anonymous source");let{actorRecorded:z}=await T.write($,Z,{actor:j});if(j!==null&&!z&&!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 UJ(this,JJ($))}async evaluateIn($,Z,O){let j=this.memoFor(Z),T=j?.get($);if(T)return T;let z=this.declared[$];if(!z)return{value:!1,reason:"undeclared"};let{active:J,unavailable:W}=await this.switchFor($),Y=XJ($,z,Z,{active:J,unavailable:W,buckets:O,warn:this.log});return j?.set($,Y),this.notify($,Y,Z),Y}async evaluateAllIn($,Z,O){let j={};for(let[T,z]of Object.entries(this.declared)){if(O.clientOnly&&z.serverOnly)continue;j[T]=(await this.evaluateIn(T,$,Z)).value}return j}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 $=N.getStore();if($?.featureContext)return $.featureContext;let Z=await zJ(this.config,this.log);if($)$.featureContext=Z;return Z}memoFor($){let Z=N.getStore();if(!Z||Z.featureContext!==$)return null;return Z.featureEvaluations??=new Map,Z.featureEvaluations}requestBuckets(){let $=N.getStore();if(!$)return new Map;return $.featureBuckets??=new Map,$.featureBuckets}notify($,Z,O){if(!this.config.onEvaluate)return;try{this.config.onEvaluate($,Z,O)}catch(j){this.log(`The \`onEvaluate\` hook in app/config/features.ts threw for "${$}". ${j instanceof Error?j.message:String(j)}`)}}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 RX($){if($===void 0||$===null)return null;if(typeof $==="string"){if($.length>0)return $}else if(typeof $==="object"){let{publicId:Z,id:O}=$;if(typeof Z==="string"&&Z.length>0)return Z;if(typeof O==="string"&&O.length>0||typeof O==="number")return String(O)}throw TypeError("Features.set() was given an `actor` that identifies nobody. Pass a string, or a user with a `publicId` or an `id`.")}function BJ($){return Object.fromEntries(Object.entries($).filter(([,Z])=>{return Z!==null&&Z!==void 0}))}var wX=50;class r${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((O)=>O.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(),(O)=>({path:O.path,variantKey:O.variantKey,startedAt:O.startedAt,settledAt:O.settledAt,status:O.status,source:O.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 T=JSON.stringify($.data)?.length??0;Z=T>=1024?`${(T/1024).toFixed(1)} kB`:`${T} B`}catch{Z="an unserializable payload"}let O=($.settledAt??0)-$.startedAt,j=$.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 (${O}ms, resolved ${Z}) could not overlap the others. It still streamed. If the query belongs on this route, \`Query.prefetch("${$.patternPath}"${j})\` 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={},O="render"){let j=Z.params??{},T=new URLSearchParams(BJ(Z.search??{}));T.delete("json"),T.sort();let z=z0($,j),J=T.toString(),W=this.keyFor(z,J),Y=this.entries.get(W);if(Y)return Y;let X;if(O==="render"&&this.renderStartedAt!==null){let G=Math.round(performance.now()-this.renderStartedAt);if(G>wX)X=G}let D,U=new Promise((G)=>{D=G}),F={path:z,patternPath:$,variantKey:J,lateBy:X,status:"pending",promise:U,source:O,startedAt:this.elapsed()};return this.entries.set(W,F),this.fetcher($,j,T).then((G)=>{F.status="resolved",F.data=G},(G)=>{F.status="rejected",F.error=G}).then(()=>{if(F.settledAt=this.elapsed(),this.maybeLogLateDiscovery(F),F.status==="rejected"&&this.failListener)this.failListener(F);if(this.settleListener)this.settleListener(F);else this.settledBacklog.push(F);D()}),F}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,O]of this.entries){if(O.status!=="resolved")continue;this.shipped.add(Z),$[O.path]??={},$[O.path][O.variantKey]=O.data}return $}onSettle($){this.settleListener=(O)=>{if(this.shipped.has(this.keyFor(O.path,O.variantKey)))return;$(O)};let Z=this.settledBacklog;this.settledBacklog=[];for(let O of Z)this.settleListener(O)}}class h1 extends Error{path;variantKey;status;body;retryAfter;constructor($,Z,O,j,T){super(typeof j?.message==="string"?j.message:`Request to /api${$} failed with status ${O}`);this.path=$;this.variantKey=Z;this.status=O;this.body=j;this.retryAfter=T;this.name="QueryError"}}function t$(){let $=JSON.stringify({error:L1("permission","Forbidden",403)});return new Response($,{status:403,headers:{"Content-Type":"application/json","Content-Length":String(Buffer.byteLength($)),"Cache-Control":"no-store"}})}function K4(){return{status:403,error:{message:"Forbidden"}}}function dZ($){let Z=e$.getStore();return(O,j,T)=>{let z=new URL($.url).origin,J=[z0(O,j),T.toString()].filter((D)=>D.length>0).join("?"),W=new Request(`${z}/${J}`,{headers:$.headers,signal:$.signal}),Y=GJ($);if(Y)$Z(W,Y);let X=new _(W,j);return e$.run(Z,()=>N.run(X,async()=>{try{let D=await C(s0).dispatchers(Y).api.getRouteData(O);if(f$(D)){if(!D.ok)throw new h1(z0(O,j),T.toString(),D.status,D.body);return D.body}if(D instanceof Response){let U=await D.json().catch(()=>null);if(!D.ok)throw new h1(z0(O,j),T.toString(),D.status,U);return U}return D}catch(D){if(D instanceof h1)throw D;let U=new h1(z0(O,j),T.toString(),500,{message:D instanceof Error?D.message:String(D)});throw U.cause=D,U}}))}}var qX=new Set(["script","style","template","title"]),kX=/\shidden([\s=/]|$)/i,gX=/"[^"]*"|'[^']*'/g;function yX($){let Z=0,O=0,j=0,T=0;while(T<$.length){let z=$.indexOf("<",T),J=z===-1?$.length:z;if(J>T){let U=$.slice(T,J).replace(/\s+/g,"").length;if(j>0)O+=U;else Z+=U}if(z===-1)break;if($.startsWith("<!--",z)){let U=$.indexOf("-->",z+4);T=U===-1?$.length:U+3;continue}let W=$.indexOf(">",z);if(W===-1)break;let Y=$.slice(z+1,W);T=W+1;let X=/^\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(Y)?.[1]?.toLowerCase();if(!X)continue;let D=Y.startsWith("/");if(!D&&qX.has(X)&&!Y.endsWith("/")){let U=$.indexOf(`</${X}`,T);T=U===-1?$.length:U;continue}if(X!=="div")continue;if(D){if(j>0)j-=1}else if(j>0)j+=1;else if(kX.test(Y.replace(gX,'""')))j=1}return{shellChars:Z,deferredChars:O}}var mX=1000,pX=64;function hX($){return $>=1000?`${($/1000).toFixed(1)} kB`:`${$} chars`}function cX($,Z){if(Z.deferredChars<mX)return null;if(Z.shellChars>=pX)return null;return`[gemi] GET ${$} streams ${hX(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 KJ($=console.warn){let Z=new Set;return{shouldObserve(O){return!Z.has(O)},report(O,j){if(Z.has(O))return;let T=cX(O,j);if(!T)return;Z.add(O),$(T)}}}function QJ(){let $=new TextDecoder,Z="";return{onChunk(O){Z+=$.decode(O,{stream:!0})},measure(){return Z+=$.decode(),yX(Z)}}}function CJ($,Z,O=1e4,j){let T=new TextEncoder,z=()=>{};return new ReadableStream({start(J){let W=!1,Y=(D)=>{if(W)return;W=!0,clearTimeout(X);try{J.close()}catch{}j?.({aborted:D})};z=Y,J.enqueue(T.encode(`${JSON.stringify($)}
3
+ `)),Z.onSettle((D)=>{if(W||D.status!=="resolved")return;J.enqueue(T.encode(`${JSON.stringify([D.path,D.variantKey,D.data])}
4
+ `))});let X=setTimeout(()=>Y(!0),O);Z.allSettled().then(()=>Y(!1),()=>Y(!1))},cancel(){z(!1)}})}var dX=async()=>(await import("./chunk-tymhsmgq.js")).default,Q4,C4=async(...$)=>{return Q4??=import("react-dom/server.browser").catch((Z)=>{throw Q4=void 0,Z}),(await Q4).renderToReadableStream(...$)},iX=1e4,uX=`
5
+ !function(){try{var d=document.documentElement,c=d.classList;
6
+ c.remove('light','dark');
7
+ var e=localStorage.getItem('theme');
8
+ if('system'===e||(!e&&'system'===defaultTheme)){
9
+ var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);
10
+ if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}
11
+ else{d.style.colorScheme='light';c.add('light')}
12
+ }else if(e){
13
+ c.add(e||'')
14
+ }}catch(e){}}()
15
+ `;async function sX($,Z,O){let j=`${O==="italic"?"italic,":""}wght@${O==="italic"?"1,":""}${Z}`,J=(await(await fetch(`https://fonts.googleapis.com/css2?family=${$}:${j}&display=swap`,{headers:{"User-Agent":"Mozilla/5.0 Firefox/1.0"}})).text()).match(/url\(([^)]+)\)/)?.[1];return await fetch(J).then((W)=>W.arrayBuffer())}var I4="/assets";function nX($){return $===I4||$.startsWith(`${I4}/`)}function aX($){let Z=$.filter(nX);if(Z.length>0){let O=Z.length>1;throw Error(`View route path${O?"s":""} ${Z.map((j)=>`"${j}"`).join(", ")} use${O?"":"s"} the reserved "${I4}" prefix. The client build output is served from there before the router runs, so the route would never match. Mount it somewhere else.`)}}function oX($){let Z=C(s0).resolver;return{...$.domain,root:Z.root,origin:Z.publicOrigin($.rawRequest)}}function f4($){let{status:Z=400,error:O}=$;return new Response(O?.message,{...$,status:Z})}function rX($){let{status:Z=400,data:O,directive:j,headers:T}=$;return new Response(JSON.stringify({data:O,directive:j}),{headers:T,status:Z})}class sZ{static token="router.view";flatViewRoutes={};routeManifest={};clientRouteManifest={};componentTree=[];flatComponentTree=[];root=null;shellReporter=KJ();preloadCache=new WeakMap;hooks;partialRendering;constructor($){let Z=A7();this.partialRendering=$.partialRendering??Z.partialRendering,this.hooks={onRequestStart:$.onRequestStart??Z.onRequestStart,onRequestEnd:$.onRequestEnd??Z.onRequestEnd,onRequestFail:$.onRequestFail??Z.onRequestFail,onStreamComplete:$.onStreamComplete??Z.onStreamComplete};let O={"/":$.rootRouter,"/auth":gT};this.flatViewRoutes=M3(O),aX(Object.keys(this.flatViewRoutes)),this.routeManifest=N3(O),this.clientRouteManifest=Object.fromEntries(Object.entries(this.routeManifest).filter(([,j])=>j.at(-1)!=="FILE")),this.componentTree=_3(O),this.flatComponentTree=X4(this.componentTree),this.root=$.root}async passesFeatureGates($){let Z=C(o$);for(let O of $)if(!await Z.enabled(O))return!1;return!0}async onRequestEnd($){return V4(),await this.hooks.onRequestEnd($)}completeStream($,Z){let O=(j)=>{B$.error(j?.message??'Error in "onStreamComplete" event handler',{err:JSON.stringify(j)})};try{Promise.resolve(this.hooks.onStreamComplete($,Z)).catch(O)}catch(j){O(j)}}modulePreloadLinks($){let{clientEntry:Z,modulePreloadManifest:O,views:j,routeKey:T}=$,z=()=>{let Y=new Set(Z?.preload??[]);for(let X of j)for(let D of O?.[X]??[])Y.add(D);return[...Y].map((X)=>ZZ("link",{key:`modulepreload:${X}`,rel:"modulepreload",href:X}))};if(!O)return z();let J=this.preloadCache.get(O);if(!J||J.clientEntry!==Z)J={clientEntry:Z,byRoute:new Map},this.preloadCache.set(O,J);let W=J.byRoute.get(T);if(!W)W=z(),J.byRoute.set(T,W);return W}async render($){let{req:Z,runInRequestScope:O,csrfTokenHMAC:j,currentPathName:T,headers:z,i18n:J,params:W,pathname:Y,serverQueries:X,userAgent:D,noStream:U,url:F,user:G,viewData:B,breadcrumbs:K,urlLocaleSegment:Q,meta:f,isOgRequest:L,appId:V,features:x}=$,P=Y.replace(`/${Q}`,""),I={kind:"view",data:{meta:f,pageData:{[P]:B},__csrf:j.toString("base64"),prefetchedData:{},i18n:J,auth:{user:G},routeManifest:this.clientRouteManifest,breadcrumbs:K,router:{urlLocaleSegment:Q,pathname:T,params:W,currentPath:Y,searchParams:F.search,is404:!T?!0:!1,domain:Z.domain?oX(Z):null},appId:V,features:x,componentTree:[["404",[]],...this.componentTree]},head:{}},M=this.root,A=this.routeManifest[T];return async(E)=>{let{bootstrapModules:j0=[],loaders:w,getStyles:g,viewImportMap:i,cssManifest:w3,ogMap:nZ,viewModules:aZ,clientEntry:n0,modulePreloadManifest:c1,assetBase:f1}=E,T0=n0?[]:j0,oZ=(o)=>[o,`window.loaders=${w}`,...n0?[`import(${JSON.stringify(n0.module)}).catch(function(e){setTimeout(function(){throw e})})`]:[]].join(";");if(L){let o=null,Q$=null;for(let C$ of A??[])if(typeof nZ[C$]==="function")Q$=C$,o=nZ[C$];if(!o)return new Response("Not found",{status:404});let sJ=Object.values(I.data.pageData)[0];try{await C4(ZZ(o,sJ[Q$]),{onError:()=>{}})}catch(C$){let{fonts:nJ,...aJ}=C$.satoriOptions,oJ=await Promise.all(nJ.map((rZ)=>{return sX(rZ.name,rZ.weight,rZ.style).then((ZW)=>({...rZ,data:ZW}))})),A4=new Headers(z);A4.set("Content-Type","image/png");let[rJ,tJ]=await Promise.all([dX(),I3("Rendering an OG image")]),eJ=await rJ(C$.jsx,{...aJ,fonts:oJ}),$W=await tJ(Buffer.from(eJ)).png({compressionLevel:0,effort:10}).toBuffer();return new Response(new Uint8Array($W),{headers:A4})}return new Response("data")}if(I.data.cssManifest=w3,I.data.modulePreloadManifest=c1??{},f1&&f1!=="/")I.data.assetBase=f1;let q3=this.modulePreloadLinks({clientEntry:n0,modulePreloadManifest:c1,views:A??["404"],routeKey:T??"404"}),G$=await g(A);I.data.prefetchedData=X.snapshotResolved(),X.markRenderStart();let J1=new AbortController,TZ=setTimeout(()=>J1.abort(),iX),K$=P3(D)||U,b=Bun.env.NODE_ENV!=="production"&&!K$&&T&&this.shellReporter.shouldObserve(T)?QJ():null,v0=IJ();try{let o=await C4(ZZ(lX,{children:[...q3,...G$,ZZ("script",{key:"theme-script",dangerouslySetInnerHTML:{__html:uX}}),ZZ(M,{data:I.data,viewImportMap:i,viewModules:aZ,serverQueries:X,dictionarySink:v0,key:"root"})]}),{bootstrapScriptContent:oZ(`window.__GEMI_DATA__ = ${U$(I.data)}`),bootstrapModules:T0,signal:J1.signal,...K$?{progressiveChunkSize:Number.MAX_SAFE_INTEGER}:{},onError(Q$){if(Bun.env.NODE_ENV!=="production")console.error(Q$)}});if(o.allReady.catch(()=>{}).finally(()=>clearTimeout(TZ)),K$)await o.allReady.catch(()=>{});return new Response(F4(o,X,{onShell:K$?void 0:()=>X.markShell(),onChunk:b?.onChunk,onClose:()=>O(()=>{if(this.completeStream(Z,X.summarize(J1.signal.aborted)),b)this.shellReporter.report(T,b.measure())})},v0),{status:!T?404:200,headers:z})}catch(o){if(clearTimeout(TZ),Bun.env.NODE_ENV==="production")throw O(()=>this.completeStream(Z,X.summarize(J1.signal.aborted))),o;let Q$=await C4(ZZ("div"),{bootstrapScriptContent:oZ(`window.error= ${U$(o.message)}; window.stack_trace=${U$(o.stack)};window.__GEMI_DATA__ = ${U$(I.data)}`),bootstrapModules:Bun.env.NODE_ENV==="development"?["/render-error.js",...T0]:T0});return new Response(F4(Q$,X,{onClose:()=>O(()=>this.completeStream(Z,X.summarize(J1.signal.aborted)))}),{status:!T?404:200,headers:z})}}}async handleViewRequest($,Z){let O=new URL($.url),j=O.pathname.endsWith(".json"),T=O.pathname.endsWith(".og"),z=O.pathname.replace(".json","").replace(".og",""),[,J,...W]=z.split("/"),Y=`/${W.join("/")}`,X=null,D=null,U=C(u);if(!U.supportedLocales.includes(J))Y=z;else X=J,D=J;let G=D===null&&lZ(this.flatViewRoutes,Y)!==null;if(U.isLocaleAware&&!T&&D===null&&!G){let I=fJ(J,U.supportedLocales,U.defaultLocale);if(I){let M=W.length?`/${W.join("/")}`:"";return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${M}${j?".json":""}${O.search}`}})}}if(U.isLocaleAware&&!T){let I=C(u).detectLocale(new _($,{},"view",Y));if(D===null&&I!==U.defaultLocale){let M=O.pathname==="/"?"":O.pathname;return new Response("",{status:302,headers:{"Cache-Control":"private, no-cache, no-store, max-age=0, must-revalidate",Location:`/${I}${M}${O.search}`}})}}Y=Y.replace("//","/");let B=[],K=[],Q=null,f={},L=null,V=!1,x=[];try{let I=lZ(this.flatViewRoutes,Y);if(I){if(Q=I.routePath,f=I.params,B=I.route.exec,K=I.route.middleware,x=I.route.features,V=K.includes("no-stream"),j&&this.partialRendering){let M=$.headers.get(Y4),A=$J({flatViewRoutes:this.flatViewRoutes,supportedLocales:C(u).supportedLocales,from:M,origin:O.origin,to:{segments:I.route.segments,params:f,search:O.search}});if(A.startIndex>0)B=B.slice(A.startIndex),L={from:M,carriedViews:A.carriedViews}}}}catch(I){throw I}let P=new _($,f,"view",Q);return this.hooks.onRequestStart(P),await N.run(P,async()=>{let I=null,M=N.getStore(),A=e$.getStore(),E=(g)=>e$.run(A,()=>N.runWith(M,g));M.serverQueries=new r$(dZ($));let j0=new Set;if(M.serverQueries.onQueryFail((g)=>{j0.add(g.error);try{E(()=>Promise.resolve(this.hooks.onRequestFail(w,g.error)).catch(()=>{}))}catch{}}),D){let g=D.replaceAll("/","");p1.setLocale(g)}else p1.setLocale();let w=M.req;V4();try{let g=!1;try{await C(cZ).runMiddleware(K)}catch(b){if(!OZ(b))throw b;g=!0}if(g||x.length>0&&!await this.passesFeatureGates(x))Q=null,B=[],w.routePath="";let i=C(u),w3=i.isEnabled,nZ=i.isLocaleAware,aZ=new _($,w.params),n0={defaultLocale:i.defaultLocale,timeZone:i.detectTimeZone(aZ)};if(nZ){let b=null;if(D)b=D.replaceAll("/",""),M.setLocale(b);else b=i.detectLocale(aZ),M.setLocale(b);let v0=w3?i.getPageTranslations(b,w.routePath):{};n0={...n0,supportedLocales:i.supportedLocales,currentLocale:b,dictionary:{[b]:v0},defaultLocale:i.defaultLocale}}await VJ(n0.currentLocale??"");let c1;try{c1=await Promise.all(B.map((b)=>b(w)))}catch(b){if(!OZ(b))throw b;Q=null,B=[],w.routePath="",c1=[]}let{cookies:f1,headers:T0}=M;I={data:c1,cookies:f1,headers:T0,user:M.user,prefetchedData:M.serverQueries.snapshotResolved(),currentPathName:Q,params:w.params,urlLocaleSegment:X,meta:M.renderMeta(),appId:C(D4).id,features:await C(o$).forClient()};let{params:oZ,user:q3}=I,G$={},J1={};for(let b of c1??[]){let[v0,o]=Object.entries(b)?.[0]??[];if(!v0||!o)continue;J1[`${v0}:${Q}`]=o.breadcrumb,G$[v0]=o}let TZ=G$.FILE;if(TZ){for(let b of f1)T0.append("Set-Cookie",b.toString());try{await this.onRequestEnd(w)}catch(b){B$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await d3(TZ,T0)}if(j){T0.set("Content-Type","application/x-ndjson; charset=utf-8"),T0.append("Vary",Y4),f1.forEach((v0)=>T0.append("Set-Cookie",v0.toString())),await this.hooks.onRequestEnd(w);let b={meta:L&&!M.metadata.touched?null:I.meta,data:{[Y]:G$},breadcrumbs:J1,prefetchedData:M.serverQueries.snapshotResolved(),i18n:n0,features:I.features,is404:!Q,appId:I.appId,partial:L};return new Response(CJ(b,M.serverQueries,void 0,({aborted:v0})=>E(()=>this.completeStream(w,M.serverQueries.summarize(v0)))),{headers:T0})}if(T0.set("Content-Type","text/html; charset=utf-8"),!V)T0.append("Vary","User-Agent");for(let b of f1)T0.append("Set-Cookie",b.toString());let K$=Bun.CSRF.generate(process.env.SECRET);T0.append("Set-Cookie",`csrf_token=${K$}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now()+86400000).toUTCString()}`);try{await this.onRequestEnd(w)}catch(b){B$.error(b?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(b)})}return await this.render({req:w,runInRequestScope:E,csrfTokenHMAC:Buffer.from(""),currentPathName:Q,headers:T0,i18n:n0,params:oZ,pathname:O.pathname,serverQueries:M.serverQueries,userAgent:$.headers.get("user-agent"),noStream:V,url:O,user:q3,viewData:G$,breadcrumbs:J1,urlLocaleSegment:X,meta:I.meta,appId:I.appId,features:I.features,isOgRequest:T})}catch(g){if(g.kind===iZ)if(j)return rX(g.payload.viewData??g.payload.api);else return f4(g.payload.view);if(!j0.has(g))this.hooks.onRequestFail(w,g);if(uZ(g))return console.error(g),j?t$():f4(K4());if(g instanceof h1&&g.status===403)return j?t$():f4(K4());throw g}},Z)}}function M4(){let $=JSON.stringify({error:L1("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 xJ extends N0{routes={"/api-routes":this.get(()=>{let $=C(A3).flatRoutes,Z=[];for(let[O,j]of Object.entries($))for(let[T,z]of Object.entries(j)){let{exec:J,middleware:W}=z;Z.push({path:O,method:T,middleware:W})}return Z}),"/view-routes":this.get(()=>{let $=C(sZ).flatViewRoutes,Z=[];for(let[O,{middleware:j,viewPath:T}]of Object.entries($))Z.push({path:O,method:"GET",viewPath:T,middleware:j});return Z})}}var tX=new Set([I1,"cookie","content-type","content-length","transfer-encoding","connection","host","user-agent","forwarded"]),eX=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$D=/^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;function ZD($,Z,O){for(let[j,T]of Object.entries(O.headers??{})){if(T===void 0||T===null)continue;let z=j.toLowerCase();if(tX.has(z)||z.startsWith("x-forwarded-"))throw Error(`dispatchAs: credentials may not set the "${j}" header. The access token stays the initiator's, and the request's framing is dispatchAs's own.`);$.set(j,T)}for(let[j,T]of Object.entries(O.cookies??{})){if(T===void 0||T===null)continue;if(j===I1)throw Error(`dispatchAs: credentials may not set the "${I1}" cookie. The access token stays the initiator's.`);if(!eX.test(j)||!$D.test(T))throw Error(`dispatchAs: "${j}" is not a cookie a Cookie header can carry.`);Z.push(`${j}=${T}`)}}function OD($,Z){let O=$.body.getReader(),j=!1,T=()=>{if(j)return;j=!0;try{Z()}catch(J){console.error(J)}},z=new ReadableStream({async pull(J){let W;try{W=await O.read()}catch(Y){T(),J.error(Y);return}if(W.done){T();try{J.close()}catch{}return}try{J.enqueue(W.value)}catch{}},async cancel(J){try{await O.cancel(J)}finally{T()}}},{highWaterMark:0});return new Response(z,{status:$.status,statusText:$.statusText,headers:$.headers})}function LJ($){let{status:Z=400,data:O,headers:j}=$,T=new Headers({"Content-Type":"application/json",...j});if(!T.has("Cache-Control"))T.set("Cache-Control","no-store");return new Response(JSON.stringify(O),{status:Z,headers:T})}function MJ($,Z,O){let j=[];Z?.forEach((J,W)=>j.push([W,J]));let T=[...typeof Z?.getSetCookie==="function"?Z.getSetCookie():[],...Array.from(O??[])];if(j.length===0&&T.length===0)return $;let z=(J)=>{for(let[W,Y]of j){if(W.toLowerCase()==="set-cookie")continue;if(!J.has(W))J.set(W,Y)}for(let W of T)J.append("Set-Cookie",W)};try{return z($.headers),$}catch{let J=new Headers($.headers);return z(J),new Response($.body,{status:$.status,statusText:$.statusText,headers:J})}}class A3{static token="router.api";flatRoutes={};onRequestStart;onRequestEnd;onRequestFail;constructor($){let Z=P7();this.onRequestStart=$.onRequestStart??Z.onRequestStart,this.onRequestEnd=$.onRequestEnd??Z.onRequestEnd,this.onRequestFail=$.onRequestFail??Z.onRequestFail,this.flatRoutes=dT({"/":$.rootRouter,"/auth":yT,"/__gemi__/services/i18n":mT,"/__gemi__/services/logs":lT,"/__gemi__/services/image":cT,"/__gemi__/debug":xJ})}getRouteHandlerAndParams($){let Z=new URL($.url),O=_J(Z.pathname),j={},T;for(let[z]of Object.entries(this.flatRoutes))try{let J=new URLPattern({pathname:z});if(J.test({pathname:O})){T=z,j=J.exec({pathname:O})?.pathname.groups;break}}catch(J){console.error(J)}return{params:j,path:T}}async runRouteMiddleware($,Z){let j=this.flatRoutes[$][Z.rawRequest.method].middleware;try{await C(cZ).runMiddleware(j)}catch(T){if(T.kind===iZ)return LJ(T.payload.api);else{if(OZ(T))return M4();if(this.onRequestFail(Z,T),console.error(T),uZ(T))return t$();throw T}}}async getRouteData($){let Z=this.flatRoutes[$],O=N.getStore(),j=Z[O.req.rawRequest.method].exec??(()=>Promise.resolve({})),T={};try{T=await j()}catch(z){if(z.kind===iZ)return LJ(z.payload.api);if(OZ(z))return M4();if(this.onRequestFail(O.req,z),console.error(z),uZ(z))return t$();throw z}return T}isFrameworkRoute($){return $.startsWith("/__gemi__")}async endRequest($,Z,O){let j=async()=>{try{if(!this.isFrameworkRoute(O))await this.onRequestEnd(Z)}catch(T){B$.error(T?.message??'Error in "onRequestEnd" event handler',{err:JSON.stringify(T)})}finally{$.destroy()}};if(!$.hasPendingWork()){await j();return}$.whenIdle().then(j).catch((T)=>{console.error(T)})}isOpenEndedBody($,Z){return $.method!=="HEAD"&&!Z.headers.has("Content-Length")&&Z.body!==null}async handleApiRequest($,Z){let{params:O,path:j}=this.getRouteHandlerAndParams($),T=this.flatRoutes[j];if(!T||!T[$.method])return new Response(JSON.stringify({error:L1("not_found","Not found",404)}),{status:404});let z=new _($,O,"api",j);if(!this.isFrameworkRoute(j))this.onRequestStart(z);return await N.run(z,async()=>{let J=N.getStore(),W=!1,Y=async()=>{W=!0,await this.endRequest(J,z,j)};try{let X=C(u);if(X.isEnabled){let K=X.detectLocale(z);J.setLocale(K)}J.setRequest(z);let D=await this.runRouteMiddleware(j,z);if(D instanceof Response){let K=MJ(D,J.headers,J.cookies);return await Y(),K}let U=await this.getRouteData(j),F=J.headers,G=J.cookies;if(U instanceof Response){let K=MJ(U,F,G);if(this.isOpenEndedBody($,K)){let Q=OD(K,()=>this.endRequest(J,z,j));return W=!0,Q}return await Y(),K}let B=(f$(U)?U:l1.json(U)).toResponse(F,G);return await Y(),B}catch(X){if(!W)try{await Y()}catch(D){console.error(D)}throw X}},Z)}async dispatchAs($,Z,O,j,T){let z=new URL($.rawRequest.url).origin,J=new URL(`${z}/api${O}`),W=`/api${O.split(/[?#]/)[0]}`;if(!O.startsWith("/")||J.origin!==z||J.pathname!==W||J.hash!==""||J.pathname.startsWith("/api/__gemi__")||J.pathname==="/api/auth"||J.pathname.startsWith("/api/auth/"))throw Error(`dispatchAs: "${O}" is not an app api path. Pass the route's own path, without "/api", with every param encoded.`);let Y=new Headers,X=[],D=$.cookies.get(I1);if(D)X.push(`${I1}=${D}`);if(T?.credentials)ZD(Y,X,T.credentials);if(X.length>0)Y.set("Cookie",X.join("; "));let U=$.headers.get(I1);if(U)Y.set(I1,U);let F=$.headers.get("User-Agent");if(F)Y.set("User-Agent",F);let G;if(j instanceof FormData)G=j;else if(j!==void 0)Y.set("Content-Type","application/json"),G=JSON.stringify(j);let B=new Request(J,{method:Z,headers:Y,body:G});if(SJ(B,I$($)),$.domain)$Z(B,$.domain);return N.exit(()=>NJ.exit(()=>this.handleApiRequest(B)))}}import{timingSafeEqual as jD}from"crypto";var E3="",_4="*",TD=60000,zD=1e4,S4=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,H3=16,PJ=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,N4="x-forwarded-host";function AJ($){return $.startsWith(":")}function x4($,Z){if($===null)return!1;let O=Buffer.from($,"utf8"),j=Buffer.from(Z,"utf8");return O.length===j.length&&jD(O,j)}function JD($){if(!$)return null;if($===!0)return{header:N4,secret:null};return{header:($.hostHeader??N4).toLowerCase(),secret:$.secret?{header:$.secret.header.toLowerCase(),value:$.secret.value}:null}}function WD($){if(!$||$===!0)return;let{hostHeader:Z,secret:O}=$;if(Z!==void 0&&(typeof Z!=="string"||!PJ.test(Z)))throw Error(`\`route.domains.trustProxy.hostHeader\` must be a single header name, e.g. "x-forwarded-host". Got ${JSON.stringify(Z)}.`);if(!O)return;if(typeof O.header!=="string"||!PJ.test(O.header))throw Error(`\`route.domains.trustProxy.secret.header\` must be a header name. Got "${O.header}".`);if(O.header.toLowerCase()===(Z??N4).toLowerCase())throw Error("`route.domains.trustProxy.secret.header` names the same header as `hostHeader`; the secret needs a header of its own.");if(typeof O.value!=="string"||O.value.length<H3)throw Error(`\`route.domains.trustProxy.secret.value\` must be at least ${H3} characters. A guessable one lets any client name its own host.`)}function z1($){if(!$)return null;try{return new URL(`http://${$.trim()}`).hostname.toLowerCase().replace(/\.$/,"")||null}catch{return null}}function YD($){try{let Z=new URL(`http://${$.trim()}`),O=Z.hostname.toLowerCase().replace(/\.$/,"");return O?Z.port?`${O}:${Z.port}`:O:null}catch{return null}}function XD($){let Z=z1($.root),O=$.root?.trim().toLowerCase().replace(/\.$/,"");if(!Z||Z!==O||!Z.split(".").every((z)=>S4.test(z)))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<H3)throw Error(`\`route.domains.ask.secret\` must be at least ${H3} characters. A guessable one is worse than leaving \`ask\` out.`);WD($.trustProxy);let j=new Set,T=null;for(let z of $.groups??[]){let{subdomain:J}=z;if(j.has(J))throw Error(`\`route.domains\` declares the subdomain "${J}" twice.`);if(j.add(J),AJ(J)){if(!/^:[A-Za-z_][A-Za-z0-9_]*$/.test(J))throw Error(`"${J}" is not a valid param subdomain. It must be a single \`:name\` label.`);if(T)throw Error(`\`route.domains\` declares two param subdomains, "${T.subdomain}" and "${J}"; a host could match either.`);T=z;continue}if(z.exists)throw Error(`The subdomain "${J}" is fixed, so \`exists\` has no param to check. It only applies to a \`:param\` subdomain.`);if(!J.split(".").every((W)=>S4.test(W)))throw Error(`"${J}" is not a valid subdomain.`)}if($.custom&&!j.has($.custom.group))throw Error(`\`route.domains.custom.group\` is "${$.custom.group}", but no group declares that subdomain.`);if($.ask&&T&&!T.exists)throw Error(`\`route.domains.ask\` is set, so "${T.subdomain}" needs an \`exists\` to say which tenants are real. Without one every host under the root would be approved for a certificate.`)}class P4{root;hostTrust;fixed=new Map;param=null;custom;cacheTtlMs;cache=new Map;inFlight=new Map;askSecret;proxySecretHeader;constructor($){XD($),this.root=z1($.root),this.hostTrust=JD($.trustProxy);for(let Z of $.groups??[])if(AJ(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??TD,this.askSecret=$.ask?.secret??null,this.proxySecretHeader=this.hostTrust?.secret?.header??null}forwardedHost($){let Z=this.hostTrust;if(!Z)return null;if(Z.secret&&!x4($.headers.get(Z.secret.header),Z.secret.value))return null;return $.headers.get(Z.header)?.split(",")[0]?.trim()||null}hostOf($){return z1(this.forwardedHost($))??z1(new URL($.url).host)}publicOrigin($){let Z=new URL($.url),O=$.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),j=O==="http"||O==="https"?O:Z.protocol.replace(/:$/,""),T=this.forwardedHost($),z=T&&z1(T)?YD(T):null;return`${j}://${z??Z.host}`}async resolve($){let Z=this.hostOf($);if(!Z)return null;let O=await this.match(Z,$);if(O)return O;if(this.custom?.fallback&&!this.isUnderRoot(Z))return{host:Z,group:_4,params:{},custom:!0};return null}async allows($,Z){let O=z1($);return O?await this.match(O,Z)!==null:!1}isUnderRoot($){return $===this.root||$.endsWith(`.${this.root}`)}async match($,Z){if($===this.root)return{host:$,group:E3,params:{},custom:!1};if($.endsWith(`.${this.root}`)){let j=$.slice(0,-(this.root.length+1)),T=this.fixed.get(j);if(T)return{host:$,group:T.subdomain,params:{},custom:!1};if(this.param&&S4.test(j)){let z={[this.param.name]:j};if(this.param.exists&&!await this.param.exists(z,Z))return null;return{host:$,group:this.param.subdomain,params:z,custom:!1}}return null}if(!this.custom)return null;let O=await this.resolveCustom($);return O?{host:$,group:this.custom.group,params:O,custom:!0}:null}async resolveCustom($){let Z=Date.now(),O=this.cache.get($);if(O&&O.expiresAt>Z)return this.cache.delete($),this.cache.set($,O),O.value;let j=this.inFlight.get($);if(j)return j;let T=(async()=>await this.custom.resolve($)??null)();this.inFlight.set($,T);let z;try{z=await T}finally{this.inFlight.delete($)}if(this.cacheTtlMs>0){if(this.cache.size>=zD)this.cache.delete(this.cache.keys().next().value);this.cache.delete($),this.cache.set($,{value:z,expiresAt:Date.now()+this.cacheTtlMs})}return z}forget($){if($===void 0)this.cache.clear();else{let Z=z1($);if(Z)this.cache.delete(Z)}}}var DD="/__gemi__/domains/ask";class s0{static token="router.domains";resolver;acceptsCustomDomains;groups=new Map;constructor($,Z){this.groups.set(E3,$);let{domains:O}=Z;if(this.acceptsCustomDomains=Boolean(O?.custom),!O){this.resolver=null;return}this.resolver=new P4(O);let j=(T)=>({api:T.api?new A3({...Z.api,...T.api}):$.api,view:T.view?new sZ({...Z.view,...T.view}):$.view});for(let T of O.groups??[])this.groups.set(T.subdomain,j(T));if(O.custom?.fallback)this.groups.set(_4,j(O.custom.fallback))}async route($){if(!this.resolver)return this.dispatchers(null);if(this.resolver.proxySecretHeader)HJ($,this.resolver.proxySecretHeader);let Z=await this.resolver.resolve($);if(!Z)return null;return $Z($,Z),this.dispatchers(Z)}async ask($){if(!this.resolver?.askSecret||$.method!=="GET")return null;let Z=new URL($.url);if(Z.pathname!==DD)return null;if(!x4(Z.searchParams.get("secret"),this.resolver.askSecret))return null;let O=Z.searchParams.get("domain"),j=O?await this.resolver.allows(O,$):!1;return new Response(null,{status:j?200:404})}dispatchers($){return this.groups.get($?.group??E3)}viewDispatchers(){return Array.from(new Set(Array.from(this.groups.values(),($)=>$.view)))}}function b3($){let Z=new Date($??0).getTime();return Number.isFinite(Z)?Z:0}var EJ=600000;function bJ($,Z){return[TO($,Z),TO($,Z-1)]}class H{static token="auth";config;provider;constructor($={},Z=new Jj){this.config={...vJ(Kz($),$),emailCode:Tj($.emailCode)},this.provider=Z}get userProvider(){return this.provider}accessTokenCookieOptions($,Z){return{expires:Z,secure:this.publicOrigin($).startsWith("https://"),httpOnly:!0,domain:this.cookieDomain($)}}publicOrigin($){let Z=C().bound(s0)?C(s0).resolver:null;return Z?Z.publicOrigin($.rawRequest):new URL($.rawRequest.url).origin}cookieDomain($){let Z=this.config.cookieDomain;if(!Z)return;let O=Z==="root"?C(s0).resolver?.root:z1(Z);if(!O)throw Error('`auth.cookieDomain` is "root", but `route.domains` is not configured.');let j=$.domain?.host??z1(new URL($.rawRequest.url).host);return j===O||j?.endsWith(`.${O}`)?O:void 0}async getSession($,Z){if(!$)return null;if(!r3($))return this.config.migrateLegacySession?this.convertLegacySession($,Z,this.config.migrateLegacySession):null;let O=await this.userProvider.findSession({token:$,userAgent:Z});if(!O?.user)return null;let j=Date.now(),T=b3(O.expiresAt),z=b3(O.absoluteExpiresAt);if(T<=j||z<=j)return await this.userProvider.deleteSession({token:$}),null;let W=await this.slideSession(O,j);return W.user.extension=await this.config.extendSession(W.user),W}async convertLegacySession($,Z,O){let j=N.getStore()?.req;if(!j)return null;let T=Date.now(),z=Math.floor(T/EJ),J=null,W=await this.userProvider.findSession({token:$,userAgent:Z});if(W?.user){if(!await O(W,{token:$,req:j,userAgent:Z}))return null;let X=TO($,z),D=W.user.id;if(await this.userProvider.withLegacySessionLock($,async()=>{if(!await this.userProvider.claimLegacySession({token:$}))return!1;return await this.userProvider.createSessionV2({token:X,userId:D,userAgent:Z,...this.freshLifetime(T)}),!0}))J=X}if(!J){for(let X of bJ($,z))if((await this.userProvider.findSession({token:X,userAgent:Z}))?.user){J=X;break}}if(!J)return null;let Y=await this.getSession(J,Z);if(Y)j.ctx().setCookie("access_token",J,this.accessTokenCookieOptions(j,new Date(Y.expiresAt)));return Y}async revokeSession($,Z){if(!$)return await this.userProvider.deleteSession({token:$}),null;if(r3($)||!this.config.migrateLegacySession){let T=await this.userProvider.findSession({token:$,userAgent:Z});return await this.userProvider.deleteSession({token:$}),T}let O=Math.floor(Date.now()/EJ),j=bJ($,O);return this.userProvider.withLegacySessionLock($,async()=>{let T=await this.userProvider.findSession({token:$,userAgent:Z});for(let z of j){if(T?.user)break;T=await this.userProvider.findSession({token:z,userAgent:Z})}await this.userProvider.deleteSession({token:$});for(let z of j)await this.userProvider.deleteSession({token:z});return T})}requestCarryingCookie($){let Z=N.getStore()?.req;return Z?.cookies.get("access_token")===$?Z:null}async slideSession($,Z){let O=this.config.sessionExpiresInHours*3600000;if(new Date($.expiresAt).getTime()-Z>=O/2)return $;let j=new Date(Math.min(Z+O,new Date($.absoluteExpiresAt).getTime())),T=await this.userProvider.updateSession({token:$.token,expiresAt:j}),z=this.requestCarryingCookie($.token);if(z)z.ctx().setCookie("access_token",$.token,this.accessTokenCookieOptions(z,j));if(!T)return $;return{...$,expiresAt:T.expiresAt??j}}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 O=await this.createOrUpdateSession({email:$,id:Z.id}),j=new _;if(j.ctx().setCookie("access_token",O.token,this.accessTokenCookieOptions(j,O.expiresAt)),O?.user)O.user.extension=await this.config.extendSession(O.user);return O}catch(Z){console.log(Z)}}async createOrUpdateSessionV2($){let Z=await this.createOrUpdateSession($),O=null;if(Z?.user)O=await this.config.extendSession(Z.user),Z.user.extension=O;return Z}async createOrUpdateSession($){let Z=new _,O=$.id??(await this.userProvider.findUserByEmailAddress($.email,!1))?.id;if(!O)throw new d1;let j=Bun.env.NODE_ENV==="development"?"local":Z.headers.get("User-Agent"),T=Tz(O),z=await this.userProvider.createSessionV2({token:T,userId:O,userAgent:j,...this.freshLifetime(Date.now())}),J=await this.userProvider.findSession({token:T,userAgent:j??""});return J?.user?J:z}async createMagicLinkToken($){let Z=await this.userProvider.findUserByEmailAddress($,!1);if(Z){let{pin:O,token:j}=await this.issueOneTimeCode($,6);return{user:Z,email:$,pin:O,token:j}}return{}}async issueOneTimeCode($,Z){await this.userProvider.deleteMagicLinkToken($);let O=await this.config.generateMagicLinkToken($),j=await this.config.generateCode($),T=typeof j==="string"&&j!==""?j:Fz(Z);return await this.userProvider.createMagicLinkToken({email:$,token:zO("link",$,O),pin:zO("pin",$,T)}),{email:$,pin:T,token:O}}async verifyOneTimeCode($,Z,O={}){let{expiresInMinutes:j,maxAttempts:T}=this.config.emailCode,z=await this.userProvider.findMagicLinkTokenByEmail($);if(!z)return YZ("pin",$,null,Z),{status:"invalid"};let J=b3(z.createdAt);if(J+j*60000<=Date.now())return YZ("pin",$,null,Z),{status:"expired"};if(!await Gz(z.id,J,T,j))return await this.userProvider.claimMagicLinkToken(z.id),{status:"too_many_attempts"};if(!YZ("pin",$,z.pin,Z))return{status:"invalid"};if(O.claim!==!1&&!await this.userProvider.claimMagicLinkToken(z.id))return{status:"invalid"};return{status:"ok",row:z}}async verifyMagicLinkToken($,Z){let O=await this.userProvider.findMagicLinkTokenByEmail($),j=YZ("link",$,O?.token,Z);if(!O||!j)return!1;if(b3(O.createdAt)+this.config.emailCode.linkExpiresInMinutes*60000<=Date.now())return!1;return await this.userProvider.claimMagicLinkToken(O.id)}}class X$ extends K0{static getFacadeAccessor(){return H}static async user(){let $=N.getStore(),Z=$?.user;if(!Z){if(Z=await OO(this.getFacadeRoot(),$?.req),Z)$?.setUser(Z)}if(Z)return Z;throw new d1({redirectTo:ZO($?.req,this.getFacadeRoot().config.signInPath)})}static intendedUrl($){let Z=N.getStore()?.req;return JZ(Z?.search.get(V$),$??this.getFacadeRoot().config.redirectPath)}static async guard($){let Z=await X$.user();if(!await $(Z))throw new a3}static async guardSafe($){let Z=await X$.user();try{return await $(Z)}catch(O){return!1}}static async authenticate($){return await this.getFacadeRoot().authenticate($)}static async createMagicLink($){return await this.getFacadeRoot().createMagicLinkToken($)}}class v3{static ensure($,Z={}){let O=N.getStore();if(O.req.kind==="api")throw Error("Query.prefetch() cannot be called from an API request");return O.serverQueries??=new r$(dZ(O.req.rawRequest)),O.serverQueries.ensure($,Z,"prefetch")}static async instant($,...Z){let O=v3.ensure($,Z[0]);if(await O.promise,O.status==="rejected")throw O.error;return O.data}static prefetch($,...Z){v3.ensure($,Z[0])}static noPrefetch(){let $=N.getStore();if($.req.kind==="api")throw Error("Query.noPrefetch() cannot be called from an API request");$.serverQueries??=new r$(dZ($.req.rawRequest)),$.serverQueries.muteDiscoveryHints()}}function RJ($,Z,O="/"){let j=new URL($.origin),T=Z.host?Z.host:Z.subdomain?`${Z.subdomain}.${$.root}`:$.root,z=new URL(O.startsWith("/")?O:`/${O}`,j),J=FD(T);if(!J)throw Error(`"${T}" 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(z.hostname=J.hostname,J.port)z.port=J.port;return z.toString()}function FD($){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 wJ{static absolute($,...Z){return`${process.env.HOST_NAME}${z0(String($),Z[0]??{})}`}static relative($,...Z){return z0(String($),Z[0]??{})}static forDomain($,Z,...O){let j=C(s0).resolver;if(!j)throw Error("`Url.forDomain` needs `route.domains` to be configured.");let T=N.getStore()?.req?.rawRequest,z=T?j.publicOrigin(T):process.env.HOST_NAME;if(!z)throw Error("`Url.forDomain` outside a request needs `HOST_NAME` for the protocol.");return RJ({root:j.root,origin:z},$,z0(String(Z),O[0]??{}))}}class qJ{name="Meta";static description($){N.getStore().metadata.description($)}static title($){N.getStore().metadata.title($)}static openGraph($){N.getStore().metadata.openGraph($)}}var UD={set($,Z,O){N.getStore().setCookie($,Z,O)},setIfAbsent($,Z,O){if(N.getStore().req.cookies.has($))return!1;return N.getStore().setCookie($,Z,O),!0},delete($,Z){N.getStore().deleteCookie($,Z)}};class C1 extends K0{static getFacadeAccessor(){return kJ}static get client(){return this.getFacadeRoot().client}static get($){return C1.client.get($)}static set($,Z){return C1.client.set($,Z)}static del(...$){return C1.client.del(...$)}static exists($){return C1.client.exists($)}static incr($){return C1.client.incr($)}static expire($,Z){return C1.client.expire($,Z)}static ttl($){return C1.client.ttl($)}}class gJ extends K0{static getFacadeAccessor(){return o0}static consume($,Z={}){return this.getFacadeRoot().consume($,Z)}}class mJ extends K0{static getFacadeAccessor(){return yJ}static run($,Z,O){return this.getFacadeRoot().run($,Z,O)}static acquire($,Z={}){return this.getFacadeRoot().acquire($,Z)}}class pJ extends K0{static getFacadeAccessor(){return o$}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,O){return this.getFacadeRoot().set($,Z,O)}static refresh(){return this.getFacadeRoot().refresh()}static invalidate(){return this.getFacadeRoot().invalidate()}}class R3{bound;constructor($){this.bound=$}get name(){return this.bound??FZ()}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,O=this.connection(Z);return lJ(O.sql,(j)=>hJ(Z,()=>$(j)),{slowTransactionThreshold:O.config.slowTransactionThreshold,connection:Z})}async schema(){let $=this.connection(),{introspect:Z}=await import("./chunk-aa13sgs2.js");return Z(this.handle()??$.sql,$.dialect)}run($,Z){let O=this.connection(),{text:j,values:T}=iJ($,dJ(O.dialect),Z);return(this.handle()??O.sql).unsafe(j,T)}handle(){let $=DZ();if($===void 0)return;return FZ()===this.name?$:void 0}connection($=this.name){return cJ($),C(UZ).connection($)}}var jZ=new R3;class uJ extends K0{static getFacadeAccessor(){return UZ}static connection($){return new R3($)}static get sql(){return jZ.sql}static get dialect(){return jZ.dialect}static query($){return jZ.query($)}static execute($){return jZ.execute($)}static transaction($){return jZ.transaction($)}static schema(){return jZ.schema()}static close(){return this.getFacadeRoot().close()}}export{W1 as gc,zZ as hc,m3 as ic,N0 as jc,c3 as kc,g4 as lc,$O as mc,l1 as nc,JW as oc,d3 as pc,V1 as qc,R0 as rc,WW as sc,YW as tc,o3 as uc,r3 as vc,Tz as wc,o0 as xc,WZ as yc,r4 as zc,I$ as Ac,zz as Bc,Jz as Cc,e3 as Dc,$j as Ec,zO as Fc,YZ as Gc,QU as Hc,Kz as Ic,MW as Jc,Jj as Kc,X$ as Lc,p1 as Mc,v3 as Nc,wJ as Oc,qJ as Pc,UD as Qc,C1 as Rc,gJ as Sc,mJ as Tc,WJ as Uc,U4 as Vc,YJ as Wc,XJ as Xc,AX as Yc,DJ as Zc,B4 as _c,bX as $c,vX as ad,G4 as bd,FJ as cd,UJ as dd,o$ as ed,pJ as fd,R3 as gd,uJ as hd,pT as id,hT as jd,TB as kd,N7 as ld,_7 as md,cZ as nd,fB as od,P7 as pd,A7 as qd,D4 as rd,t$ as sd,K4 as td,I4 as ud,nX as vd,f4 as wd,rX as xd,sZ as yd,M4 as zd,LJ as Ad,MJ as Bd,A3 as Cd,s0 as Dd,H as Ed,i4 as Fd,u4 as Gd,s4 as Hd,$z as Id,Zz as Jd,Oz as Kd};
16
+
17
+ //# debugId=29A789CD26C2BA9264756E2164756E21