@gjermundgaraba/clankerauth-dev 0.24.0 → 0.26.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.
@@ -0,0 +1,539 @@
1
+ import{t as e}from"./esm-CdWTLqG7.mjs";import{c as t,r as n,s as r}from"./sqlite-introspector-DSCAP82F-CISODKY3.mjs";import{c as i,i as a,n as o,o as s,r as c,s as l,t as u}from"./dist-D9v3IUMo.mjs";import{t as d}from"./compiled-query-C8AL3JwF.mjs";import{A as f,B as p,C as m,D as h,E as g,F as _,G as v,H as y,I as b,K as x,L as S,N as ee,P as C,R as te,S as ne,T as w,U as T,V as re,W as ie,_ as ae,a as oe,b as se,c as ce,d as le,f as ue,g as de,h as fe,i as pe,j as me,k as he,l as ge,m as _e,o as ve,p as ye,q as be,t as xe,u as Se,v as eee,w as tee,x as Ce,y as we,z as Te}from"./get-id-field-CHlYHt3y.mjs";import{A as nee,C as Ee,D as De,E as Oe,F as ke,I as Ae,L as je,M as E,N as D,O as ree,P as O,S as k,T as iee,_ as Me,a as aee,b as Ne,c as Pe,d as Fe,f as Ie,g as Le,h as Re,i as ze,j as Be,k as Ve,l as He,m as Ue,n as oee,o as We,p as see,r as Ge,s as Ke,t as cee,u as qe,v as A,w as Je,x as Ye,y as Xe}from"./schemas-CYWNDEcx.mjs";import{a as Ze,c as lee,l as uee,o as dee,r as fee,s as pee}from"./schema-check-6AE7KkNs.mjs";import{n as mee,r as Qe}from"./factory-tEOeUNZI.mjs";import{n as $e}from"./access-CoaNEa0I.mjs";import*as et from"node:crypto";import{randomBytes as tt,scrypt as nt}from"node:crypto";import*as rt from"node:path";import it,{dirname as at,join as ot,resolve as st}from"node:path";import*as ct from"node:url";import{fileURLToPath as lt}from"node:url";import ut,*as dt from"node:os";import*as ft from"node:child_process";import{Duplex as hee,PassThrough as pt,Readable as mt,pipeline as gee}from"node:stream";import{IncomingMessage as ht,createServer as gt}from"node:http";import{isIP as _t}from"node:net";import*as vt from"node:fs";import yt,{mkdirSync as bt}from"node:fs";import{request as xt}from"node:https";import*as St from"node:stream/promises";import{pipeline as Ct}from"node:stream/promises";import*as wt from"node:zlib";import*as Tt from"node:readline";import{DatabaseSync as Et}from"node:sqlite";import Dt from"node:fs/promises";import{lookup as _ee}from"node:dns/promises";const Ot=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let e=0,r=t.length;e<r;e++)n=t[e](n);return n}}},kt={pipe(){return Ot(this,arguments)}},At=/*#__PURE__*/ function(){function e(){}return e.prototype=kt,e}(),j=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},M=e=>e,jt=e=>()=>e,Mt=/*#__PURE__*/ jt(!0),Nt=/*#__PURE__*/ jt(!1),Pt=/*#__PURE__*/ jt(void 0),Ft=Pt;function It(e,...t){return Ot(e,t)}function vee(e,t,n,r,i,a,o,s,c){switch(arguments.length){case 1:return e;case 2:return function(){return t(e.apply(this,arguments))};case 3:return function(){return n(t(e.apply(this,arguments)))};case 4:return function(){return r(n(t(e.apply(this,arguments))))};case 5:return function(){return i(r(n(t(e.apply(this,arguments)))))};case 6:return function(){return a(i(r(n(t(e.apply(this,arguments))))))};case 7:return function(){return o(a(i(r(n(t(e.apply(this,arguments)))))))};case 8:return function(){return s(o(a(i(r(n(t(e.apply(this,arguments))))))))};case 9:return function(){return c(s(o(a(i(r(n(t(e.apply(this,arguments)))))))))}}}function Lt(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function Rt(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i!==n&&t.set(i,i),i}}const zt=e=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;e instanceof Error&&t.delete(`stack`);let n=Object.getPrototypeOf(e),r=n;for(;r!==null&&r!==Object.prototype;){let e=Reflect.ownKeys(r);for(let n=0;n<e.length;n++)t.add(e[n]);r=Object.getPrototypeOf(r)}return t.has(`constructor`)&&typeof e.constructor==`function`&&n===e.constructor.prototype&&t.delete(`constructor`),t},Bt=/*#__PURE__*/ new WeakSet,Vt=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let Ht=0;const yee=()=>{Ht++};function Ut(e){return typeof e==`string`}function Wt(e){return typeof e==`number`}function Gt(e){return typeof e==`boolean`}function Kt(e){return typeof e==`symbol`}function qt(e){return Ut(e)||Wt(e)||Kt(e)}function Jt(e){return typeof e==`function`}function Yt(e){return e===void 0}function Xt(e){return e!==void 0}function Zt(e){return e!==null}function Qt(e){return e==null}function $t(e){return e!=null}function en(e){return!1}function tn(e){return!0}function nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e){return nn(e)}function an(e){return typeof e==`object`&&!!e||Jt(e)}const N=/*#__PURE__*/ j(2,(e,t)=>an(e)&&t in e),on=/*#__PURE__*/ j(2,(e,t)=>N(e,`_tag`)&&e._tag===t);function sn(e){return e instanceof Error}function cn(e){return N(e,Symbol.iterator)||Ut(e)}const ln=`~effect/Hash`,un=e=>{switch(typeof e){case`number`:return gn(e);case`bigint`:return _n(e.toString(10));case`string`:return _n(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?_n(`Invalid Date`):_n(e.toISOString());if(e instanceof RegExp)return _n(e.toString());{if(Bt.has(e))return dn(e);let t=wn.get(e);if(t!==void 0)return t;if(Tn.has(e))return yee(),_n(`[Circular]`);Tn.add(e);let n=Ht,r;try{r=`~effect/Hash`in e?e[ln]():typeof e==`function`?dn(e):e instanceof DataView?bn(Vt(e)):Array.isArray(e)||ArrayBuffer.isView(e)?bn(e):e instanceof Map?xee(e):e instanceof Set?Sn(e):vn(e)}finally{Tn.delete(e)}return n===Ht&&wn.set(e,r),r}}return mn(fn(_n(String(e))))},dn=e=>(Cn.has(e)||Cn.set(e,mn(Math.random()*4294967296|0)),Cn.get(e)),fn=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),pn=/*#__PURE__*/ j(2,(e,t)=>fn(Math.imul(e,2654435761)+Math.imul(t,2246822507))),mn=e=>e&3221225471|e>>>1&1073741824,hn=/*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)),gn=e=>{let t=e|0;return t===e?mn(t):(hn.setFloat64(0,e===e?e:NaN),mn(pn(hn.getInt32(0),hn.getInt32(4))))},_n=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return mn(t)},bee=(e,t)=>{let n=12289;for(let r of t)n^=pn(un(r),un(e[r]));return mn(n)},vn=e=>bee(e,zt(e)),yn=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return mn(r)},bn=e=>{let t=6151;for(let n of e)t=pn(t,un(n));return mn(t)},xee=/*#__PURE__*/ yn(/*#__PURE__*/ _n(`Map`),([e,t])=>pn(un(e),un(t))),xn=/*#__PURE__*/ _n(`Set`),Sn=/*#__PURE__*/ yn(xn,e=>pn(xn,un(e))),Cn=/*#__PURE__*/ new WeakMap,wn=/*#__PURE__*/ new WeakMap,Tn=/*#__PURE__*/ new WeakSet,En=`~effect/Equal`;function Dn(){return arguments.length===1?e=>On(e,arguments[0]):On(arguments[0],arguments[1])}function On(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;return n===typeof t?n===`number`&&e!==e&&t!==t?!0:n!==`object`&&n!==`function`||Bt.has(e)||Bt.has(t)?!1:See(e,t):!1}function See(e,t){let n=An.length;for(let r=n;r-->0;)if(An[r]===e&&jn[r]===t)return!0;if(n)return kn(e,t);let r=Mn.get(e);r||Mn.set(e,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=kn(e,t)),i}function kn(e,t){An.push(e),jn.push(t);try{return Nn(e,t)}finally{An.pop(),jn.pop()}}const An=[],jn=[],Mn=/*#__PURE__*/ new WeakMap;function Nn(e,t){if(un(e)!==un(t))return!1;if(e instanceof Date){if(!(t instanceof Date))return!1;let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=Rn(e);if(n!==Rn(t)||typeof e==`function`&&!n)return!1;if(n)return e[En](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Cee(e,t);if(ArrayBuffer.isView(e)){let n=e instanceof DataView;return!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||n!==t instanceof DataView?!1:n?Pn(Vt(e),Vt(t)):Pn(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:Fn(e,t,In,Ln):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:Fn(e,t,un,On):wee(e,t)}function Cee(e,t){for(let n=0;n<e.length;n++)if(!On(e[n],t[n]))return!1;return!0}function Pn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function wee(e,t){let n=zt(e),r=zt(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!On(e[i],t[i]))return!1;return!0}function Fn(e,t,n,r){let i=/* @__PURE__ */ new Map,a=0;for(let e of t){let t=n(e),r=i.get(t);r?r.push(e):i.set(t,[e]),a++}outer:for(let t of e){let e=i.get(n(t));if(e){for(let n=0;n<e.length;n++)if(r(t,e[n])){e[n]=e[e.length-1],e.pop(),a--;continue outer}}return!1}return a===0}const In=e=>un(e[0]),Ln=(e,t)=>On(e[0],t[0])&&On(e[1],t[1]),Rn=e=>N(e,En),zn=()=>Dn,Bn=/*#__PURE__*/ Symbol.for(`~effect/Redactable`),Vn=e=>N(e,Bn);function Hn(e){return Vn(e)?Un(e):e}function Un(e){return e[Bn](globalThis[`~effect/Fiber/currentFiber`]?.context??Kn)}const Wn=`~effect/Fiber/currentFiber`,Gn=/*#__PURE__*/ new Map,Kn={"~effect/Context":{},base:Gn,depth:0,mapUnsafe:Gn,pipe(){return Ot(this,arguments)}};function qn(e,t){let n=t?.space??0,r=/* @__PURE__ */ new WeakSet,i=n?typeof n==`number`?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,t=0){try{return l(e,t)}catch{return(typeof e==`object`&&e||typeof e==`function`)&&r.delete(e),`[inspection threw]`}}function l(e,n=0){if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||e==null||typeof e==`boolean`||typeof e==`symbol`)return String(e);if(typeof e==`bigint`)return String(e)+`n`;if(typeof e==`object`||typeof e==`function`){if(r.has(e))return Jn;r.add(e);let l;if(Bn in e)l=c(Un(e),n);else if(Array.isArray(e))l=!i||e.length<=1?`[${e.map(e=>c(e,n)).join(`,`)}]`:`[\n${a(n+1)}${e.map(e=>c(e,n+1)).join(`,
2
+ `+a(n+1))}\n${a(n)}]`;else if(e instanceof Date)l=Zn(e);else if(!t?.ignoreToString&&N(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Qn(e);l=e instanceof Error&&e.cause!==void 0?`${t} (cause: ${c(e.cause,n)})`:t}else if(Symbol.iterator in e)l=`${e.constructor.name}(${c(Array.from(e),n)})`;else{let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${Yn(t)}:${c($n(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Yn(t)}: ${c($n(e,t),n+1)}`).join(`,
3
+ `)}\n${a(n)}}`;l=o(e,r)}}return r.delete(e),l}return String(e)}return c(e,0)}const Jn=`[Circular]`;function Yn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function Xn(e){return e.map(e=>`[${Yn(e)}]`).join(``)}function Zn(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Qn(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function $n(e,t){try{return e[t]}catch{return`[property access threw]`}}function er(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=N(r,Bn)?Hn(r):Hn(t);if(typeof i==`bigint`)return qn(i);if(typeof i!=`object`||!i)return i;let a=i instanceof Error&&!N(i,`toJSON`)?{...i,name:i.name,message:i.message}:i;for(;n.length>0&&n[n.length-1]!==this;)n.pop();if(n.includes(i))return;if(n.push(i),a!==i&&n.push(a),!tr(a)||nr(a))return a;let o=new Proxy(a,{get(e,t){let n=Reflect.get(e,t,e);return Object.getOwnPropertyDescriptor(e,t)?.get===void 0?n:Hn(n)}});return n.push(o),o},t?.space)??`null`}function tr(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function nr(e){for(let t of[Number.prototype.valueOf,Boolean.prototype.valueOf,String.prototype.valueOf])try{return Reflect.apply(t,e,[]),!0}catch{}return!1}const rr=/*#__PURE__*/ Symbol.for(`nodejs.util.inspect.custom`),ir=e=>{try{return e=Hn(e),N(e,`toJSON`)&&Jt(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map(ir):e}catch{return`[toJSON threw]`}},Tee=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?er(e,{space:t}):qn(e,{space:t})}catch{return String(e)}},ar={toJSON(){return ir(this)},[rr](){return this.toJSON()},toString(){return qn(this.toJSON())}};var or=class{[rr](){return this.toJSON()}toString(){return qn(this.toJSON())}};const Eee=/*#__PURE__*/ (()=>{let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.hasOwn(e,`writable`)?e.writable===!0:e.set!==void 0})(),sr=()=>Error.stackTraceLimit,cr=e=>{Eee&&(Error.stackTraceLimit=e)};var lr=class{constructor(e){this.value=e,this.done=!1}next(e){return this.done?(this.value=e,this):(this.done=!0,{value:this.value,done:!1})}};const ur=/*#__PURE__*/ (()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=sr();if(r===0)return n[e];cr(2);let i=t[e](()=>/* @__PURE__ */ Error());return cr(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function dr(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function fr(e,t){for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&dr(e,n,t[n])}const pr=`~effect/Effect`,mr=`~effect/Exit`,Dee={_A:M,_E:M,_R:M},hr=`${pr}/identifier`,gr=`${pr}/args`,_r=`${pr}/evaluate`,vr=`${pr}/successCont`,yr=`${pr}/failureCont`,br=`${pr}/ensureCont`,xr=/*#__PURE__*/ Symbol.for(`effect/Effect/Yield`),Sr={pipe(){return Ot(this,arguments)},toJSON(){return{...this}},toString(){return qn(this.toJSON(),{ignoreToString:!0,space:2})},[rr](){return this.toJSON()}},Oee={[pr]:Dee,...Sr,[Symbol.iterator](){return new lr(this)},toJSON(){return{_id:`Effect`,op:this[hr],...`~effect/Effect/args`in this?{args:this[gr]}:void 0}}},Cr=e=>N(e,pr),wr=e=>N(e,mr),Tr=`~effect/Cause`,Er=`~effect/Cause/Reason`,Dr=e=>N(e,Tr),Or=e=>N(e,Er);var kr=class{constructor(e){this[Tr]=Tr,this.reasons=e}pipe(){return Ot(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${qn(this.reasons)})`}[rr](){return this.toJSON()}[En](e){return Dr(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Dn(t,e.reasons[n]))}[ln](){return bn(this.reasons)}};const Ar=/*#__PURE__*/ new WeakMap;var jr=class{[Er];annotations;_tag;constructor(e,t,n){if(this[Er]=Er,this._tag=e,t!==Mr&&typeof n==`object`&&n&&t.size>0){let e=Ar.get(n);e&&(t=new Map([...e,...t])),Ar.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((e,r)=>{t?.overwrite!==!0&&n.has(r)||n.set(r,e)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return Ot(this,arguments)}toString(){return qn(this)}[rr](){return this.toString()}};const Mr=/*#__PURE__*/ new Map;var Nr=class extends jr{constructor(e,t=Mr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${qn(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[En](e){return Ur(e)&&Dn(this.error,e.error)&&Dn(this.annotations,e.annotations)}[ln](){return pn(_n(this._tag))(pn(un(this.error))(un(this.annotations)))}};const Pr=e=>new kr(e),Fr=(e,t)=>{let n=/* @__PURE__ */ new Map,r=[];for(let i of e.concat(t)){let e=un(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>Dn(e,i)))continue;else t.push(i);r.push(i)}return r},Ir=/*#__PURE__*/ j(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new kr(Fr(e.reasons,t.reasons));return Dn(e,n)?e:n}),Lr=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)Gr(e)&&!n.some(t=>Gr(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new kr(n)},Rr=/*#__PURE__*/ new kr([]),zr=e=>new kr([new Nr(e)]);var Br=class extends jr{constructor(e,t=Mr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${qn(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[En](e){return Wr(e)&&Dn(this.defect,e.defect)&&Dn(this.annotations,e.annotations)}[ln](){return pn(_n(this._tag))(pn(un(this.defect))(un(this.annotations)))}};const Vr=e=>new kr([new Br(e)]),Hr=/*#__PURE__*/ j(e=>Dr(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new kr(e.reasons.map(e=>e.annotate(t,n)))),Ur=e=>e._tag===`Fail`,Wr=e=>e._tag===`Die`,Gr=e=>e._tag===`Interrupt`;function Kr(e){return ti(`Effect.evaluate: Not implemented`)}const qr=e=>({...Oee,[hr]:e.op,[_r]:e[`~effect/Effect/evaluate`]??Kr,[vr]:e[vr],[yr]:e[yr],[br]:e[br]}),Jr=e=>{let t=qr(e),n=function(e){this[gr]=e};return n.prototype=t,function(e){return new n(e)}},Yr=e=>{let t={[mr]:mr,_tag:e.op,get[e.prop](){return this[gr]},...qr(e),toString(){return`${e.op}(${qn(this[gr])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[gr]}},[En](e){return wr(e)&&e._tag===this._tag&&Dn(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[ln](){return pn(_n(e.op),un(this[gr]))}},n=function(e){this[gr]=e};return n.prototype=t,function(e){return new n(e)}},Xr=/*#__PURE__*/ Yr({op:`Success`,prop:`value`,[_r](e){let t=e.getCont(vr);return t?t[vr](this[gr],e,this):e.yieldWith(this)}}),Zr={key:`effect/Cause/StackTrace`},Qr={key:`effect/Cause/InterruptorStackTrace`},$r=/*#__PURE__*/ Yr({op:`Failure`,prop:`cause`,[_r](e){let t=this[gr],n=!1;e.cache.stackFrame&&(t=Hr(t,{mapUnsafe:/* @__PURE__ */ new Map([[Zr.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(yr),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=hr in r,r=e.getCont(yr);a&&(t=Pr(t.reasons.filter(e=>e._tag!==`Fail`))),t=Lr(t,i),n=!0}return r?r[yr](t,e,n?void 0:this):e.yieldWith(n?$r(t):this)}}),ei=e=>$r(zr(e)),ti=e=>$r(Vr(e)),ni=/*#__PURE__*/ Jr({op:`WithFiber`,[_r](e){return this[gr](e)}}),ri=/*#__PURE__*/ function(){class e extends globalThis.Error{}let t=/*#__PURE__*/ qr({op:`YieldableError`,[_r](){return ei(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),ii=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Symbol.for(`effect/Data/Error/plainArgs`);return class extends ri{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(fr(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),ai=e=>{class t extends ii{_tag=e}return t.prototype.name=e,t},oi=`~effect/Cause/NoSuchElementError`,si=e=>N(e,oi);var ci=class extends (/*#__PURE__*/ ai(`NoSuchElementError`)){[oi]=oi;constructor(e){super({message:e})}};const li=`~effect/Cause/Done`,kee=e=>N(e,li),ui={[li]:li,_tag:`Done`,value:void 0},di=e=>e===void 0?ui:{[li]:li,_tag:`Done`,value:e},Aee=/*#__PURE__*/ ei(ui),jee=e=>e===void 0?Aee:ei(di(e)),fi=e=>qr({op:e.label,[_r]:e.evaluate}),pi=e=>(t,n)=>t===n||e(t,n),Mee=(e,t)=>e===t,mi=()=>Mee;function Nee(e){return pi((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e[r](t[r],n[r]))return!1;return!0})}function Pee(e){return pi((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0})}const hi=`~effect/Option`,gi={[hi]:{_A:e=>e},...Sr,[Symbol.iterator](){return new lr(this)}},Fee=/*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(gi),{_tag:`Some`,_op:`Some`,[En](e){return _i(e)&&yi(e)&&Dn(this.value,e.value)},[ln](){return pn(un(this._tag))(un(this.value))},toString(){return`some(${qn(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:ir(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Iee=/*#__PURE__*/ un(`None`),Lee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(gi),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[En](e){return _i(e)&&vi(e)},[ln](){return Iee},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),_i=e=>N(e,hi),vi=e=>e._tag===`None`,yi=e=>e._tag===`Some`,Ree=/*#__PURE__*/ Object.create(Lee),bi=function(e){this.value=e};bi.prototype=Fee;const zee=e=>new bi(e),xi=`~effect/Result`,Si={[xi]:{
4
+ /* v8 ignore next 2 */
5
+ _A:e=>e,_E:e=>e},...Sr,[Symbol.iterator](){return new lr(this)}},Bee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(Si),{_tag:`Success`,_op:`Success`,[En](e){return Ci(e)&&Ti(e)&&Dn(this.success,e.success)},[ln](){return pn(un(this._tag))(un(this.success))},toString(){return`success(${qn(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:ir(this.success)}}}),Vee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(Si),{_tag:`Failure`,_op:`Failure`,[En](e){return Ci(e)&&wi(e)&&Dn(this.failure,e.failure)},[ln](){return pn(un(this._tag))(un(this.failure))},toString(){return`failure(${qn(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:ir(this.failure)}}}),Ci=e=>N(e,xi),wi=e=>e._tag===`Failure`,Ti=e=>e._tag===`Success`,Ei=function(e){this.failure=e};Ei.prototype=Vee;const Hee=e=>new Ei(e),Di=function(e){this.success=e};Di.prototype=Bee;const Uee=e=>new Di(e);function Oi(e){return(t,n)=>t===n?0:e(t,n)}const Wee=/*#__PURE__*/ Oi((e,t)=>e<t?-1:1),ki=/*#__PURE__*/ Oi((e,t)=>globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t)?0:globalThis.Number.isNaN(e)?-1:globalThis.Number.isNaN(t)?1:e<t?-1:1),Gee=/*#__PURE__*/ j(2,(e,t)=>Oi((n,r)=>e(t(n),t(r)))),Kee=e=>j(2,(t,n)=>e(t,n)===-1),Ai=e=>j(2,(t,n)=>e(t,n)===1),ji=e=>j(2,(t,n)=>e(t,n)!==1),Mi=e=>j(2,(t,n)=>e(t,n)!==-1),Ni=()=>Ree,Pi=zee,Fi=vi,Ii=yi,Li=/*#__PURE__*/ j(2,(e,{onNone:t,onSome:n})=>Fi(e)?t():n(e.value)),Ri=/*#__PURE__*/ j(2,(e,t)=>Fi(e)?t():e.value),qee=/*#__PURE__*/ j(2,(e,t)=>Fi(e)?t():e),zi=e=>e==null?Ni():Pi(e),Bi=e=>e===void 0?Ni():Pi(e),Vi=/*#__PURE__*/ Ri(Pt),Hi=e=>(...t)=>{try{return Pi(e(...t))}catch{return Ni()}},Ui=/*#__PURE__*/ j(2,(e,t)=>Fi(e)?Ni():Pi(t(e.value))),Wi=/*#__PURE__*/ j(2,(e,t)=>Fi(e)?Ni():t(e.value)),Gi=/*#__PURE__*/ j(2,(e,t)=>Fi(e)?Ni():t(e.value)?Pi(e.value):Ni()),Ki=`~effect/Context/Service`,P=function(){function e(){}let t=e;Object.setPrototypeOf(t,qi);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[Yi]=Yi,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&Ji.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},qi={[Ki]:Ki,.../*#__PURE__*/ fi({label:`Service`,evaluate(e){return Xr(va(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return da(this,e)},use(e){return ni(t=>e(va(t.context,this)))},useSync(e){return ni(t=>Xr(e(va(t.context,this))))}},Ji=/*#__PURE__*/ new Set,Yi=`~effect/Context/Reference`,Xi=`~effect/Context`,Zi=(e,t,n,r)=>{let i=Object.create(ia);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Qi=(e,t)=>{t&&(Qi(e,t.parent),e.set(t.key,t.value))},$i=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Qi(t,e.overlay),e._flat=t},ea=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),ra(n)},ta=/*#__PURE__*/ Symbol(),na=(e,t)=>{let n=e;for(let e=n.overlay;e;e=e.parent)if(e.key===t)return e.value;let r=n.base.get(t);return r===void 0&&!n.base.has(t)?ta:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=8&&(n.base=$i(n),n.overlay=void 0,n.depth=0),r)},ra=e=>Zi(void 0,e,void 0,0),ia={get mapUnsafe(){return $i(this)},...Sr,[Xi]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[En](e){if(!oa(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[e,r]of t)if(!n.has(e)||!Dn(r,n.get(e)))return!1;return!0},[ln](){return gn(this.mapUnsafe.size)}},aa=(e,t)=>e.cacheRoot===t.cacheRoot,oa=e=>N(e,Xi),sa=e=>N(e,Ki),ca=e=>!!e[Yi],la=()=>ua,ua=/*#__PURE__*/ ra(/*#__PURE__*/ new Map),da=(e,t)=>ra(/* @__PURE__ */ new Map([[e.key,t]])),fa=/*#__PURE__*/ j(3,(e,t,n)=>pa(e,t.key,n)),pa=(e,t,n)=>{let r=e,i=Ji.has(t)?void 0:r.cacheRoot;if(r.depth>=8){let e=new Map(r._flat??r.base);return r._flat||Qi(e,r.overlay),e.set(t,n),Zi(i,e,void 0,0)}return Zi(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},ma=/*#__PURE__*/ j(3,(e,t,n)=>{let r=na(e,t.key);return r===ta?ca(t)?ba(t):n():r}),ha=/*#__PURE__*/ j(2,(e,t)=>ga(e,t.key)),ga=(e,t)=>{let n=na(e,t);return n===ta?void 0:n},_a=/*#__PURE__*/ j(2,(e,t)=>{let n=na(e,t.key);if(n===ta){if(ca(t))return ba(t);throw xa(t)}return n}),va=_a,ya=`~effect/Context/defaultValue`,ba=e=>ya in e?e[ya]:e[ya]=e.defaultValue(),xa=e=>{let t=/* @__PURE__ */ Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(t.stack){let e=t.stack.split(`
6
+ `);e.splice(1,3),t.stack=e.join(`
7
+ `)}return t},Sa=/*#__PURE__*/ j(2,(e,t)=>{let n=na(e,t.key);return n===ta?ca(t)?Pi(ba(t)):Ni():Pi(n)}),Ca=/*#__PURE__*/ j(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:ea(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),wa=(...e)=>{let t=/* @__PURE__ */ new Map;for(let n=0;n<e.length;n++)e[n].mapUnsafe.forEach((e,n)=>{t.set(n,e)});return ra(t)},Ta=(...e)=>t=>ea(t,t=>{for(let n=0;n<e.length;n++)t.delete(e[n].key)}),Ea=P,Da=e=>e.length>0,Oa=e=>e>0?Math.floor(e):0,ka=Uee,Aa=Hee,ja=e=>{if(Jt(e))try{return ka(e())}catch(e){return Aa(e)}try{return ka(e.try())}catch(t){return Aa(e.catch(t))}},Ma=Ci,Na=wi,Pa=Ti,Fa=/*#__PURE__*/ j(2,(e,t)=>Na(e)?Aa(t(e.failure)):e),Ia=/*#__PURE__*/ j(2,(e,t)=>Pa(e)?ka(t(e.success)):e),Jee=/*#__PURE__*/ j(2,(e,{onFailure:t,onSuccess:n})=>Na(e)?t(e.failure):n(e.success)),Yee=/*#__PURE__*/ (/* @__PURE__ */ j(2,(e,t)=>Na(e)?t(e.failure):e.success))(Pt),Xee=Nee,Zee=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},Qee=()=>({}),$ee=e=>Object.keys(e).length===0,ete=/*#__PURE__*/ j(2,(e,t)=>Object.hasOwn(e,t)),La=/*#__PURE__*/ j(2,(e,t)=>{let n={...e};for(let r of Ra(e))dr(n,r,t(e[r],r));return n}),tte=/*#__PURE__*/ j(2,(e,t)=>{let n=Qee();for(let r of Ra(e))t(e[r],r)&&dr(n,r,e[r]);return n}),Ra=e=>Object.keys(e),nte=/*#__PURE__*/ j(3,(e,t,n)=>({...e,[t]:n})),rte=e=>j(2,(t,n)=>{for(let r of Ra(t))if(!ete(n,r)||!e(t[r],n[r]))return!1;return!0}),ite=e=>{let t=rte(e);return(e,n)=>t(e,n)&&t(n,e)},za=globalThis.Array,Ba=e=>za.isArray(e)?e:za.from(e),Va=e=>za.isArray(e)?e:[e],Ha=/*#__PURE__*/ j(2,(e,t)=>[...e,t]);za.isArray;const Ua=Da,Wa=Da;function ate(e){let t=Number(e);return String(t)===e&&Number.isInteger(t)&&t>=0&&t<2**32-1}const ote=(e,t)=>Math.min(Oa(e),t),ste=/*#__PURE__*/ j(2,(e,t)=>{let n=Ba(e);return n.slice(0,ote(t,n.length))}),cte=e=>za.from(e).reverse(),lte=(e,t)=>{let n=un(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(Dn(e,t))return!1;return r.push(t),!0},Ga=()=>[],Ka=e=>[e],qa=/*#__PURE__*/ j(2,(e,t)=>e.map(t)),ute=Pee,dte=e=>{let t=Ba(e);if(t.length<2)return[...t];let n=/* @__PURE__ */ new Map,r=[];for(let e of t)lte(n,e)&&r.push(e);return r},Ja=`~effect/Duration`,Ya=/*#__PURE__*/ BigInt(0),Xa=/*#__PURE__*/ BigInt(1),fte=/*#__PURE__*/ BigInt(2),pte=/*#__PURE__*/ BigInt(10),Za=/*#__PURE__*/ BigInt(24),Qa=/*#__PURE__*/ BigInt(60),$a=/*#__PURE__*/ BigInt(1e3),eo=/*#__PURE__*/ BigInt(1e6),to=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),no=e=>Number.isInteger(e)?BigInt(e)*eo:to(e*1e6),ro=e=>co(Number.isFinite(e)?to(e):e),io=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=pte**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return mte(r?-o:o,a)},mte=(e,t)=>{let n=e<Ya?-e:e,r=n/t+(n%t*fte>=t?Xa:Ya);return e<Ya?-r:r},hte=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,ao=e=>{switch(typeof e){case`number`:return go(e);case`bigint`:return ho(e);case`string`:{if(e===`Infinity`)return po;if(e===`-Infinity`)return mo;let t=hte.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return ho(io(r,Xa));if(i===`micro`||i===`micros`)return ho(io(r,$a));let a=Number(r);switch(i){case`milli`:case`millis`:return go(a);case`second`:case`seconds`:return _o(a);case`minute`:case`minutes`:return vo(a);case`hour`:case`hours`:return Ste(a);case`day`:case`days`:return Cte(a);case`week`:case`weeks`:return wte(a)}break}case`object`:{if(e===null)break;if(Ja in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(Wt)?oo(e):Number.isNaN(e[0])||Number.isNaN(e[1])?fo:e[0]===-1/0||e[1]===-1/0?mo:e[0]===1/0||e[1]===1/0?po:ro(e[0]*1e9+e[1]);let t=e,n=0;return t.weeks&&(n+=t.weeks*6048e5),t.days&&(n+=t.days*864e5),t.hours&&(n+=t.hours*36e5),t.minutes&&(n+=t.minutes*6e4),t.seconds&&(n+=t.seconds*1e3),t.milliseconds&&(n+=t.milliseconds),!t.microseconds&&!t.nanoseconds?co(n):ro(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0))}}return oo(e)},oo=e=>{throw Error(`Invalid Input: ${e}`)},so={_tag:`Millis`,millis:0},gte={_tag:`Infinity`},_te={_tag:`NegativeInfinity`},vte={[Ja]:Ja,[ln](){switch(this.value._tag){case`Millis`:return un(no(this.value.millis));case`Nanos`:return un(this.value.nanos);default:return vn(this.value)}},[En](e){return yte(e)&&Ote(this,e)},toString(){switch(this.value._tag){case`Infinity`:return`Infinity`;case`NegativeInfinity`:return`-Infinity`;case`Nanos`:return`${this.value.nanos} nanos`;case`Millis`:return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case`Millis`:return{_id:`Duration`,_tag:`Millis`,millis:this.value.millis};case`Nanos`:return{_id:`Duration`,_tag:`Nanos`,nanos:String(this.value.nanos)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`};case`NegativeInfinity`:return{_id:`Duration`,_tag:`NegativeInfinity`}}},[rr](){return this.toJSON()},pipe(){return Ot(this,arguments)}},co=e=>{let t=Object.create(vte);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?so:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:no(e)}:e>0?gte:_te:e===Ya?so:{_tag:`Nanos`,nanos:e},t},yte=e=>N(e,Ja),lo=e=>e.value._tag!==`Infinity`&&e.value._tag!==`NegativeInfinity`,uo=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===Ya;case`Infinity`:case`NegativeInfinity`:return!1}},bte=e=>{switch(e.value._tag){case`Millis`:return e.value.millis<0;case`Nanos`:return e.value.nanos<Ya;case`NegativeInfinity`:return!0;case`Infinity`:return!1}},xte=e=>{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:return po;case`Millis`:return e.value.millis<0?co(-e.value.millis):e;case`Nanos`:return e.value.nanos<Ya?co(-e.value.nanos):e}},fo=/*#__PURE__*/ co(0),po=/*#__PURE__*/ co(1/0),mo=/*#__PURE__*/ co(-1/0),ho=e=>co(e),go=e=>co(e),_o=e=>co(e*1e3),vo=e=>co(e*6e4),Ste=e=>co(e*36e5),Cte=e=>co(e*864e5),wte=e=>co(e*6048e5),yo=e=>xo(ao(e),{onMillis:M,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),Tte=e=>xo(ao(e),{onMillis:e=>e/1e3,onNanos:e=>Number(e)/1e9,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),bo=e=>{let t=ao(e);switch(t.value._tag){case`Infinity`:case`NegativeInfinity`:throw Error(`Cannot convert infinite duration to nanos`);case`Nanos`:return t.value.nanos;case`Millis`:return no(t.value.millis)}},xo=/*#__PURE__*/ j(2,(e,t)=>{switch(e.value._tag){case`Millis`:return t.onMillis(e.value.millis);case`Nanos`:return t.onNanos(e.value.nanos);case`Infinity`:return t.onInfinity();case`NegativeInfinity`:return(t.onNegativeInfinity??t.onInfinity)()}}),Ete=/*#__PURE__*/ j(3,(e,t,n)=>e.value._tag===`Infinity`||e.value._tag===`NegativeInfinity`||t.value._tag===`Infinity`||t.value._tag===`NegativeInfinity`?n.onInfinity(e,t):e.value._tag===`Millis`?t.value._tag===`Millis`?n.onMillis(e.value.millis,t.value.millis):n.onNanos(bo(e),t.value.nanos):n.onNanos(e.value.nanos,bo(t))),Dte=(e,t)=>Ete(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Ote=/*#__PURE__*/ j(2,(e,t)=>Dte(e,t)),kte=e=>{if(e.value._tag===`Infinity`)return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};if(e.value._tag===`NegativeInfinity`)return{days:-1/0,hours:-1/0,minutes:-1/0,seconds:-1/0,millis:-1/0,nanos:-1/0};let t=bo(e),n=t<Ya,r=n?-t:t,i=r/eo,a=i/$a,o=a/Qa,s=o/Qa,c=s/Za,l=n?-1:1;return{days:l*Number(c),hours:l*Number(s%Za),minutes:l*Number(o%Qa),seconds:l*Number(a%Qa),millis:l*Number(i%$a),nanos:l*Number(r%eo)}},So=e=>{if(e.value._tag===`Infinity`)return`Infinity`;if(e.value._tag===`NegativeInfinity`)return`-Infinity`;if(uo(e))return`0`;if(bte(e))return`-`+So(xte(e));let t=kte(e),n=[];return t.days!==0&&n.push(`${t.days}d`),t.hours!==0&&n.push(`${t.hours}h`),t.minutes!==0&&n.push(`${t.minutes}m`),t.seconds!==0&&n.push(`${t.seconds}s`),t.millis!==0&&n.push(`${t.millis}ms`),t.nanos!==0&&n.push(`${t.nanos}ns`),n.join(` `)},Co=/*#__PURE__*/ Ea(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new Eo}),wo=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Ate=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},To=e=>{try{return Ate(e)}catch{return wo(e)}};var jte=class{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,a=0;for(;a<r&&!(n[a][0]>t);a++)i=n[a];i&&i[0]===t?i[1].push(e):a===r?n.push([t,[e]]):n.splice(a,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}},Eo=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?wo:To)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new Mte(this.setImmediate)}},Mte=class{tasks=/*#__PURE__*/ new jte;running=void 0;setImmediate;constructor(e=To){this.setImmediate=e}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running===void 0&&(this.running=this.setImmediate(this.afterScheduled))}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let e=0;e<n.length;e++)n[e]()}}flush(){for(;this.tasks.buckets.length>0;)this.running!==void 0&&(this.running(),this.running=void 0),this.runTasks()}};const Nte=/*#__PURE__*/ Ea(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Pte=/*#__PURE__*/ Ea(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),Do=class extends At{constructor(e){super(),e&&fr(this,e)}},Fte=e=>class extends Do{_tag=e},Oo=()=>new Proxy({},{get(e,t,n){return t===`$is`?on:t===`$match`?ko:e=>({...e,_tag:t})}});function ko(){if(arguments.length===1){let e=arguments[0];return function(t){return e[t._tag](t)}}let e=arguments[0];return arguments[1][e._tag](e)}const Ao=ii,jo=ai,Mo=`~effect/encoding/EncodingError`;var No=class extends (/*#__PURE__*/ jo(`EncodingError`)){[Mo]=Mo};const Po=e=>{switch(e){case 16:return Ro();case 32:return zo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Lo();return t}}},Fo=/*#__PURE__*/ Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),Io=()=>Math.random()*4294967296>>>0,Lo=()=>{let e=Io();return String.fromCharCode(Fo[e>>>28],Fo[e>>>24&15],Fo[e>>>20&15],Fo[e>>>16&15],Fo[e>>>12&15],Fo[e>>>8&15],Fo[e>>>4&15],Fo[e&15])},Ro=()=>{let e=Io(),t=Io();return String.fromCharCode(Fo[e>>>28],Fo[e>>>24&15],Fo[e>>>20&15],Fo[e>>>16&15],Fo[e>>>12&15],Fo[e>>>8&15],Fo[e>>>4&15],Fo[e&15],Fo[t>>>28],Fo[t>>>24&15],Fo[t>>>20&15],Fo[t>>>16&15],Fo[t>>>12&15],Fo[t>>>8&15],Fo[t>>>4&15],Fo[t&15])},zo=()=>{let e=Io(),t=Io(),n=Io(),r=Io();return String.fromCharCode(Fo[e>>>28],Fo[e>>>24&15],Fo[e>>>20&15],Fo[e>>>16&15],Fo[e>>>12&15],Fo[e>>>8&15],Fo[e>>>4&15],Fo[e&15],Fo[t>>>28],Fo[t>>>24&15],Fo[t>>>20&15],Fo[t>>>16&15],Fo[t>>>12&15],Fo[t>>>8&15],Fo[t>>>4&15],Fo[t&15],Fo[n>>>28],Fo[n>>>24&15],Fo[n>>>20&15],Fo[n>>>16&15],Fo[n>>>12&15],Fo[n>>>8&15],Fo[n>>>4&15],Fo[n&15],Fo[r>>>28],Fo[r>>>24&15],Fo[r>>>20&15],Fo[r>>>16&15],Fo[r>>>12&15],Fo[r>>>8&15],Fo[r>>>4&15],Fo[r&15])},Bo=`effect/Tracer/ParentSpan`;var Vo=class extends (/*#__PURE__*/ P()(Bo,{fiberCached:!0})){};const Ho=e=>e,Uo=e=>({_tag:`ExternalSpan`,spanId:e.spanId,traceId:e.traceId,sampled:e.sampled??!0,annotations:e.annotations??la()}),Wo=/*#__PURE__*/ Ea(`effect/Tracer/DisablePropagation`,{defaultValue:Nt}),Go=/*#__PURE__*/ Ea(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),Ko=/*#__PURE__*/ Ea(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),qo=`effect/Tracer`,Jo=/*#__PURE__*/ Ea(qo,{fiberCached:!0,defaultValue:()=>Yo}),Yo=/*#__PURE__*/ Ho({span:e=>new Xo(e)});var Xo=class{_tag=`Span`;sampled;name;parent;annotations;links;startTime;kind;status;_traceId=void 0;_spanId=void 0;_attributes=void 0;_events=void 0;constructor(e){this.name=e.name,this.parent=e.parent,this.annotations=e.annotations,this.links=e.links,this.startTime=e.startTime,this.kind=e.kind,this.sampled=e.sampled,this.status={_tag:`Started`,startTime:e.startTime}}get traceId(){return this._traceId??=Vi(this.parent)?.traceId??Po(32)}get spanId(){return this._spanId??=Po(16)}get attributes(){return this._attributes??=/* @__PURE__ */ new Map}get events(){return this._events??=[]}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}};const Zo=/*#__PURE__*/ Ea(`effect/ErrorReporter/CurrentErrorReporters`,{defaultValue:()=>/* @__PURE__ */ new Set}),Qo=/*#__PURE__*/ Ea(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:Pt}),$o=/*#__PURE__*/ Ea(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:Mt}),es=/*#__PURE__*/ Ea(`effect/References/TracerTimingEnabled`,{defaultValue:Mt}),ts=/*#__PURE__*/ Ea(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),ns=/*#__PURE__*/ Ea(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),rs=/*#__PURE__*/ Ea(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),is=/*#__PURE__*/ Ea(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),as=/*#__PURE__*/ Ea(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),os=/*#__PURE__*/ Ea(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),ss=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=sr();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};cr(3);let n=/* @__PURE__ */ Error();return cr(t),{...e,captureStackTrace:ls(()=>n.stack)}},cs=e=>t=>{let n;return()=>{if(n!==void 0)return n;let r=t();if(!r)return;let i=r.split(`
8
+ `);if(i[e]!==void 0)return n=i[e].trim(),n}},ls=/*#__PURE__*/ cs(3);var us=class extends jr{constructor(e,t=Mr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[En](e){return Gr(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[ln](){return _n(`${this._tag}:${this.fiberId}`)}};const ds=e=>new us(e),fs=e=>new kr([new us(e)]),ps=e=>{let t=e.reasons.find(Ur);return t?ka(t):Aa(e)},ms=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return ka(n.error)}return Aa(e)},hs=e=>e.reasons.some(Wr),gs=e=>{let t=e.reasons.find(Wr);return t?ka(t.defect):Aa(e)},_s=e=>e.reasons.some(Gr),vs=e=>{let t;for(let n=0;n<e.reasons.length;n++){let r=e.reasons[n];r._tag===`Interrupt`&&(t??=/* @__PURE__ */ new Set,r.fiberId!==void 0&&t.add(r.fiberId))}return t?ka(t):Aa(e)},ys=e=>{let t=vs(e);return Na(t)?bs:t.success},bs=/*#__PURE__*/ new Set,xs=e=>e.reasons.length>0&&e.reasons.every(Gr),Ss=e=>ra(e.annotations),Cs=/*#__PURE__*/ j(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>Ur(e)?(n=!0,new Nr(t(e.error),e.annotations)):e);return n?Pr(r):e}),ws=e=>{let t;for(let n of e.reasons){if(n._tag===`Fail`)return n.error;n._tag===`Die`&&(t??=n)}return t===void 0?e.reasons.length>0?new globalThis.Error(`All fibers interrupted without error`):new globalThis.Error(`Empty cause`):t.defect},Ts=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=sr();i!==0&&cr(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(Es(i._tag===`Die`?i.defect:i.error,i.annotations,t));if(n.length===0){let e=/* @__PURE__ */ Error(`The fiber was interrupted by:`);e.name=`InterruptCause`,e.stack=js(e,r);let i=new globalThis.Error(`All fibers interrupted without error`,{cause:e});i.name=`InterruptError`,i.stack=`${i.name}: ${i.message}`,n.push(Es(i,r[0].annotations,t))}}finally{i!==0&&cr(i)}return n},Es=(e,t,n)=>{let r=typeof e,i;if(e&&r===`object`){if(i=new globalThis.Error(Ds(e),{cause:e.cause?Es(e.cause):void 0}),typeof e.name==`string`&&(i.name=e.name),typeof e.stack==`string`)i.stack=ks(e.stack,i,t);else{let e=`${i.name}: ${i.message}`;i.stack=t?As(e,t):e}n?.includeCauseInStack&&(i.stack=Ps(i));for(let t of Object.keys(e))t in i||(i[t]=e[t])}else{i=new globalThis.Error(e?r===`string`?e:er(e):`Unknown error: ${e}`);let n=`${i.name}: ${i.message}`;i.stack=t?As(n,t):n}return i},Ds=e=>{if(typeof e.message==`string`)return e.message;if(typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return er(e)},Os=/\((.*)\)/g,ks=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
9
+ `),a=[r];for(let e=1;e<i.length&&!/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[e]);e++)a.push(i[e]);return n?As(a.join(`
10
+ `),n):a.join(`
11
+ `)},As=(e,t)=>{let n=t?.get(Zr.key);return n&&(e=`${e}\n${Ms(n)}`),e},js=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let e of t){let t=e.fiberId===void 0?`unknown`:`#${e.fiberId}`,r=e.annotations.get(Qr.key);n.push(` at fiber (${t})`),r&&n.push(Ms(r))}return n.join(`
12
+ `)},Ms=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Os),i=!1;for(let[,e]of r)i=!0,t.push(` at ${n.name} (${e})`);i||t.push(` at ${n.name} (${e.replace(/^at /,``)})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
13
+ `)},Ns=e=>Ts(e).map(Ps).join(`
14
+ `),Ps=e=>e.cause?`${e.stack} {\n${Fs(e.cause,` `)}\n}`:e.stack,Fs=(e,t)=>{let n=e.stack.split(`
15
+ `),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${Fs(e.cause,`${t} `)}\n${t}}`),r},Is=`~effect/Fiber`,Ls={_A:M,_E:M},Rs={id:0},zs=/*#__PURE__*/ (()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),Bs=()=>zs===void 0?void 0:new zs(`effect/Fiber`),Vs=()=>globalThis[Wn];var Hs=class{constructor(e,t=!0){this.setContext(e),this.id=++Rs.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this._asyncContext=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[Is](){return Ls}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return va(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Ft):(this._observers===void 0?this._observers=[e]:this._observers.push(e),()=>this.removeObserver(e))}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=fs(e);this.cache.stackFrame&&(n=Hr(n,da(Zr,this.cache.stackFrame))),t&&(n=Hr(n,t)),this._interruptedCause=this._interruptedCause?Lr(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(nc(this._interruptedCause)))}pollUnsafe(){return this._exit}evaluate(e){if(this._exit)return;if(this._asyncContext!==void 0){let t=this._asyncContext;return this._asyncContext=void 0,t.runInAsyncScope(this.evaluate,this,e)}if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===xr){this._asyncContext=Bs();return}let n=Ks.interruptChildren&&Ks.interruptChildren(this);if(n!==void 0)return this.evaluate(Rc(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent&&=(this._parent._children?.delete(this),void 0),this._observers!==void 0){let e=this._observers;this._observers=void 0;for(let n=0;n<e.length;n++)e[n](t)}this._stack.length=0,this._children=void 0,this.context=la()}runLoop(e){let t=globalThis[Wn];globalThis[Wn]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{for(;;)try{this._deferredInterrupt&&(this._deferredInterrupt=!1,i=nc(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=Rc(sc,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[_r](this),i===xr){let e=this._yielded;if(`~effect/Exit`in e)return this._deferredInterrupt=!1,this._yielded=void 0,e;if(this._deferredInterrupt){this._yielded=void 0,e();continue}return xr}}catch(e){if(!N(i,`~effect/Effect/evaluate`))return ti(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=ti(e)}}finally{this._running=n,globalThis[Wn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Ws;for(;;){let t=this._stack.pop();if(!t)return;let n=t[br];if(n!==void 0){let r=n.call(t,this);if(r)return r[e]=r,r}if(t[e])return t}}succeedWith(e){if(!(++this.currentOpCount&Gs-1))return Xr(e);let t=this.getCont(vr);return t?t[vr](e,this):this.yieldWith(Xr(e))}yieldWith(e){return this._yielded=e,xr}children(){return this._children??=/* @__PURE__ */ new Set}pipe(){return Ot(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&aa(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Us(e);this.cache?.scheduler!==r.scheduler&&(this._dispatcher=void 0),this.cache=r}get currentSpanLocal(){let e=this.cache.span;return e?._tag===`Span`?e:void 0}};const Us=e=>{let t=ga(e,qo);return{scheduler:va(e,Co),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:va(e,$o),span:ga(e,Bo),logLevel:va(e,is),minimumLogLevel:va(e,as),stackFrame:va(e,Qo),runtimeMetrics:ga(e,`effect/Metric/FiberRuntimeMetrics`),maxOpsBeforeYield:va(e,Nte),preventYield:va(e,Pte)}},Ws={[vr](e,t){return nc(t._interruptedCause)},[yr](e,t){return nc(t._interruptedCause)}},Gs=32,Ks={interruptChildren:void 0},qs=e=>{if(!e.cache.stackFrame)return;let t=/* @__PURE__ */ new Map;return t.set(Qr.key,e.cache.stackFrame),ra(t)},Js=e=>{if(e._children!==void 0&&e._children.size!==0)return ec(e._children)},Ys=e=>{let t=e;return t._exit?tc(t._exit):vc(n=>t._exit?n(tc(t._exit)):ic(e.addObserver(e=>n(tc(e)))))},Xs=e=>vc(t=>{let n=e[Symbol.iterator](),r=[],i;function a(){let e=n.next();for(;!e.done;)if(e.value._exit)r.push(e.value._exit),e=n.next();else{i=e.value.addObserver(e=>{r.push(e),a()});return}t(tc(r))}return a(),ic(()=>i?.())}),Zs=e=>{let t=e;return t._exit?t._exit:vc(n=>t._exit?n(t._exit):ic(e.addObserver(n)))},Qs=e=>ni(t=>$s(e,t.id)),$s=/*#__PURE__*/ j(e=>N(e[0],Is),(e,t,n)=>ni(r=>{let i=qs(r);return i=i&&n?Ca(i,n):i??n,e.interruptUnsafe(t,i),Ic(Ys(e))})),ec=e=>ni(t=>{let n=qs(t),r=Ga();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Ic(Xs(r))}),tc=Xr,nc=$r,rc=ei,ic=/*#__PURE__*/ Jr({op:`Sync`,[_r](e){let t=this[gr](),n=e.getCont(vr);return n?n[vr](t,e):e.yieldWith(Xr(t))}}),ac=/*#__PURE__*/ Jr({op:`Suspend`,[_r](e){return this[gr]()}}),oc=/*#__PURE__*/ Jee({onFailure:rc,onSuccess:tc}),sc=/*#__PURE__*/ (/* @__PURE__ */ Jr({op:`Yield`,[_r](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Wc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}}))(0),cc=/*#__PURE__*/ tc(/*#__PURE__*/ Ni()),lc=e=>ac(()=>nc(e())),uc=e=>ti(e),dc=e=>ac(()=>rc(e())),fc=/*#__PURE__*/ tc(void 0),pc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Hu(e,`An error occurred in Effect.try`):e.catch;return ac(()=>{try{return tc(t())}catch(e){return rc(n(e))}})},mc=e=>_c(function(t,n){e(n).then(e=>t(tc(e)),e=>t(uc(e)))},e.length!==0),hc=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new Hu(e,`An error occurred in Effect.tryPromise`):e.catch;return _c(function(e,r){let i=e=>ac(()=>{try{return rc(ur(()=>n(e)))}catch(e){return uc(e)}});try{t(r).then(t=>e(tc(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},gc=e=>ni(t=>e(t.id)),_c=/*#__PURE__*/ function(){let e=/*#__PURE__*/ qr({op:`Async`,[_r](e){let t=!1,n=!1,r=this.withSignal?new AbortController:void 0,i=this.register.call(e.cache.scheduler,r=>{t||(t=!0,n?e.evaluate(r):n=r)},r?.signal);return n===!1?(n=!0,e._yielded=()=>{t=!0},r===void 0&&i===void 0||e._stack.push(Ite(()=>(t=!0,r?.abort(),i??Wc))),xr):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Ite=/*#__PURE__*/ Jr({op:`AsyncFinalizer`,[br](e){e.interruptible&&(e.interruptible=!1,e._stack.push(Ul))},[yr](e,t){return _s(e)?Rc(_l($r(e),this[gr]()),()=>nc(e)):nc(e)}}),vc=e=>_c(e,e.length>=2),yc=/*#__PURE__*/ vc(Ft),Lte=(...e)=>{if(e.length===1){let t=e[0];return ac(()=>Tc(t()))}let[t,n]=e;return ac(()=>Tc(n.call(t.self)))},bc=(e,...t)=>{let n=t.length===0?function(){return ac(()=>Tc(e.apply(this,arguments)))}:function(){let n=ac(()=>Tc(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return xc(e.length,n)},xc=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Sc=/*#__PURE__*/ cs(2),Rte=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=sr(),i;return r!==0&&(cr(2),i=new globalThis.Error,cr(r)),e?(r,...a)=>Cc(t,r,i,a,e,n):Cc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},Cc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?Sc(()=>n.stack):Pt;return xc(o.length,function(...t){let n=ac(()=>{let e=o.apply(this,arguments);return Cr(e)?e:Tc(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!Cr(n))return n;let l=sr(),u;return l!==0&&(cr(2),u=new globalThis.Error,cr(l)),qc(i?wu(e,a,e=>Tu(n,e)):n,Qo,t=>({name:e,stack:u?Sc(()=>u.stack):Pt,parent:{name:s,stack:c,parent:t}}))})},zte=(e,...t)=>xc(e.length,t.length===0?function(){return wc(()=>e.apply(this,arguments))}:function(){let n=wc(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),wc=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return tc(r.value);let i=r.value;if(i&&i._tag===`Success`)n=i.value;else{if(i&&i._tag===`Failure`)return r.value;{let n=!0;return ac(()=>n?(n=!1,Rc(r.value,e=>Tc(t,e))):ac(()=>Tc(e())))}}}}catch(e){return uc(e)}},Tc=/*#__PURE__*/ function(){let e=/*#__PURE__*/ qr({op:`Iterator`,[vr](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return tc(r.value);if(!zc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[_r](e){return this[vr](this.initial,e)}}),t=function(e,t){this.iterator=e,this.initial=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),Ec=/*#__PURE__*/ j(2,(e,t)=>new Oc(e,kc,tc(t))),Dc=function(e){return e._stack.push(this),this[gr]},Bte=/*#__PURE__*/ qr({op:`OnSuccess`,[_r]:Dc}),Oc=function(e,t,n){this[gr]=e,this[vr]=t,this.payload=n};Oc.prototype=Bte;const kc=function(){return this.payload},Ac=function(e,t){return t.succeedWith(this.payload)},jc=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ sr();if(e===0)return!1;let t=`~effect/Effect/stackProbe`,n={[t]:function(){return/* @__PURE__ */ Error()}};cr(1);let r=/*#__PURE__*/ n[t]();return cr(e),r.stack?.includes(`[as `+t+`]`)===!0})(),Vte=function(e,t){let n=this.payload;return t.succeedWith(jc?n(e):ur(()=>n(e)))},Mc=function(e){let t=this.payload;return t(e)},Hte=function(e){let t=this.payload;return new Oc(t(e),Ac,e)},Ute=function(e){return new Oc(this.payload,Ac,e)},Nc=e=>Bc(e,Pi),Pc=/*#__PURE__*/ j(2,(e,t)=>new Oc(e,Cr(t)?kc:Mc,t)),Fc=/*#__PURE__*/ j(2,(e,t)=>new Oc(e,Cr(t)?Ute:Hte,t)),Ic=e=>new Oc(e,kc,Wc),Wte=(e,t)=>ni(n=>{let r=/* @__PURE__ */ new Set;return Nl(n,()=>r.size===0?void 0:ec(r)),vc(i=>{let a=Ba(e),o=a.length,s=0,c=!1,l=[],u=(e,r,a)=>{if(s++,e._tag===`Failure`){l.push(...e.cause.reasons),s>=o&&i(nc(Pr(l)));return}let u=!c;c=!0,i(e),u&&t?.onWinner&&t.onWinner({fiber:r,index:a,parentFiber:n})};for(let e=0;e<o;e++){let t=iu(n,a[e],!0,!0,!1);if(r.add(t),t.addObserver(n=>{r.delete(t),u(n,t,e)}),c)break}})}),Gte=(e,t)=>ni(n=>{let r=/* @__PURE__ */ new Set;return Nl(n,()=>r.size===0?void 0:ec(r)),vc(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=iu(n,s,!0,!0,!1);r.add(c),c.addObserver(o=>{r.delete(c);let s=!a;a=!0,i(o),s&&t?.onWinner&&t.onWinner({fiber:c,index:e,parentFiber:n})})}})}),Kte=/*#__PURE__*/ j(e=>Cr(e[1]),(e,t,n)=>Wte([e,t],n)),Lc=/*#__PURE__*/ j(e=>Cr(e[1]),(e,t,n)=>Gte([e,t],n)),Rc=/*#__PURE__*/ j(2,(e,t)=>new Oc(e,Mc,t)),qte=/*#__PURE__*/ j(2,(e,t)=>zc(e)?e._tag===`Success`?t.onSuccess(e.value):t.onFailure(e.cause):al(e,t)),zc=e=>e[mr]!==void 0,Jte=/*#__PURE__*/ j(2,(e,t)=>zc(e)?e._tag===`Success`?t(e.value):e:Rc(e,t)),Yte=e=>Rc(e,M),Bc=/*#__PURE__*/ j(2,(e,t)=>new Oc(e,Vte,t)),Xte=/*#__PURE__*/ j(2,(e,t)=>zc(e)?nne(e,t):Bc(e,t)),Zte=/*#__PURE__*/ j(2,(e,t)=>zc(e)?rne(e,t):rl(e,t)),Qte=/*#__PURE__*/ j(2,(e,t)=>zc(e)?ine(e,t):Cne(e,t)),$te=/*#__PURE__*/ j(2,(e,t)=>{if(zc(e)){if(e._tag===`Success`)return e;let n=ms(e.cause);return Na(n)?e:t(n.success)}return tl(e,t)}),Vc=e=>$r(fs(e)),Hc=e=>e._tag===`Success`,ene=e=>e._tag===`Failure`,tne=e=>e._tag===`Failure`?ka(e.cause):Aa(e),Uc=e=>e._tag===`Failure`&&_s(e.cause),Wc=/*#__PURE__*/ Xr(void 0),nne=/*#__PURE__*/ j(2,(e,t)=>e._tag===`Success`?Xr(t(e.value)):e),rne=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return e;let n=ms(e.cause);return Na(n)?e:ei(t(n.success))}),ine=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return Xr(t.onSuccess(e.value));let n=ms(e.cause);return Na(n)?e:ei(t.onFailure(n.success))}),ane=/*#__PURE__*/ j(2,(e,t)=>Hc(e)?t:e),Gc=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Wc:$r(Pr(t))},one=e=>e,sne=e=>ni(t=>tc(Sa(t.context,e))),Kc=/*#__PURE__*/ j(2,(e,t)=>ni(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),Nl(n,()=>{n.setContext(r)})),e})),qc=/*#__PURE__*/ j(3,(e,t,n)=>Kc(e,e=>{let r=_a(e,t),i=n(r);return r===i?e:fa(e,t,i)})),cne=()=>lne,lne=/*#__PURE__*/ ni(e=>tc(e.context)),Jc=e=>ni(t=>e(t.context)),une=/*#__PURE__*/ j(2,(e,t)=>Kc(e,jt(t))),Yc=/*#__PURE__*/ j(2,(e,t)=>zc(e)?e:Kc(e,Ca(t))),Xc=function(){return arguments.length===1?j(2,(e,t)=>Zc(e,arguments[0],t)):j(3,(e,t,n)=>Zc(e,t,n)).apply(this,arguments)},Zc=(e,t,n)=>Kc(e,fa(t,n)),dne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n)=>Kne(e,t,n?e=>rc(n(e)):()=>rc(new ci))),fne=/*#__PURE__*/ j(2,(e,t)=>Rc(t,t=>t?Nc(e):cc)),pne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t)=>Zl({while:Mt,body:jt(t?.disableYield?e:Rc(e,e=>sc)),step:Ft})),Qc=/*#__PURE__*/ j(2,(e,t)=>new $c(e,t.length===1?t:e=>t(e))),mne=/*#__PURE__*/ qr({op:`OnFailure`,[_r]:Dc}),$c=function(e,t){this[gr]=e,this[yr]=t};$c.prototype=mne;const hne=/*#__PURE__*/ j(3,(e,t,n)=>Qc(e,e=>t(e)?n(e):nc(e))),el=/*#__PURE__*/ j(3,(e,t,n)=>Qc(e,e=>{let r=t(e);return Na(r)?nc(r.failure):n(r.success,e)})),tl=/*#__PURE__*/ j(2,(e,t)=>el(e,ms,e=>t(e))),gne=/*#__PURE__*/ j(2,(e,t)=>el(e,gs,t)),_ne=/*#__PURE__*/ j(2,(e,t)=>Qc(e,e=>Pc(t(e),nc(e)))),vne=/*#__PURE__*/ j(3,(e,t,n)=>Qc(e,e=>{let r=t(e);return Na(r)?nc(e):Pc(n(r.success,e),nc(e))})),yne=/*#__PURE__*/ j(2,(e,t)=>vne(e,ms,e=>t(e))),nl=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n,r)=>Qc(e,e=>{let i=ms(e);return Na(i)?nc(i.failure):t(i.success)?n(i.success):r?r(i.success):nc(e)})),bne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n,r)=>Qc(e,e=>{let i=ms(e);if(Na(i))return nc(i.failure);let a=t(i.success);return Na(a)?r?r(a.failure):nc(e):n(a.success)})),xne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n,r)=>{let i=Array.isArray(t)?e=>N(e,`_tag`)&&t.includes(e._tag):on(t);return nl(e,i,n,r)}),Sne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n)=>{let r;return bne(e,e=>(r??=Object.keys(t),N(e,`_tag`)&&Ut(e._tag)&&r.includes(e._tag)?ka(e):Aa(e)),e=>t[e._tag](e),n)}),rl=/*#__PURE__*/ j(2,(e,t)=>tl(e,e=>dc(()=>t(e)))),Cne=/*#__PURE__*/ j(2,(e,t)=>sl(e,{onFailure:e=>dc(()=>t.onFailure(e)),onSuccess:e=>ic(()=>t.onSuccess(e))})),wne=e=>tl(e,uc),Tne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t)=>{if(!t?.log)return sl(e,{onFailure:e=>fc,onSuccess:e=>fc});let n=Ku(t.log===!0?void 0:t.log);return al(e,{onFailure(e){let r=ps(e);return Na(r)?nc(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>fc})}),Ene=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t)=>{if(!t?.log)return al(e,{onFailure:e=>fc,onSuccess:e=>fc});let n=Ku(t.log===!0?void 0:t.log);return al(e,{onFailure:e=>t.message===void 0?n(e):n(t.message,e),onSuccess:e=>fc})}),Dne=e=>cl(e,{onFailure:Ni,onSuccess:Pi}),il=e=>jne(e,{onFailure:Aa,onSuccess:ka}),al=/*#__PURE__*/ j(2,(e,t)=>new ol(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),One=/*#__PURE__*/ qr({op:`OnSuccessAndFailure`,[_r]:Dc}),ol=function(e,t,n){this[gr]=e,this[vr]=t,this[yr]=n};ol.prototype=One;const kne=function(e,t){let n=this.payload;return t.succeedWith(jc?n.onSuccess(e):ur(()=>n.onSuccess(e)))},Ane=/*#__PURE__*/ ((e,t)=>{let n=qr({op:e,[_r]:Dc,[vr]:kne,[yr]:t}),r=function(e,t){this[gr]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=e.reasons.find(Ur);if(n===void 0)return nc(e);let r=this.payload;return t.succeedWith(jc?r.onFailure(n.error):ur(()=>r.onFailure(n.error)))}),sl=/*#__PURE__*/ j(2,(e,t)=>al(e,{onFailure:e=>{let n=e.reasons.find(Ur);return n?t.onFailure(n.error):nc(e)},onSuccess:t.onSuccess})),cl=/*#__PURE__*/ j(2,(e,t)=>new Ane(e,t)),jne=/*#__PURE__*/ j(2,(e,t)=>{if(zc(e)){if(e._tag===`Success`)return Xr(t.onSuccess(e.value));let n=ms(e.cause);return Na(n)?e:Xr(t.onFailure(n.success))}return cl(e,t)}),ll=e=>zc(e)?Xr(e):Mne(e),Mne=/*#__PURE__*/ Jr({op:`Exit`,[_r](e){return e._stack.push(this),this[gr]},[vr](e,t,n){return t.succeedWith(n??Xr(e))},[yr](e,t,n){return t.succeedWith(n??$r(e))}}),Nne=/*#__PURE__*/ j(2,(e,t)=>Pc(Iu(t),e)),ul=/*#__PURE__*/ j(2,(e,t)=>Rc(Ine(e,t.duration),e=>Fi(e)?t.orElse():tc(e.value))),Pne=e=>new ere(`Operation timed out after '${So(e)}'`),Fne=/*#__PURE__*/ j(2,(e,t)=>{let n=ao(t);return ul(e,{duration:n,orElse:()=>rc(Pne(n))})}),Ine=/*#__PURE__*/ j(2,(e,t)=>Lc(Nc(e),Ec(Iu(t),Ni()))),dl=`~effect/Scope`,fl=`~effect/Scope/Closeable`,pl=/*#__PURE__*/ P(`effect/Scope`),ml=(e,t)=>ni(n=>(Kl(n),hl(e,t)??fc)),hl=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&xl(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return gl(n.finalizer,t);let r=n.finalizers;return r.size===1?gl(r.values().next().value,t):Lne(e,r,t)},gl=(e,t)=>{try{return e(t)}catch(e){return ti(e)}},_l=(e,t)=>Hc(e)?t:Qc(t,t=>nc(Ir(e.cause,t))),Lne=/*#__PURE__*/ bc(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Vs();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*ll(gl(s,n))):i.push(iu(o,gl(s,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Xs(i)),yield*Gc(r)}),Rne=(e,t)=>ic(()=>vl(e,t)),vl=(e,t)=>{let n=Cl(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(bl(e,n,e=>ml(n,e)),n)},yl=(e,t)=>ac(()=>e.state._tag===`Closed`?t(e.state.exit):(bl(e,{},t),fc)),zne=(e,t)=>yl(e,jt(t)),bl=(e,t,n)=>{if(e.state._tag===`Empty`)e.state={_tag:`Open`,finalizerKey:t,finalizer:n,finalizers:void 0};else if(e.state._tag===`Open`){let r=e.state;r.finalizer===void 0||(r.finalizers=/* @__PURE__ */ new Map([[r.finalizerKey,r.finalizer]]),r.finalizerKey=void 0,r.finalizer=void 0),r.finalizers.set(t,n)}},xl=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=wl:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=wl))},Sl=e=>Cl(e,void 0),Cl=(e=`sequential`,t)=>({[fl]:fl,[dl]:dl,strategy:e,parent:t,state:wl}),wl={_tag:`Empty`},Bne=e=>ic(()=>Sl(e)),Tl=pl,El=/*#__PURE__*/ Xc(pl),Dl=e=>ni(t=>{let n=t.context,r=Sl();return t.setContext(fa(t.context,pl,r)),Nl(t,e=>(t.setContext(n),hl(r,e))),e}),Ol=/*#__PURE__*/ j(2,(e,t)=>Pl(El(e,t),e=>ac(()=>hl(t,e)??fc))),kl=e=>ac(()=>{let t=Sl();return Pl(e(t),e=>ac(()=>hl(t,e)??fc))}),Vne=(e,t,n)=>Jc(r=>Yl(i=>Rc(Tl,a=>Fc(n?.interruptible?i(e):e,e=>yl(a,n=>Yc(t(e,n),r)))))),Al=e=>Rc(Tl,t=>Jc(n=>yl(t,t=>Yc(e(t),n)))),jl=/*#__PURE__*/ function(){let e=/*#__PURE__*/ qr({op:`OnExit`,[_r](e){return e._stack.push(this),this.effect},[br](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(Ul),e.interruptible=!1)},[vr](e,t,n){n??=Xr(e);let r;try{r=this.onExit(n)}catch(e){r=ti(e)}return r?Rc(r,e=>n):n},[yr](e,t,n){n??=$r(e);let r;try{r=this.onExit(n)}catch(e){r=ti(e)}return r?Rc(_l(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),Ml=(e,t,n)=>new jl(e,t,n),Nl=(e,t)=>{e._stack.push(new jl(void 0,t,void 0))},Pl=/*#__PURE__*/ j(2,Ml),Fl=/*#__PURE__*/ j(2,(e,t)=>Pl(e,e=>t)),Il=/*#__PURE__*/ j(3,(e,t,n)=>Pl(e,e=>{let r=t(e);return Na(r)?fc:n(r.success,e)})),Ll=/*#__PURE__*/ j(2,(e,t)=>Il(e,tne,t)),Rl=/*#__PURE__*/ j(3,(e,t,n)=>Pl(e,e=>{if(e._tag!==`Failure`)return fc;let r=t(e.cause);return Na(r)?fc:n(r.success,e.cause)})),zl=/*#__PURE__*/ j(2,(e,t)=>Rl(vs,t)(e)),Hne=/*#__PURE__*/ jt(1/0),Une=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,Nl(e,()=>{if(!(--t.awaiters>0||i!==t))return i=void 0,Qs(t.fiber)}),Zs(t.fiber));return[ni(o=>{if(i!==void 0)return o===i.fiber?Zs(i.fiber):a(o,i);if(r!==void 0&&(n===1/0||o.getRef(ku).currentTimeMillisUnsafe()<n))return r;r=void 0;let s=o.getRef(ku),c={fiber:new Hs(o.context),awaiters:0};i=c;let l=a(o,c);return c.fiber.evaluate(Ml(e,e=>{if(i!==c||(i=void 0,Uc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),ic(()=>{r=void 0})]},Wne=e=>ic(()=>Une(e,Hne)[0]),Bl=/*#__PURE__*/ ni(e=>nc(fs(e.id))),Vl=e=>ni(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(Ul)),e)),Hl=/*#__PURE__*/ Jr({op:`SetInterruptible`,[br](e){if(e.interruptible=this[gr],e._interruptedCause&&e.interruptible)return()=>nc(e._interruptedCause)}}),Ul=/*#__PURE__*/ Hl(!0),Wl=/*#__PURE__*/ Hl(!1),Gl=e=>{if(e.interruptible=!0,e._stack.push(Wl),e._interruptedCause)return nc(e._interruptedCause)},Kl=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(Ul))},ql=e=>{let t=e;if(!t.interruptible)return Gl(t)},Jl=e=>ni(t=>t.interruptible?e:Gl(t)??e),Yl=e=>ni(t=>t.interruptible?(t.interruptible=!1,t._stack.push(Ul),e(Jl)):e(M)),Xl=(e,t)=>cn(e)?t?.mode===`result`?Ql(e,il,t):Ql(e,M,t):t?.discard?t.mode===`result`?Ql(Object.values(e),il,t):Ql(Object.values(e),M,t):ac(()=>{let n={};return Ec(Ql(Object.entries(e),([e,r])=>Bc(t?.mode===`result`?il(r):r,t=>{dr(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),Zl=/*#__PURE__*/ Jr({op:`While`,[vr](e,t){return this[gr].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[gr].body()):Wc},[_r](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[gr].body()):Wc}}),Ql=/*#__PURE__*/ j(e=>typeof e[1]==`function`,(e,t,n)=>ac(()=>{let r=eu(n?.concurrency);if(r===1)return $l(e,t,n);let i=Ba(e),a=i.length;if(a===0)return n?.discard?fc:tc([]);let o=n?.discard?void 0:Array(a),s=Gne({f:t,out:o},i,{concurrency:r});return s?Ec(s,o):tc(o)})),$l=(e,t,n)=>ac(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return Ec(Zl({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),eu=e=>e===`unbounded`?1/0:Math.max(1,e??1),tu=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>Rc(ll(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??fc),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!zc(c))return r(e,i,a,o,c);let l=n(e,s,c,a);if(l)return l._tag===`Failure`?l:void 0}};return i},nu=e=>{let t=e.onItem,n=e.step;return(e,r,i)=>{let a=0,o=i.end??r.length,s=i.concurrency,c=!1,l,u,d,f,p,m=e=>{let t=ti(e);return f=t,c=!0,u&&u.size>0?Rc(Vl(ec(Array.from(u))),()=>f??t):t},h=()=>{let i=!1;for(;!f&&a<o;a++){let o=r[a],g=p??t(e,o,a);if(zc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=iu(l,g,!0,!0,`inherit`);if(t._exit){if(f=n(e,o,t._exit,a),f)break;continue}u.add(t);let r=a;if(t.addObserver(a=>{u.delete(t);try{if(f){if(a._tag===`Failure`){let e=a.cause.reasons.filter(e=>e._tag!==`Interrupt`);if(e.length>0){let t=Pr(e);f=$r(f._tag===`Failure`?Ir(f.cause,t):t)}}}else{let t=n(e,o,a,r);t&&(f=t,h())}if(i){let e=h();e&&d(e)}else c&&u.size===0&&d(f??fc)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return vc(e=>{l=Vs(),u=/* @__PURE__ */ new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):ac(()=>(f??=Wc,Rc(u?ec(u):fc,()=>f?._tag===`Failure`?f:fc)))})}if(c=!0,f){if(u&&u.size>0){let e=qs(l);u.forEach(t=>t.interruptUnsafe(l.id,e));return}if(d||f._tag===`Failure`)return f}else if(d){if(u)u.size===0&&d(fc);else return Wc}};return h()}},ru=()=>e=>nu(e),Gne=/*#__PURE__*/ nu({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag===`Failure`)return n;e.out&&(e.out[r]=n.value)}}),Kne=/*#__PURE__*/ j(3,(e,t,n)=>Rc(e,e=>t(e)?tc(e):n(e))),qne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t)=>ni(n=>(pre(),tc(iu(n,e,t?.startImmediately,!1,t?.uninterruptible??!1))))),iu=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Hs(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=Bs(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},au=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n)=>ni(r=>{let i=iu(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};bl(t,e,()=>gc(e=>e===i.id?fc:Qs(i))),i.addObserver(()=>xl(t,e))}else i.interruptUnsafe(r.id,qs(r))}return tc(i)})),Jne=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t)=>Rc(Tl,n=>au(e,n,t))),ou=e=>(t,n)=>{let r=new Hs(n?.scheduler?fa(e,Co,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal){if(n.signal.aborted)r.interruptUnsafe();else{let e=()=>r.interruptUnsafe();n.signal.addEventListener(`abort`,e,{once:!0}),r.addObserver(()=>n.signal.removeEventListener(`abort`,e))}}return n?.onFiberStart&&n.onFiberStart(r),r},Yne=/*#__PURE__*/ j(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(xl(t,e),bl(t,e,()=>Qs(e)),e.addObserver(()=>xl(t,e)),e)),Xne=/*#__PURE__*/ ou(/*#__PURE__*/ la()),Zne=e=>{let t=ou(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},su=e=>{let t=Zne(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw ws(e.cause);return e.value})},Qne=/*#__PURE__*/ su(/*#__PURE__*/ la()),cu=e=>{let t=ou(e);return e=>{if(zc(e))return e;let n=new Eo(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??ti(new rre(r))}},lu=/*#__PURE__*/ cu(/*#__PURE__*/ la()),uu=/*#__PURE__*/ (e=>{let t=cu(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw ws(n.cause);return n.value}})(/*#__PURE__*/ la()),du=/*#__PURE__*/ tc(!0),fu=/*#__PURE__*/ tc(!1);var pu=class{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return du;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let e=0;e<this.waiters.length;e++)this.scheduled.push(this.waiters[e]);return this.waiters=[],du}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](Wc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Wc)}open=/*#__PURE__*/ ni(e=>this._isOpen?fu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=/*#__PURE__*/ ni(e=>this._isOpen?fu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=/*#__PURE__*/ vc(e=>this._isOpen?e(fc):(this.waiters.push(e),ic(()=>{let t=this.waiters.indexOf(e);t===-1?this.scheduled!==void 0&&(t=this.scheduled.indexOf(e),t!==-1&&this.scheduled.splice(t,1)):this.waiters.splice(t,1)})));closeUnsafe(){return this._isOpen?(this._isOpen=!1,!0):!1}close=/*#__PURE__*/ ic(()=>this.closeUnsafe());whenOpen=e=>Rc(this.await,()=>e);isOpen(){return this._isOpen}};const mu=e=>new pu(e??!1),hu=e=>ic(()=>mu(e)),gu=/*#__PURE__*/ BigInt(0),_u={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:gu,endTime:gu,exit:Wc},attributes:/*#__PURE__*/ new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},vu=e=>Object.assign(Object.create(_u),e),yu=e=>e?va(e.annotations,Wo)?e._tag===`Span`?yu(Vi(e.parent)):Ni():Pi(e):Ni(),bu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&va(n.annotations,Wo),i=n?.parent===void 0?n?.root?Ni():yu(e.cache.span):Pi(n.parent),a;if(r)a=vu({name:t,parent:i,annotations:fa(n?.annotations??la(),Wo,!0)});else{let r=e.cache.tracer??Yo,o=e.getRef(ku),s=e.getRef(es),c=e.getRef(ts),l=e.getRef(ns),u=n?.level??e.getRef(Go),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??la(),links:d,startTime:s?o.currentTimeNanosUnsafe():gu,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(Ii(i)&&i.value.sampled===!1?!1:!Wu(e.getRef(Ko),u))});for(let e in c)a.attribute(e,c[e]);if(n?.attributes!==void 0)for(let e in n.attributes)a.attribute(e,n.attributes[e])}return a},xu=(e,t)=>Vl(ni(n=>{let r=_a(n.context,pl),i=bu(n,e,t??{}),a=n.getRef(ku),o=n.getRef(es);return Ec(yl(r,e=>Cu(i,e,a,o)),i)})),Su=(e,t)=>(t=typeof t==`function`?t:Pt,qc(Qo,n=>({name:e,stack:t,parent:n}))),Cu=(e,t,n,r)=>ic(()=>{e.status._tag!==`Ended`&&e.end(r?n.currentTimeNanosUnsafe():gu,t)}),wu=(e,...t)=>{let n=t.length===1?void 0:t[0],r=t[t.length-1];return ni(t=>{let i=bu(t,e,n),a=t.getRef(ku),o=t.getRef(es);return Nl(t,e=>Cu(i,e,a,o)),r(i)})},Tu=/*#__PURE__*/ Xc(Vo),Eu=function(){let e=Cr(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=M;return t._tag===`Span`&&(n=ss(n),r=Su(t.name,n?.captureStackTrace)),e?Tu(r(arguments[0]),t):e=>Tu(r(e),t)},Du=function(){let e=typeof arguments[0]!=`string`,t=e?arguments[1]:arguments[0],n=ss(arguments[2]);if(e){let e=arguments[0];return wu(t,arguments[2],t=>Eu(e,t,n))}let r=typeof arguments[1]==`function`?arguments[1]:void 0,i=r?void 0:arguments[1];return(e,...a)=>wu(t,r?r(...a):i,t=>Eu(e,t,n))},Ou=(...e)=>ni(t=>{let n=t.currentSpanLocal;if(n){if(e.length===1)for(let[t,r]of Object.entries(e[0]))n.attribute(t,r);else n.attribute(e[0],e[1])}return fc}),ku=/*#__PURE__*/ Ea(`effect/Clock`,{defaultValue:()=>new ju}),Au=2**31-1;var ju=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=/*#__PURE__*/ ic(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Pu()}currentTimeNanos=/*#__PURE__*/ ic(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return Nu()}monotonicTimeNanos=/*#__PURE__*/ ic(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(yo(e))}sleepMillis(e){return e<=0?sc:Number.isFinite(e)?vc(t=>{let n=e>Au?this.sleepMillis(e-Au):fc,r=setTimeout(()=>t(n),Math.min(e,Au));return ic(()=>clearTimeout(r))}):yc}};const Mu=/*#__PURE__*/ BigInt(1e6),Nu=/*#__PURE__*/ function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==`function`)return()=>e.bigint();if(typeof performance<`u`&&typeof performance.now==`function`)return()=>BigInt(Math.round(performance.now()*1e6));let t=/*#__PURE__*/ BigInt(0);return()=>{let e=BigInt(Date.now())*Mu;return e>t&&(t=e),t}}(),Pu=/*#__PURE__*/ function(){let e=/*#__PURE__*/ BigInt(1e9),t;return()=>{let n=Nu(),r=BigInt(Date.now())*Mu;if(t===void 0)t=r-n;else{let i=t+n;(r>i?r-i:i-r)>e&&(t=r-n)}return t+n}}(),Fu=e=>ni(t=>e(t.getRef(ku))),Iu=e=>Fu(t=>t.sleep(ao(e))),$ne=/*#__PURE__*/ Fu(e=>e.currentTimeMillis),Lu=`~effect/Cause/TimeoutError`;var ere=class extends (/*#__PURE__*/ ai(`TimeoutError`)){[Lu]=Lu;constructor(e){super({message:e})}};const Ru=`~effect/Cause/IllegalArgumentError`;var tre=class extends (/*#__PURE__*/ ai(`IllegalArgumentError`)){[Ru]=Ru;constructor(e){super({message:e})}};const zu=`~effect/Cause/ExceededCapacityError`;var nre=class extends (/*#__PURE__*/ ai(`ExceededCapacityError`)){[zu]=zu;constructor(e){super({message:e})}};const Bu=`~effect/Cause/AsyncFiberError`;var rre=class extends (/*#__PURE__*/ ai(`AsyncFiberError`)){[Bu]=Bu;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};const Vu=`~effect/Cause/UnknownError`;var Hu=class extends (/*#__PURE__*/ ai(`UnknownError`)){[Vu]=Vu;constructor(e,t){super({message:t,cause:e})}};const ire=/*#__PURE__*/ Ea(`effect/Console`,{defaultValue:()=>globalThis.console}),Uu=/*#__PURE__*/ Gee(ki,e=>{switch(e){case`All`:return-(2**53-1);case`Fatal`:return 5e4;case`Error`:return 4e4;case`Warn`:return 3e4;case`Info`:return 2e4;case`Debug`:return 1e4;case`Trace`:return 0;case`None`:return 2**53-1}}),Wu=/*#__PURE__*/ Ai(Uu),are=/*#__PURE__*/ Ea(`effect/Logger/CurrentLoggers`,{defaultValue:()=>/* @__PURE__ */ new Set([dre,fre])}),ore=/*#__PURE__*/ Ea(`effect/Logger/LogToStderr`,{defaultValue:Nt}),sre={"~effect/Logger":{_Message:M,_Output:M},pipe(){return Ot(this,arguments)}},Gu=e=>{let t=Object.create(sre);return t.log=e,t},cre=e=>e.replace(/[\s="]/g,`_`),lre=(e,t)=>`${cre(e[0])}=${t-e[1]}ms`,Ku=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];Dr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?Pr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=Rr),ni(r=>{let i=e??r.cache.logLevel;if(Wu(r.cache.minimumLogLevel,i))return fc;let a=r.getRef(ku),o=r.getRef(are);if(o.size>0){let e=new Date(a.currentTimeMillisUnsafe());for(let a of o)a.log({cause:n,fiber:r,date:e,logLevel:i,message:t})}return fc})},qu={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};qu.gray,qu.blue,qu.green,qu.yellow,qu.red,qu.bgBrightRed,qu.black;const ure=e=>`${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}.${e.getMilliseconds().toString().padStart(3,`0`)}`,dre=/*#__PURE__*/ Gu(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Ns(e));let o=t.getTime(),s=n.getRef(os),c=``;for(let e of s)c+=` ${lre(e,o)}`;let l=n.getRef(rs);Object.keys(l).length>0&&a.push(l);let u=n.getRef(ire);(n.getRef(ore)?u.error:u.log)(`[${ure(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),fre=/*#__PURE__*/ Gu(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(ku),a=t.getRef(rs),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))dr(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Ns(e)),o.event(Tee(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});function pre(){Ks.interruptChildren??=Js}const mre=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t)=>Ll(e,e=>ni(n=>(Ju(n,e,t?.defectsOnly),fc)))),Ju=(e,t,n)=>{let r=e.getRef(Zo);if(r.size===0||n&&!hs(t))return;let i={cause:t,fiber:e,timestamp:e.getRef(ku).currentTimeNanosUnsafe()};r.forEach(e=>e.report(i))},hre=Dr,gre=Or,Yu=Ur,_re=Wr,Xu=Pr,Zu=zr,Qu=Vr,$u=e=>new Nr(e),ed=e=>new Br(e),td=ds,nd=xs,rd=Cs,id=Ir,ad=ws,od=ms,sd=hs,cd=_s,ld=ys,ud=Ns,dd=si,fd=kee,pd=di,md=jee,hd=tre,gd=nre,_d=Hu,vd=Ss;var yd=class extends (/*#__PURE__*/ P()(`effect/Cause/StackTrace`)){};const bd=wr,xd=Xr,Sd=$r,Cd=ei,wd=ti,Td=Vc,Ed=Wc,Dd=Hc,Od=ene,kd=Uc,Ad=Gc,jd=`~effect/Deferred`,Md=e=>N(e,jd),Nd={[jd]:{_A:M,_E:M},pipe(){return Ot(this,arguments)}},Pd=function(){this.resumes=void 0,this.effect=void 0};Pd.prototype=Nd;const Fd=()=>new Pd,Id=()=>ic(()=>Fd()),Ld=e=>vc(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),ic(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),Rd=/* @__PURE__ */ j(2,(e,t)=>ic(()=>Wd(e,t))),zd=/*#__PURE__*/ j(2,(e,t)=>Rd(e,$r(t))),Bd=/*#__PURE__*/ j(2,(e,t)=>zd(e,fs(t))),Vd=e=>ic(()=>Hd(e)),Hd=e=>e.effect!==void 0,Ud=/*#__PURE__*/ j(2,(e,t)=>Rd(e,Xr(t))),Wd=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},Gd=rs,Kd=is,qd=es,Jd=pl,Yd=Bne,Xd=Sl,Zd=El,Qd=yl,$d=zne,ef=Rne,tf=vl,nf=ml,rf=hl,af=Ol,of=`~effect/Layer/MemoMap`,sf=(e,t)=>{let n={observers:0,deferred:Fd(),scope:Xd(),finalizer:r=>ac(()=>--n.observers>0?fc:(e.map.delete(t),nf(n.scope,r)))};return n},cf=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,bl(t,{},e.finalizer),!0),lf={"~effect/Layer":{_ROut:M,_E:M,_RIn:M},pipe(){return Ot(this,arguments)}},uf=e=>{let t=Object.create(lf);return t.build=e,t},df=e=>uf((t,n)=>{let r=tf(n);return Pl(e(t,r),e=>e._tag===`Failure`?nf(r,e):fc)}),ff=e=>{let t=df((n,r)=>n.getOrElseMemoize(t,r,e));return t};var pf=class{get[of](){return of}parent;constructor(e){this.parent=e}map=/*#__PURE__*/ new Map;get(e,t){let n=this.map.get(e);return n?(cf(n,t),n.deferred.effect??Ld(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return ac(()=>{let r;return Ml(ac(()=>{let i=this.get(e,t);if(i)return i;let a=sf(this,e);return cf(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&Wd(r,e)})})}};const mf=()=>new pf,vre=e=>new pf(e);var hf=class e extends (/*#__PURE__*/ P()(`effect/Layer/CurrentMemoMap`)){static forkOrCreate(t){let n=ha(t,e);return n?vre(n):mf()}};const gf=/*#__PURE__*/ j(3,(e,t,n)=>Xc(Bc(ac(()=>e.build(t,n)),fa(hf,t)),hf,t)),yre=e=>ni(t=>gf(e,hf.forkOrCreate(t.context),_a(t.context,Jd))),bre=/*#__PURE__*/ j(2,(e,t)=>ni(n=>gf(e,hf.forkOrCreate(n.context),t))),_f=function(){return arguments.length===1?e=>vf(da(arguments[0],e)):vf(da(arguments[0],arguments[1]))},vf=e=>uf(jt(tc(e))),yf=/*#__PURE__*/ vf(/*#__PURE__*/ la()),bf=function(){return arguments.length===1?e=>xf(arguments[0],e):xf(arguments[0],arguments[1])},xf=(e,t)=>Sf(Bc(t,t=>da(e,t))),Sf=e=>ff((t,n)=>Zd(e,n)),Cf=e=>Sf(Ec(e,la())),wf=/*#__PURE__*/ P(`effect/Layer/unwrap`),Tf=e=>xre(bf(wf)(e),va(wf)),Ef=(e,t,n)=>{let r=tf(n,`parallel`);return Ql(e,e=>e.build(t,tf(r,`sequential`)),{concurrency:e.length}).pipe(Bc(e=>wa(...e)))},Df=(...e)=>df((t,n)=>Ef(e,t,n)),Of=/*#__PURE__*/ j(2,(e,t)=>Df(e,...Array.isArray(t)?t:[t])),kf=(e,t,n)=>df((r,i)=>Rc(Array.isArray(t)?Ef(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(Yc(t),Bc(e=>n(e,t))))),Af=/*#__PURE__*/ j(2,(e,t)=>kf(e,t,M)),jf=/*#__PURE__*/ j(2,(e,t)=>kf(e,t,(e,t)=>Ca(t,e))),xre=/*#__PURE__*/ j(2,(e,t)=>df((n,r)=>Rc(e.build(n,r),e=>t(e).build(n,r)))),Sre=e=>uf((t,n)=>e.build(mf(),n)),Mf=ku,Nf=$ne,Pf=`~effect/DateTime`,Ff=`~effect/DateTime/TimeZone`,If={[Pf]:Pf,pipe(){return Ot(this,arguments)},[rr](){return this.toString()},toJSON(){return Hf(this).toJSON()}},Cre={...If,_tag:`Utc`,[ln](){return gn(this.epochMilliseconds)},[En](e){return Rf(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Hf(this).toJSON()})`}};({...If});const Lf={[Ff]:Ff,[rr](){return this.toString()}};({...Lf}),{...Lf};const Rf=e=>N(e,Pf),wre=e=>e._tag===`Utc`,zf=e=>{let t=Object.create(Cre);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Bf=e=>{let t=e.getTime();if(Number.isNaN(t))throw new hd(`Invalid date`);return zf(t)},Vf=e=>{if(Rf(e))return e;if(e instanceof Date)return Bf(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Bf(new Date(e.epochMilliseconds));let t=/* @__PURE__ */ new Date(0);return kre(t,e),Bf(t)}return typeof e==`string`&&!Tre(e)?Bf(/* @__PURE__ */ new Date(e+`Z`)):Bf(new Date(e))},Tre=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Ere=/*#__PURE__*/ Hi(Vf),Dre=e=>zf(e.epochMilliseconds),Hf=e=>new Date(e.epochMilliseconds),Ore=e=>e.epochMilliseconds,kre=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Are=e=>Hf(e).toISOString();globalThis.String;const jre=e=>e.trim(),Mre=(e,t,n)=>{let r=n*(t-e)+e;if(r!==t||e>=t||!Number.isFinite(t))return r;if(t===0)return-Number.MIN_VALUE;let i=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));i.setFloat64(0,t);let a=i.getBigUint64(0);return i.setBigUint64(0,t>0?a-BigInt(1):a+BigInt(1)),i.getFloat64(0)},Uf=/*#__PURE__*/ j(2,(e,t)=>el(e,Nre,e=>t(e))),Wf=e=>e.reasons.some(Gf),Gf=e=>e._tag===`Fail`&&fd(e.error),Kf=e=>{let t,n=!1;for(let r of e.reasons)Gf(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Aa(e):n?Aa(Xu(e.reasons.filter(e=>!Gf(e)))):ka(t)},Nre=e=>{let t=Kf(e);return Na(t)?t:ka(t.success.value)},qf=e=>{let t=Kf(e);return Na(t)?Sd(t.failure):xd(t.success.value)},Pre=/*#__PURE__*/ j(2,(e,t)=>al(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=Kf(e);return Na(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Fre=(e,t,n)=>kl(r=>Rc(n?.local?gf(t,mf(),r):bre(t,r),t=>Yc(e,t))),Ire=/*#__PURE__*/ j(e=>Cr(e[0]),(e,t,n)=>oa(t)?Yc(e,t):Fre(e,Array.isArray(t)?Df(...t):t,n)),Jf=`~effect/MutableHashMap`,Lre={[Jf]:Jf,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${qn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:ir(Array.from(this))}},[rr](){return this.toJSON()},pipe(){return Ot(this,arguments)}},Rre=()=>{let e=Object.create(Lre);return e.backing=/* @__PURE__ */ new Map,e.buckets=/* @__PURE__ */ new Map,e},Yf=/*#__PURE__*/ j(2,(e,t)=>{if(e.backing.has(t))return Pi(e.backing.get(t));if(Xf(t))return Ni();let n=un(t),r=e.buckets.get(n);return r===void 0?Ni():zre(e,r,t)}),Xf=e=>typeof e!=`object`&&typeof e!=`function`,zre=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(Dn(n,t[r])){let n=t[r];return Pi(e.backing.get(n))}return Ni()},Bre=/*#__PURE__*/ j(3,(e,t,n)=>{if(e.backing.has(t)||Xf(t))return e.backing.set(t,n),e;let r=un(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Vre(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Vre=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(Dn(t,e[n]))return e[n]},Zf=/*#__PURE__*/ j(2,(e,t)=>{if(Xf(t))return e.backing.delete(t),e;let n=un(t),r=e.buckets.get(n);if(r===void 0)return e;for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i===t||Dn(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Hre=e=>(e.backing.clear(),e.buckets.clear(),e),Ure=e=>e.backing.size,Qf=Cr,$f=Xl,ep=Ql,tp=Zl,np=mc,rp=hc,F=tc,ip=cc,ap=ac,I=ic,L=fc,op=vc,sp=yc,R=Lte,z=rc,cp=nc,lp=lc,up=uc,dp=pc,Wre=sc,fp=ni,pp=oc,B=Rc,Gre=Yte,mp=Pc,hp=Fc,gp=il,Kre=Dne,_p=ll,V=Bc,vp=Ec,yp=Ic,bp=tl,xp=xne,qre=Sne,Sp=Qc,Cp=gne,wp=nl,Jre=hne,Tp=rl,Ep=wne,Dp=yne,Op=_ne,kp=Tne,Ap=Ene,Yre=mre,Xre=Fne,jp=ul,Zre=Nne,Mp=Iu,Qre=Kte,Np=Lc,$re=dne,eie=fne,Pp=cl,tie=qte,Fp=al,Ip=sl,Lp=cne,Rp=Jc,zp=Ire,Bp=Yc,nie=une,Vp=one,Hp=sne,Up=Kc,Wp=Xc,Gp=Tl,Kp=Dl,rie=kl,qp=Vne,Jp=Al,Yp=Fl,Xp=Ll,Zp=Ml,Qp=Pl,$p=Wne,em=Bl,tm=Jl,nm=zl,rm=Vl,im=Yl,am=pne,iie=Ou,om=xu,sm=wu,cm=Du,lm=Eu,um=qne,dm=au,fm=Jne,pm=Xne,mm=ou,hm=Qne,gm=su,_m=uu,vm=lu,H=bc,ym=Rte,bm=Fu,xm=/*#__PURE__*/ Ku(`Fatal`),Sm=/*#__PURE__*/ Ku(`Warn`),Cm=/*#__PURE__*/ Ku(`Error`),wm=/*#__PURE__*/ Ku(`Info`),Tm=/*#__PURE__*/ Ku(`Debug`),Em=/*#__PURE__*/ j(e=>Qf(e[0]),(e,...t)=>qc(e,Gd,e=>{let n=t.length===1?{...e,...t[0]}:{...e};return t.length===1||dr(n,t[0],t[1]),n})),Dm=(e,t,n)=>(...r)=>op(i=>{try{e(...r,(e,n)=>{i(e?t?ap(()=>z(t(e,r))):z(e):F(n))})}catch(e){i(n?z(n(e,r)):up(e))}}),Om=Xte,km=Zte,Am=Qte,jm=Jte,Mm=$te,Nm=zte,Pm=`~effect/BigDecimal`,Fm={[Pm]:Pm,[ln](){let e=Um(this);return pn(_n(String(e.value)),gn(e.scale))},[En](e){return Im(e)&&qm(this,e)===0},toString(){return`BigDecimal(${Ym(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[rr](){return this.toJSON()},pipe(){return Ot(this,arguments)}},Im=e=>N(e,Pm),Lm=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(Fm);return n.value=e,n.scale=t,n},Rm=(e,t)=>{let n=Lm(e,t);return n.normalized=n,n},zm=/*#__PURE__*/ BigInt(0),Bm=/*#__PURE__*/ BigInt(1),Vm=/*#__PURE__*/ BigInt(10),Hm=/*#__PURE__*/ Rm(zm,0),Um=e=>{if(e.normalized===void 0){if(e.value===zm)e.normalized=Hm;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=Rm(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Wm=[Bm],Gm=(e,t)=>e===t?0:e<t?-1:1,Km=(e,t)=>{let n=`${e.value<zm?-e.value:e.value}`,r=`${t.value<zm?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==zm)return i<zm?-1:1;let a=Math.max(n.length,r.length);return Wee(n.padEnd(a,`0`),r.padEnd(a,`0`))},qm=(e,t)=>{if(e.scale===t.scale)return Gm(e.value,t.value);let n=Jm(e),r=Jm(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>100)return n===-1?Km(t,e):Km(e,t);let o=Wm[a]??=Vm**BigInt(a);return i>0?Gm(e.value,t.value*o):Gm(e.value*o,t.value)},Jm=e=>e.value===zm?0:e.value<zm?-1:1,Ym=e=>{let t=Um(e);if(Math.abs(t.scale)>=16)return Xm(t);let n=t.value<zm,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},Xm=e=>{if(Zm(e))return`0e+0`;let t=Um(e),n=`${t.value}`,r=t.value<zm?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Zm=e=>e.value===zm,Qm=globalThis.BigInt,$m=e=>e>Qm(2**53-1)||e<Qm(-(2**53-1))?Ni():Pi(Number(e)),eh=/*#__PURE__*/ BigInt(0),th=/*#__PURE__*/ BigInt(1),nh=/*#__PURE__*/ BigInt(1e3),rh=/*#__PURE__*/ BigInt(1024),ih=[{symbol:`B`,factor:th,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:nh,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:nh**/*#__PURE__*/ BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:nh**/*#__PURE__*/ BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:nh**/*#__PURE__*/ BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:nh**/*#__PURE__*/ BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:nh**/*#__PURE__*/ BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:nh**/*#__PURE__*/ BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:nh**/*#__PURE__*/ BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:nh**/*#__PURE__*/ BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:nh**/*#__PURE__*/ BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],ah=[ih[0],{symbol:`KiB`,factor:rh,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:rh**/*#__PURE__*/ BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:rh**/*#__PURE__*/ BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:rh**/*#__PURE__*/ BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:rh**/*#__PURE__*/ BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:rh**/*#__PURE__*/ BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:rh**/*#__PURE__*/ BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:rh**/*#__PURE__*/ BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}],oh=[...ih,.../*#__PURE__*/ ah.slice(1)],sh=/*#__PURE__*/ new Map(/*#__PURE__*/ oh.flatMap(e=>e.names.map(t=>[t,e]))),ch=/*#__PURE__*/ new Map(/*#__PURE__*/ oh.map(e=>[e.symbol,e])),lh=e=>e,uh=/*#__PURE__*/ lh(eh),dh=e=>{throw Error(`Invalid ByteSize: ${e}`)},fh=e=>!Number.isSafeInteger(e)||e<0?dh(`expected a non-negative safe integer, received ${e}`):lh(BigInt(e)),ph=(e,t)=>{if(typeof e==`bigint`)return e<eh?dh(`expected a non-negative quantity, received ${e}`):lh(e*t.factor);let n=e*Number(t.factor);return!Number.isSafeInteger(n)||n<0?dh(`expected an exact non-negative safe-integer byte result, received ${e} ${t.symbol}`):lh(BigInt(n))},mh=e=>{let t=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(e);if(t===null)return dh(`unsupported syntax ${JSON.stringify(e)}`);let n=sh.get(t[3]);if(n===void 0)return dh(`unsupported unit ${JSON.stringify(t[3])}`);let r=t[2]??``,i=BigInt(10)**BigInt(r.length),a=BigInt(t[1]+r)*n.factor;return a%i===eh?lh(a/i):dh(`${JSON.stringify(e)} does not represent an integral number of bytes`)},hh=e=>{switch(typeof e){case`bigint`:return e<eh?dh(`expected a non-negative bigint, received ${e}`):lh(e);case`number`:return fh(e);case`string`:return mh(e)}return dh(`unsupported input ${e}`)},gh=/*#__PURE__*/ Hi(hh),_h=e=>typeof e==`bigint`?hh(e):fh(e),vh=/*#__PURE__*/ (e=>t=>ph(t,ch.get(e)))(`MiB`),yh=Rf,bh=wre,xh=Bf,Sh=Vf,Ch=Ere,wh=Dre,Th=Ore,Eh=Are,Dh=e=>Ah(typeof e==`string`?jh.encode(e):e),Oh=e=>{let t=Nh(e),n=t.length;if(n%4!=0)return Aa(new No({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return Aa(new No({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=Ih(t.charCodeAt(e))<<18|Ih(t.charCodeAt(e+1))<<12|Ih(t.charCodeAt(e+2))<<6|Ih(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return ka(r)}catch(e){return Aa(new No({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},kh=e=>Ia(Oh(e),e=>Mh.decode(e)),Ah=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=Ph[e[r-2]>>2],n+=Ph[(e[r-2]&3)<<4|e[r-1]>>4],n+=Ph[(e[r-1]&15)<<2|e[r]>>6],n+=Ph[e[r]&63];return r===t+1&&(n+=Ph[e[r-2]>>2],n+=Ph[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Ph[e[r-2]>>2],n+=Ph[(e[r-2]&3)<<4|e[r-1]>>4],n+=Ph[(e[r-1]&15)<<2],n+=`=`),n},jh=/*#__PURE__*/ new TextEncoder,Mh=/*#__PURE__*/ new TextDecoder,Nh=e=>e.replace(/[\n\r]/g,``),Ph=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Fh=/*#__PURE__*/ (/* @__PURE__ */ new Uint8Array(123)).fill(255);for(let e=0;e<64;e++)Fh[/*#__PURE__*/ Ph.charCodeAt(e)]=e;Fh[61]=0;const Ih=e=>{if(e>=Fh.length||Fh[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Fh[e]},Lh=`~effect/http/Cookies`,Rh=e=>N(e,Lh),zh=`~effect/http/Cookies/Cookie`,Bh=`~effect/http/Cookies/CookieError`;var Vh=class extends Ao{},Hh=class e extends (/*#__PURE__*/ jo(`CookiesError`)){static fromReason(t,n){return new e({reason:new Vh({_tag:t,cause:n})})}[Bh]=Bh;get message(){return this.reason._tag}};const Uh={[Lh]:Lh,...ar,toJSON(){return{_id:`effect/Cookies`,cookies:La(this.cookies,e=>e.toJSON())}},pipe(){return Ot(this,arguments)}},Wh=e=>{let t=Object.create(Uh);return t.cookies=e,t},Gh=e=>{let t={};for(let n of e)dr(t,n.name,n);return Wh(t)},Kh=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=qh(e.trim());t&&n.push(t)}return Gh(n)};function qh(e){let t=e.split(`;`).map(e=>e.trim()).filter(e=>e!==``);if(t.length===0)return;let n=t[0].indexOf(`=`);if(n===-1)return;let r=t[0].slice(0,n);if(!Zh.test(r))return;let i=t[0].slice(n+1),a=ug(i);if(t.length===1)return Object.assign(Object.create(eg),{name:r,value:a,valueEncoded:i});let o={};for(let e=1;e<t.length;e++){let n=t[e],r=n.indexOf(`=`),i=r===-1?n:n.slice(0,r).trim(),a=r===-1?void 0:n.slice(r+1).trim();switch(i.toLowerCase()){case`domain`:{if(a===void 0)break;let e=a.trim().replace(/^\./,``);e&&(o.domain=e);break}case`expires`:{if(a===void 0)break;let e=new Date(a);isNaN(e.getTime())||(o.expires=e);break}case`max-age`:{if(a===void 0)break;let e=parseInt(a,10);isNaN(e)||(o.maxAge=_o(e));break}case`path`:if(a===void 0)break;a[0]===`/`&&(o.path=a);break;case`priority`:if(a===void 0)break;switch(a.toLowerCase()){case`low`:o.priority=`low`;break;case`medium`:o.priority=`medium`;break;case`high`:o.priority=`high`}break;case`httponly`:o.httpOnly=!0;break;case`secure`:o.secure=!0;break;case`partitioned`:o.partitioned=!0;break;case`samesite`:if(a===void 0)break;switch(a.toLowerCase()){case`lax`:o.sameSite=`lax`;break;case`strict`:o.sameSite=`strict`;break;case`none`:o.sameSite=`none`}}}return Object.assign(Object.create(eg),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}const Jh=/*#__PURE__*/ Gh([]),Yh=e=>$ee(e.cookies),Xh=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Zh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Qh=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,$h=/^[\u0020-\u003a\u003c-\u007e]+$/,eg={[zh]:zh,...ar,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}};function tg(e,t,n){let r=encodeURIComponent(t),i=ng(e,r,n);return i===void 0?ka(Object.assign(Object.create(eg),{name:e,value:t,valueEncoded:r,options:n})):Aa(i)}function ng(e,t,n){if(!Zh.test(e))return Hh.fromReason(`InvalidCookieName`);if(t&&!Xh.test(t))return Hh.fromReason(`InvalidCookieValue`);if(n?.domain!==void 0&&!Qh.test(n.domain))return Hh.fromReason(`InvalidCookieDomain`);if(n?.path!==void 0&&!$h.test(n.path))return Hh.fromReason(`InvalidCookiePath`);if(n?.maxAge!==void 0&&!lo(ao(n.maxAge)))return Hh.fromReason(`CookieInfinityMaxAge`)}const rg=/*#__PURE__*/ j(2,(e,t)=>Wh({...e.cookies,...t.cookies})),ig=/*#__PURE__*/ j(e=>Rh(e[0]),(e,t,n,r)=>Ia(tg(t,n,r),n=>Wh(nte(e.cookies,t,n))));function ag(e){let t=ng(e.name,e.valueEncoded,e.options);if(t!==void 0)throw t;let n=e.name+`=`+e.valueEncoded;if(e.options===void 0)return n;let r=e.options;if(r.maxAge!==void 0){let e=Tte(ao(r.maxAge));n+=`; Max-Age=`+Math.trunc(e)}if(r.domain!==void 0&&(n+=`; Domain=`+r.domain),r.path!==void 0&&(n+=`; Path=`+r.path),r.priority!==void 0)switch(r.priority){case`low`:n+=`; Priority=Low`;break;case`medium`:n+=`; Priority=Medium`;break;case`high`:n+=`; Priority=High`}if(r.expires!==void 0&&(n+=`; Expires=`+r.expires.toUTCString()),r.httpOnly&&(n+=`; HttpOnly`),r.secure&&(n+=`; Secure`),r.partitioned&&(n+=`; Partitioned`),r.sameSite!==void 0)switch(r.sameSite){case`lax`:n+=`; SameSite=Lax`;break;case`strict`:n+=`; SameSite=Strict`;break;case`none`:n+=`; SameSite=None`}return n}const og=e=>Object.values(e.cookies).map(e=>`${e.name}=${e.valueEncoded}`).join(`; `),sg=e=>{let t={},n=Object.values(e.cookies);for(let e=0;e<n.length;e++){let r=n[e];dr(t,r.name,r.value)}return t},cg=e=>Object.values(e.cookies).map(ag);function lg(e){let t={},n=e.length,r=0,i=0;for(;i!==n;){i=e.indexOf(`;`,r),i===-1&&(i=n);let a=e.indexOf(`=`,r);if(a===-1)break;if(a>i){r=i+1;continue}let o=e.substring(r,a++).trim();if(!Object.hasOwn(t,o)){let n=e.charCodeAt(a)===34?e.substring(a+1,i-1).trim():e.substring(a,i).trim();dr(t,o,n.indexOf(`%`)===-1?n:ug(n))}r=i+1}return t}const ug=e=>{try{return decodeURIComponent(e)}catch{return e}},dg=/*#__PURE__*/ new WeakMap,fg=e=>{if(dg.has(e))return dg.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},pg=`~effect/Redacted`,mg=e=>N(e,pg),hg=(e,t)=>{let n=Object.create(gg);return t?.label&&(n.label=t.label),dg.set(n,e),n},gg={[pg]:{_A:e=>e},label:void 0,...Sr,toJSON(){return this.toString()},toString(){return`<redacted${Ut(this.label)?`:`+this.label:``}>`},[ln](){return un(dg.get(this))},[En](e){return mg(e)&&Dn(dg.get(this),dg.get(e))}},_g=fg,vg=e=>pi((t,n)=>e(_g(t),_g(n))),yg=/*#__PURE__*/ Symbol.for(`~effect/http/Headers`),bg=/*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null),{[yg]:{value:yg},[Bn]:{value(e){return jg(this,va(e,Ng))}},toJSON:{value(){return Hn(this)}},[En]:{value(e){return Sg(this,e)}},[ln]:{value(){return vn(this)}},toString:{value:ar.toString},[rr]:{value:ar[rr]}}),xg=e=>Object.assign(Object.create(bg),e),Sg=/*#__PURE__*/ ite(/*#__PURE__*/ mi()),Cg=/*#__PURE__*/ Object.create(bg),wg=e=>{if(e===void 0)return Cg;if(Symbol.iterator in e){let t=Object.create(bg);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(bg);for(let[n,r]of Object.entries(e))Array.isArray(r)?t[n.toLowerCase()]=r.join(`, `):r!==void 0&&(t[n.toLowerCase()]=r);return t},Tg=e=>Object.setPrototypeOf(e,bg),Eg=/*#__PURE__*/ j(3,(e,t,n)=>{let r=xg(e);return r[t.toLowerCase()]=n,r}),Dg=/*#__PURE__*/ j(2,(e,t)=>xg({...e,...wg(t)})),Og=/*#__PURE__*/ j(2,(e,t)=>{let n=xg(e);return Object.assign(n,t),n}),kg=/*#__PURE__*/ j(2,(e,t)=>{let n=xg(e);return delete n[t.toLowerCase()],n}),Ag=/*#__PURE__*/ j(2,(e,t)=>{let n=xg(e);for(let e of t)delete n[e.toLowerCase()];return n}),jg=/*#__PURE__*/ j(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=hg(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=hg(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),Mg=(e,t)=>{let n=e.toLowerCase();for(let r=0;r<t.length;r++){let i=t[r];if(typeof i==`string`){if(i.toLowerCase()===n)return!0}else if(e.search(i)!==-1)return!0}return!1},Ng=/*#__PURE__*/ Ea(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Pg=e=>typeof e==`string`?e:_g(e),Fg=`~effect/http/UrlParams`,Ig=e=>N(e,Fg),Lg={...Sr,[Fg]:Fg,[Symbol.iterator](){return this.params[Symbol.iterator]()},[Bn](e){return{_id:`UrlParams`,params:Object.fromEntries(Jg(this,va(e,i_)))}},toJSON(){return Hn(this)},[En](e){return Hg(this,e)},[ln](){return bn(this.params.flat())}},Rg=e=>{let t=Object.create(Lg);return t.params=e,t},zg=e=>{if(Ig(e))return e;let t=Bg(e),n=[];for(let e=0;e<t.length;e++)if(Array.isArray(t[e][0])){let[r,i]=t[e];n.push([`${r[0]}[${r.slice(1).join(`][`)}]`,i])}else n.push(t[e]);return Rg(n)},Bg=e=>{let t=typeof e[Symbol.iterator]==`function`?Ba(e):Object.entries(e),n=[];for(let[e,r]of t)if(Array.isArray(r))for(let t=0;t<r.length;t++)r[t]!==void 0&&n.push([e,Vg(r[t])]);else if(typeof r==`object`&&r&&!mg(r)){let t=Bg(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,Vg(r)]);return n},Vg=e=>mg(e)?e:String(e),Hg=/*#__PURE__*/ pi((e,t)=>Ug(e.params,t.params)),Ug=/*#__PURE__*/ ute(/*#__PURE__*/ Xee([/*#__PURE__*/ mi(),/*#__PURE__*/ zn()])),Wg=/*#__PURE__*/ Rg([]),Gg=/*#__PURE__*/ j(2,(e,t)=>{let n=zg(t).params.slice(),r=/* @__PURE__ */ new Set;for(let e=0;e<n.length;e++)r.add(n[e][0]);for(let t=0;t<e.params.length;t++)r.has(e.params[t][0])||n.push(e.params[t]);return Rg(n)}),Kg=e=>new URLSearchParams(zg(e).params.map(([e,t])=>[e,Pg(t)])).toString(),qg=e=>{let t={};for(let[n,r]of e.params){let e=Pg(r);if(!Object.hasOwn(t,n))dr(t,n,e);else{let r=t[n];typeof r==`string`?dr(t,n,[r,e]):r.push(e)}}return t},Jg=/*#__PURE__*/ j(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Yg(e,n)?hg(t):t])}),Yg=Mg,Xg=(e,t=r_())=>{e.includes(`@`)&&(e=e_(e));let n=e.indexOf(`?`);if(n===-1||t.length===0)return e;let r=e.indexOf(`#`);if(r!==-1&&r<n)return e;let i=r===-1?e.length:r;return e.slice(0,n+1)+t_(e.slice(n+1,i),t)+e.slice(i)},Zg=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,Qg=/[/\\?#]/,$g=/[/?#]/,e_=e=>{let t=``,n=[];for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===9||i===10||i===13||t===``&&i<=32||(t+=e[r],n.push(r))}let r=Zg.exec(t);if(r===null)return e;let i=r[0].length,a=r[1]!==void 0||!r[0].includes(`:`),o=t.slice(i),s=o.search(a?Qg:$g),c=(s===-1?o:o.slice(0,s)).lastIndexOf(`@`);return c===-1?e:e.slice(0,n[i])+`REDACTED:REDACTED`+e.slice(n[i+c])},t_=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Yg(n_(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),n_=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},r_=()=>va(globalThis[`~effect/Fiber/currentFiber`]?.context??la(),i_),i_=/*#__PURE__*/ Ea(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function a_(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function o_(e){return t=>a_(t)?.[e]}const s_=`~structural`,c_=`~identifier`,l_=`~sentinels`,u_=`~constructor`,d_=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],f_=/*#__PURE__*/ o_(`identifier`),p_=/*#__PURE__*/ o_(c_),m_=/*#__PURE__*/ o_(`description`),h_=/*#__PURE__*/ Lt(e=>{let t=a_(e)?.identifier;return typeof t==`string`?t:e.getExpected(h_)}),g_=/*#__PURE__*/ new Set([l_,s_,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),__=/*#__PURE__*/ Symbol(),v_=xd,y_=/*#__PURE__*/ v_(__),b_=/*#__PURE__*/ v_(__),x_=e=>e===__?Ni():Pi(e),S_=e=>e._tag===`None`?y_:v_(e.value),C_=`~effect/SchemaIssue/Issue`;function w_(e){return N(e,C_)&&e[C_]===C_}function T_(e){return Object.hasOwn(e,`input`)}var E_=class{[C_]=C_;constructor(e,t){t?.reportInput===!0&&e!==__&&(this.input=e)}};const D_=class extends E_{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},O_=class extends E_{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},k_=class extends E_{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},A_=class extends E_{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},j_=class extends E_{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},M_=class extends E_{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},N_=class extends E_{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},P_=class extends E_{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function F_(e,t,n,r,i){return new M_(e,[new k_([t],n)],r,i)}const I_=class extends E_{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},L_=class extends E_{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},R_=class extends E_{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function z_(e,t,n){if(w_(e))return e;if(typeof e==`string`)return new P_({message:e},t,n);let r=typeof e.issue==`string`?new P_({message:e.issue},t,n):e.issue;return new k_(e.path,r)}function B_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new P_(void 0,t,n):z_(e,t,n)}function V_(e,t,n,r){return Array.isArray(t)?Wa(t)?t.length===1?z_(t[0],n,r):new M_(e,qa(t,e=>z_(e,n,r)),n,r):void 0:B_(t,n,r)}const H_=e=>{let t=$_(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return q_(h_(e.ast),e);case`InvalidValue`:{let t=K_(e);if(t!==void 0)return q_(t,e);let n=G_(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=G_(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=G_(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},U_=e=>$_(e.issue)??$_(e);function W_(e){return t=>({issues:J_(t,[],e?.leafHook??H_,e?.checkHook??U_)})}function G_(e){return T_(e)?qn(e.input):void 0}function K_(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function q_(e,t){let n=G_(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function J_(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];if(e.issue._tag!==`InvalidValue`)return J_(e.issue,t,n,r);let a=K_(e.issue);return[{path:t,message:a===void 0?q_(Y_(e.filter),e):q_(a,e.issue)}]}case`Encoding`:return J_(e.issue,t,n,r);case`Pointer`:return J_(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>J_(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:$_(e)??q_(h_(e.ast),e)}]:e.issues.flatMap(e=>J_(e,t,n,r));default:return[{path:t,message:n(e)}]}}function Y_(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>Y_(e)).join(` & `)}}function X_(){return e=>Q_(e,``)}const Z_=/*#__PURE__*/ X_();function Q_(e,t){let n;switch(e._tag){case`Filter`:{let r=U_(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return Q_(e.issue,t);let r=K_(e.issue);n=r===void 0?q_(Y_(e.filter),e):q_(r,e.issue)}break}case`Encoding`:return Q_(e.issue,t);case`Pointer`:return Q_(e.issue,t+Xn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Q_(e,t)).join(`
16
+ `);n=$_(e)??q_(h_(e.ast),e);break;default:n=H_(e)}return t?`${n}\n at ${t}`:n}function $_(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return $_(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function ev(e){let t;for(let n of e.reasons){if(!Yu(n)||!w_(n.error))return;t??=n.error}return t}function tv(e,t){let n=ev(e);if(n===void 0)throw Error(t,{cause:e});return n}const nv=(e,t,n)=>{switch(e._tag){case`Passthrough`:return F(t);case`Transform`:return F(Ui(t,e.transform));case`TransformOptional`:return F(e.transform(t));case`TransformEffect`:return Fi(t)?ip:Om(e.transform(t.value,n),Pi);case`TransformOptionalEffect`:return e.transform(t,n)}},rv=e=>Object.assign(Object.create(kt),e),iv=(e,t)=>mv((n,r)=>jm(nv(e,n,r),e=>nv(t,e,r))),av=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Passthrough`)return t;if(t._tag===`Passthrough`)return e;switch(e._tag){case`Transform`:switch(t._tag){case`Transform`:return dv(n=>t.transform(e.transform(n)));case`TransformOptional`:return pv(n=>t.transform(Ui(n,e.transform)));case`TransformEffect`:return fv((n,r)=>t.transform(e.transform(n),r));case`TransformOptionalEffect`:return iv(e,t)}case`TransformOptional`:switch(t._tag){case`Transform`:return pv(n=>Ui(e.transform(n),t.transform));case`TransformOptional`:return pv(n=>t.transform(e.transform(n)));case`TransformEffect`:case`TransformOptionalEffect`:return iv(e,t)}case`TransformEffect`:switch(t._tag){case`Transform`:return fv((n,r)=>Om(e.transform(n,r),t.transform));case`TransformOptional`:case`TransformOptionalEffect`:return iv(e,t);case`TransformEffect`:return fv((n,r)=>jm(e.transform(n,r),e=>t.transform(e,r)))}case`TransformOptionalEffect`:return iv(e,t)}});function ov(e){return mv((t,n)=>z(e(t,n)))}function sv(e){return ov((t,n)=>{let r={message:e(t)};return Ii(t)?new I_(r,t.value,n):new I_(r)})}const cv=/*#__PURE__*/ sv(()=>`Encoding is not supported`),lv=/*#__PURE__*/ rv({_tag:`Passthrough`});function uv(){return lv}function dv(e){return rv({_tag:`Transform`,transform:e})}function fv(e){return rv({_tag:`TransformEffect`,transform:e})}function pv(e){return rv({_tag:`TransformOptional`,transform:e})}function mv(e){return rv({_tag:`TransformOptionalEffect`,transform:e})}function hv(e){return mv(t=>{let n=Gi(t,Xt);return Ii(n)?F(n):Om(e,Pi)})}function gv(){return dv(globalThis.String)}function _v(){return dv(globalThis.Number)}function vv(){return dv(jre)}function aie(e){return fv((t,n)=>dp({try:()=>JSON.parse(t,e?.reviver),catch:()=>new P_({expected:`a valid JSON string`},t,n)}))}function oie(e){return fv((t,n)=>dp({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new P_({expected:`a JSON-serializable value`},t,n)}))}function sie(e){let t=e?.separator??`,`;return dv(e=>e===``?[]:e.split(t))}function cie(){return dv(Dh)}function lie(){return fv((e,t)=>km(pp(Oh(e)),()=>new P_({expected:`a valid Base64 string`},e,t)))}const uie=class extends At{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new uie(this.encode,this.decode)}},yv=`~effect/SchemaTransformation/Transformation`,bv=class extends At{[yv]=yv;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new bv(this.encode,this.decode)}};function die(e){return N(e,yv)&&e[yv]===yv}const xv=e=>die(e)?e:new bv(e.decode,e.encode);function Sv(e){return new bv(fv(e.decode),fv(e.encode))}function Cv(e){return new bv(dv(e.decode),dv(e.encode))}function fie(){return new bv(vv(),uv())}const pie=/*#__PURE__*/ new bv(/*#__PURE__*/ uv(),/*#__PURE__*/ uv());function wv(){return pie}const Tv=/*#__PURE__*/ new bv(/*#__PURE__*/ _v(),/*#__PURE__*/ gv()),mie=e=>nn(e)&&typeof e.message==`string`,hie=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:Ev(e.cause)}):Error(e.message);return typeof e.name==`string`&&e.name!==`Error`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t},gie=e=>{try{let t=er(e);return t===void 0?qn(e):JSON.parse(t)}catch{return qn(e)}},_ie=(e,t,n)=>{let r={name:e.name,message:typeof e.message==`string`?e.message:``};return t?.includeStack&&typeof e.stack==`string`&&(r.stack=e.stack),!t?.excludeCause&&e.cause!==void 0&&(r.cause=n(e.cause)),r},vie=e=>{let t=/* @__PURE__ */ new WeakSet,n=r=>{if(sn(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=_ie(r,e,n);return t.delete(r),i}return gie(r)};return n},Ev=e=>mie(e)?hie(e):e,yie=e=>Cv({decode:Ev,encode:vie(e)}),Dv=/*#__PURE__*/ new bv(/*#__PURE__*/ lie(),/*#__PURE__*/ cie());function bie(e){return new bv(aie(e??{}),oie(e))}function Ov(e){return t=>t._tag===e}const kv=/*#__PURE__*/ Ov(`Declaration`),xie=/*#__PURE__*/ Ov(`Null`),Sie=/*#__PURE__*/ Ov(`Undefined`),Av=/*#__PURE__*/ Ov(`Void`),Cie=/*#__PURE__*/ Ov(`Never`),jv=/*#__PURE__*/ Ov(`Literal`),Mv=/*#__PURE__*/ Ov(`UniqueSymbol`),wie=/*#__PURE__*/ Ov(`Enum`),Nv=/*#__PURE__*/ Ov(`Arrays`),Pv=/*#__PURE__*/ Ov(`Objects`),Fv=/*#__PURE__*/ Ov(`Union`),Iv=/*#__PURE__*/ Ov(`Suspend`),Lv=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Rv={},zv=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Bv=`~effect/Schema`;var Vv=class{[Bv]=Bv;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}};const Hv=class extends Vv{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>t===__?y_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=Zy(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Hv(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},Uv=/*#__PURE__*/ new class extends Vv{_tag=`Null`;getParser(){return sb(this,null)}getExpected(){return`null`}},Tie=class extends Vv{_tag=`Undefined`;getParser(){return sb(this,void 0)}toCodecJson(){return By(this,[Wv])}getExpected(){return`undefined`}},Wv=/*#__PURE__*/ new Lv(Uv,/*#__PURE__*/ new bv(/*#__PURE__*/ dv(()=>void 0),/*#__PURE__*/ dv(()=>null))),Gv=/*#__PURE__*/ new Tie,Eie=/*#__PURE__*/ new class extends Vv{_tag=`Void`;getParser(){let e=v_(void 0);return t=>t===__?y_:e}toCodecJson(){return By(this,[Wv])}getExpected(){return`void`}},Die=/*#__PURE__*/ new class extends Vv{_tag=`Never`;getParser(){return cb(this,en)}getExpected(){return`never`}},Oie=/*#__PURE__*/ new class extends Vv{_tag=`Any`;getParser(){return cb(this,tn)}getExpected(){return`any`}},Kv=/*#__PURE__*/ new class extends Vv{_tag=`Unknown`;getParser(){return cb(this,tn)}getExpected(){return`unknown`}};function qv(e){return typeof e==`number`?`parts[${e}]`:e}function Jv(e,t,n){if(n.has(e))return!0;if(e.encoding)throw Error(`TemplateLiteral parts cannot have an encoding at ${qv(t)}`);let r;switch(e._tag){case`String`:case`Number`:case`BigInt`:r=!0;break;case`Literal`:r=!e.checks;break;case`TemplateLiteral`:{let i=qv(t);r=!e.checks&&e.parts.every((e,t)=>Jv(e,`${i}.parts[${t}]`,n));break}case`Union`:{let i=qv(t);r=!e.checks&&e.types.every((e,t)=>Jv(e,`${i}.types[${t}]`,n));break}default:return!1}return r&&n.add(e),r}const kie=class extends Vv{_tag=`TemplateLiteral`;parts;encodedParts;literals;suffixLengths;constructor(e,t,n,r,i){super(t,n,r,i);let a=[],o=[],s=/* @__PURE__ */ new Set;for(let t=0;t<e.length;t++){let n=e[t];if(!Jv(n,t,s))throw Error(`Invalid TemplateLiteral part ${n._tag}`);a.push(n),o.push(n._tag===`Literal`?globalThis.String(n.literal):void 0)}let c=Array(a.length+1);c[a.length]=0;for(let e=a.length-1;e>=0;e--)c[e]=c[e+1]+(o[e]?.length??0);this.parts=e,this.encodedParts=a,this.literals=o,this.suffixLengths=c}getParser(e){let t=new ey(!1,this.parts.map(fb),[]),n=e(eb(Zv,t,Aie(this)));return(e,t)=>{if(e===__)return y_;let r=n(e,t);return r._tag===`Success`?b_:Am(r,{onSuccess:()=>e,onFailure:n=>new M_(this,[n],e,t)})}}getExpected(){return`string`}matchPart(e,t){return lb(this,e,t)===void 0?void 0:e}};function Aie(e){return new bv(fv((t,n)=>{let r=lb(e,t,n);return r?F(r):z(new P_({expected:`a string matching template literal parts`},t,n))}),dv(e=>e.join(``)))}const Yv=class extends Vv{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${qn(e)}`);this.literal=e}getParser(){return sb(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Xv(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Xv(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Xv(e){let t=globalThis.String(e.literal);return By(e,[new Lv(new Yv(t),new bv(dv(()=>e.literal),dv(()=>t)))])}const Zv=/*#__PURE__*/ new class extends Vv{_tag=`String`;getParser(){return cb(this,Ut)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&hb(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},jie=class extends Vv{_tag=`Number`;getParser(){return cb(this,Wt)}matchKey(e,t){return this._match(tae,e,t)}matchPart(e,t){return this._match(pb,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:hb(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Qv(this.checks,`effect/schema/isFinite`)||Qv(this.checks,`effect/schema/isInt`))?this:By(this,[Uie])}toCodecStringTree(){return this.toCodecJson()===this?By(this,[rae]):By(this,[iae])}getExpected(){return`number`}};function Qv(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Qv(e.checks,t))}const $v=/*#__PURE__*/ new jie,Mie=/*#__PURE__*/ new class extends Vv{_tag=`Boolean`;getParser(){return cb(this,Gt)}getExpected(){return`boolean`}},ey=class extends Vv{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(tb(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(tb(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new j_(n,t[o],i),a=new k_([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return z(new M_(n,[a],t,i))}return e.issues?z(new M_(n,e.issues,t,i)):v_(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:new globalThis.Array(r),issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:eu(t.concurrency),f=d===1?Pie(i,e,0,u):Fie(i,e,{concurrency:d,end:u});if(!f)return c(i);if(zc(f))return jm(f,()=>c(i));let p=!0;return ap(()=>p?(p=!1,B(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===__)return y_;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):z(new N_(n,e,a))}catch(e){return up(e)}}}_rebuild(e,t,n){let r=Zy(this.elements,e),i=Zy(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new ey(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function Nie(e,t,n,r){if(n._tag===`Failure`)return ny(e,e.ast,r,n);let i=n===b_?t:n[gr];if(i!==__)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(tb(t.ast))return;let n=new k_([r],new A_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Cd(new M_(e.ast,[n],e.input,e.options))}}const ty={onItem(e,t,n){let r=n<e.len?t:__;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Nie},Pie=/*#__PURE__*/ tu()(ty),Fie=/*#__PURE__*/ ru()(ty),ny=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=ev(r.cause);if(i===void 0)return Sd(rd(r.cause,r=>new M_(t,[new k_([n],r)],e.input,e.options)));let a=new k_([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Cd(new M_(t,[a],e.input,e.options))},ry=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function iy(e,t,n=Rv){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(ub(ib(t)))}const ay=class{name;type;constructor(e,t){this.name=e,this.type=t}};function oy(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(oy);default:return!1}}function sy(e){let t=Hy(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(sy);default:return!1}}function Iie(e){return oy(e)&&sy(e)}const cy=class{parameter;type;constructor(e,t){if(!Iie(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,tb(t)&&!ob(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},ly=class extends Vv{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return cb(n,$t);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(ub(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return ny(t,n,i,s)??Ed;let c=s===b_?o:s[gr];if(a!==__&&c!==__){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Ed;dr(t.out,a,c)}return Ed},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!zc(t))return B(_p(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return ny(e,n,r,a)??Ed;let o=a===b_?r:a[gr],s=e.input[r],l=i.parserValue(s,e.options);return zc(l)?t(e,r,o,s,l):B(_p(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return zc(a)?t(e,n,n,i,a):B(_p(a),r=>t(e,n,n,i,r))},u=i?ru()({onItem:(e,[t,n])=>n.is.parameter===Zv?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return Nm(function*(t,d){if(t===__)return __;if(typeof t!=`object`||!t||Array.isArray(t))return yield*z(new N_(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},h=d.errors===`all`,g=d.onExcessProperty===`error`,_=d.concurrency===void 0?1:eu(d.concurrency),v=i&&g?n.indexSignatures.map(e=>iy(f,e.parameter,d)):void 0;if(g){let r=v?new Set(e):e;if(v)for(let e of v)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new j_(n,f[a],d),r=new k_([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*z(new M_(n,[r],t,d))}}}if(r){let e=_===1?fy(m,a):Lie(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Zv?l:c,r=v?.[e]??(t.is.parameter===Zv?Object.keys(f):iy(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!zc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Ga();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===Zv?Object.keys(f):iy(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:_});t&&(yield*t)}return m.issues?yield*z(new M_(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return B(_p(n),n=>{let i=uy(e,r,n);if(i)return i;let o=()=>v_(e.out),s=fy(e,a.slice(t+1));return s?jm(s,o):o()})};return(e,t)=>{if(e===__)return y_;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&eu(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return z(new N_(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=wy(i,s),l=c?i[s]:__,d=n.parser(l,t);if(!zc(d))return u(o,e,d);if(d===b_){c&&dr(a,s,l);continue}let f=uy(o,n,d);if(f)return f}}catch(e){return up(e)}return v_(a)}}_rebuild(e,t,n,r){let i=Zy(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new ay(t.name,n)}),a=Zy(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new cy(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new ly(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function uy(e,t,n){if(n._tag===`Failure`)return ny(e,e.ast,t.name,n);if(n===b_)return;let r=n[gr];if(r!==__)dr(e.out,t.name,r);else if(delete e.out[t.name],!tb(t.type)){let n=new k_([t.name],new A_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Cd(new M_(e.ast,[n],e.input,e.options))}}const dy={onItem(e,t){if(!wy(e.input,t.name))return t.parser(__,e.options);let n=e.input[t.name];return dr(e.out,t.name,n),t.parser(n,e.options)},step:uy},fy=/*#__PURE__*/ tu()(dy),Lie=/*#__PURE__*/ ru()(dy);function py(e,t){return e?t?[...e,...t]:e:t}function my(e,t,n){return new ly(Reflect.ownKeys(e).map(t=>new ay(t,e[t].ast)),[],n,t)}function hy(e){return e.ast}function gy(e,t=void 0){return new ey(!1,e.map(e=>e.ast),[],void 0,t)}function _y(e,t,n){return new Ty(e.map(hy),t,void 0,n)}function Rie(e,t){if(e.encoding||t.some(e=>e.encoding))throw Error(`StructWithRest does not support encodings`);let n=e.propertySignatures,r=e.indexSignatures,i=e.checks;for(let e of t){for(let t of e.propertySignatures)if(n.some(e=>e.name===t.name))throw Error(`Duplicate identifier: ${JSON.stringify(t.name)}. ts(2300)`);n=n.concat(e.propertySignatures),r=r.concat(e.indexSignatures),i=py(i,e.checks)}return new ly(n,r,void 0,i)}const vy=/*#__PURE__*/ Rt(e=>{for(;;){if(Iv(e))return Kv;let t=e.encoding;if(!t)return e.recur?.(vy,M)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==M))return Kv;e=t[t.length-1].to}});function yy(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(yy)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function by(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[l_];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!tb(t)){if(jv(t))return[{key:e.name,literal:t.literal}];if(Mv(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!tb(e)){if(jv(e))return[{key:t,literal:e.literal}];if(Mv(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>by(vy(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return by(e.thunk())}}const xy=/*#__PURE__*/ new WeakMap,Sy=/*#__PURE__*/ Object.freeze([]),Cy=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,wy=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function zie(e){let t=xy.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=vy(c);if(Cie(l))continue;if(jv(l)||Mv(l)){a??=/* @__PURE__ */ new Map;let e=jv(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=by(l);if(u.length){n??=/* @__PURE__ */ new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[/* @__PURE__ */ new Map,/* @__PURE__ */ new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=/* @__PURE__ */ new Set),a.add(t)}}else{i??={};let e=yy(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Sy);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Sy;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=/* @__PURE__ */ new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(an(e)){let n=wy(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Sy;if(t)return o}return Sy}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=Cy(t);if(!an(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=wy(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=wy(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=wy(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(Cy(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return xy.set(e,t),t}const Ty=class extends Vv{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===__)return y_;let i=(o??=zie(n.types))(e,r);if(i.length===0)return z(new L_(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:zc(r)?Ey(n,r.cause,e,t):Bie(n,r,e,t)}return Dy(n,a,i,e,t)}}_rebuild(e,t,n){let r=Zy(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Ty(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=ib(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(jv);if(t.length>0)return`${Ay(n.isMutable)}[ ${t.map(t=>e(t)+jy(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>jv(e.type));if(t.length>0)return`{ ${t.map(t=>`${Ay(t.type.context?.isMutable)}${Yn(t.name)}${jy(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Ey(e,t,n,r){let i=ev(t);return i?Cd(new L_(e,[i],n,r)):Sd(t)}function Bie(e,t,n,r){return Sp(t,t=>Ey(e,t,n,r))}function Dy(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=Vie(a,n);if(!o)return a.out?a.out:z(new L_(e,a.issues??[],r,i));if(zc(o))return Oy(o,a);let s=!0;return ap(()=>s?(s=!1,Oy(o,a)):Dy(e,t,n,r,i))}function Oy(e,t){return jm(e,e=>t.out===b_?F(t.input):t.out?t.out:z(new L_(t.ast,t.issues??[],t.input,t.options)))}const Vie=/*#__PURE__*/ tu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=ev(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),Cd(new R_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Ed}}}),ky=/*#__PURE__*/ new Ty([/*#__PURE__*/ new Yv(`Infinity`),/*#__PURE__*/ new Yv(`-Infinity`),/*#__PURE__*/ new Yv(`NaN`)]);function Ay(e){return e?``:`readonly `}function jy(e){return e?`?`:``}const My=class extends At{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new My(this.run,{...this.annotations,...e},this.aborted)}abort(){return new My(this.run,this.annotations,!0)}and(e,t){return new Ny([this,e],t)}},Ny=class extends At{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Ny(this.checks,{...this.annotations,...e})}and(e,t){return new Ny([this,e],t)}};function Py(e,t,n=!1){return new My((t,n,r)=>V_(n,e(t,n,r),t,r),t,n)}function Hie(e){return Py(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}const Fy=/*#__PURE__*/ Gy($v,[/*#__PURE__*/ Hie()]),Uie=/*#__PURE__*/ new Lv(/*#__PURE__*/ new Ty([Fy,ky]),/*#__PURE__*/ new bv(/*#__PURE__*/ _v(),/*#__PURE__*/ dv(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Iy(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Py(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}const Ly=/*#__PURE__*/ new WeakMap;function Ry(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Ly.set(n,zy(e)),n}function zy(e){let t=Ly.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Ly.set(e,n),n}function By(e,t){return e.encoding===t?e:Ry(e,{encoding:t})}function Vy(e,t){if(e.context===t)return e;let n=zy(e);return n.context===t&&n.encoding===e.encoding?n:Ry(e,{context:t})}function Hy(e){return e.encoding?Hy(e.encoding[e.encoding.length-1].to):e}function Uy(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Wy(e,Ha(e.checks.slice(0,-1),n.annotate(t)))}return Ry(e,{annotations:{...e.annotations,...t}})}function Wy(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Ry(e,{checks:t})}function Gy(e,t){return Wy(e,py(e.checks,t))}function Ky(e,t){let n=t(e.to);return n===e.to?e:new Lv(n,e.transformation)}function qy(e,t){let n=e,r=n[n.length-1],i=Ky(r,t);return i===r?e:Ha(e.slice(0,e.length-1),i)}function Jy(e){return t=>t.encoding?By(t,qy(t.encoding,e)):t}function Yy(e,t){return Jy(e=>Vy(e,t))(e)}function Wie(e){function t(n){return n.encoding?By(n,qy(n.encoding,t)):e(n)}return Lt(t)}function Xy(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:By(r,qy(r.encoding,n))}return e(r)}return Rt(n)}function Gie(e,t,n){let r=new Lv(e,t);return By(n,n.encoding?[...n.encoding,r]:[r])}function Zy(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function Qy(e,t){return Vy(e,e.context?new zv(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new zv(!1,!1,void 0,t))}const $y=/*#__PURE__*/ Rt(e=>{let t=e.context?e.context.isOptional===!1?new zv(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new zv(!0,!1);return Kie(Vy(e,t))}),Kie=/*#__PURE__*/ Jy($y),qie=/*#__PURE__*/ Lt(e=>$y(new Ty([e,Gv])));function Jie(e,t){return Vy(e,e.context?new zv(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new zv(!1,!1,t))}function eb(e,t,n){return Gie(e,n,t)}function Yie(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:qt(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function Xie(e,t){let{literals:n,parameters:r}=Yie(e);return new ly(n.map(e=>new ay(e,t)),r.map(e=>new cy(e,t)))}function tb(e){return e.context?.isOptional??!1}function Zie(e){return e.context?.isMutable??!1}function nb(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(nb)}function Qie(e){function t(e){return nb(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Ua(n)?n:void 0}function $ie(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Iv(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}const rb=/*#__PURE__*/ Rt(e=>{let t=zy(e);if(t!==e){let n=rb(t);return n===t&&e.encoding===void 0?e:Vy(n,e.context)}let n=`recur`in e?e.recur(rb):e;if(`encodingChecks`in n&&n.encodingChecks){let t=$ie(e)?n.encodingChecks:Nv(n)||Pv(n)||kv(n)&&n.typeParameters.length>0?Qie(n.encodingChecks):void 0;return Ry(n,{encodingChecks:void 0,checks:py(n.checks,t)})}return n}),ib=/*#__PURE__*/ Rt(e=>rb(ab(e)));function eae(e,t){let n=t,r=n.length,i=n[r-1],a=[new Lv(ab(By(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Lv(ab(n[e-1].to),n[e].transformation.flip()));let o=ab(i.to);return o.encoding?By(o,[...o.encoding,...a]):By(o,a)}const ab=/*#__PURE__*/ Lt(e=>{if(e.encoding)return eae(e,e.encoding);let t=zy(e);if(t!==e){let n=ab(t);return n===t?e:Vy(n,e.context)}return`flip`in e?e.flip(ab):`recur`in e?e.recur(ab):e});function ob(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(ob);default:return!1}}function sb(e,t){let n=t===0?b_:v_(t);return(r,i)=>r===__?y_:r===t?n:z(new N_(e,r,i))}function cb(e,t){return(n,r)=>n===__?y_:t(n)?b_:z(new N_(e,n,r))}function lb(e,t,n){let r=e.encodedParts,i=e.literals,a=t.length;for(let e=0;e<i.length;e++){let n=i[e];if(n&&!t.includes(n))return}if(e.suffixLengths[0]>a)return;let o=Array(r.length),s;function c(l,u){if(l===r.length)return u===a;if(s?.has(l*(a+1)+u))return!1;let d=r[l];if(l===r.length-1){let e=t.slice(u);if(d.matchPart(e,n)!==void 0)return o[l]=e,!0}else if(d._tag===`Literal`){let e=i[l];if(t.startsWith(e,u)&&c(l+1,u+e.length))return o[l]=e,!0}else{let r=a-e.suffixLengths[l+1],s=i[l+1],f=s===void 0?r:t.lastIndexOf(s,r);for(;f>=u;){let e=t.slice(u,f);if(d.matchPart(e,n)!==void 0&&c(l+1,f))return o[l]=e,!0;if(f===0)break;f=s===void 0?f-1:t.lastIndexOf(s,f-1)}}return s??=/* @__PURE__ */ new Set,s.add(l*(a+1)+u),!1}return c(0,0)?o:void 0}const ub=/*#__PURE__*/ Xy(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(ub)}}),db=/*#__PURE__*/ Xy(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(db)}}),fb=/*#__PURE__*/ Xy(e=>{switch(e._tag){default:return e;case`Number`:case`Literal`:case`BigInt`:return e.toCodecStringTree();case`Union`:return e.recur(fb)}}),pb=/*#__PURE__*/ new globalThis.RegExp(`^${ry}$`),tae=/*#__PURE__*/ new globalThis.RegExp(`^(?:${ry}|Infinity|-Infinity|NaN)$`);function nae(e){return Iy(pb,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:pb.source}),...e})}const mb=/*#__PURE__*/ Gy(Zv,[/*#__PURE__*/ nae()]),rae=/*#__PURE__*/ new Lv(mb,Tv),iae=/*#__PURE__*/ new Lv(/*#__PURE__*/ new Ty([mb,ky]),Tv);function hb(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=hb(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new D_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function aae(e){if(!kv(e))return;let t=e.annotations?.[u_];return Jt(t)?t(e.typeParameters):void 0}const gb=o_,_b=f_,oae=m_;function sae(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function cae(e){return e===void 0||typeof e==`string`}function vb(e,t){let n=/* @__PURE__ */ new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function yb(e){return vb(e,sae)}const bb=/*#__PURE__*/ new Hv([],()=>(e,t,n)=>yb(e)?b_:z(new N_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>Sb}),xb=/*#__PURE__*/ new Lv(bb,/*#__PURE__*/ wv()),lae=/*#__PURE__*/ new Lv(/*#__PURE__*/ new Ty([/*#__PURE__*/ new ey(!1,[],[bb]),/*#__PURE__*/ new ly([],[/*#__PURE__*/ new cy(Zv,bb)])]),/*#__PURE__*/ wv());function uae(e){return vb(e,cae)}const Sb=/*#__PURE__*/ new Lv(/* @__PURE__ */ new Hv([],()=>(e,t,n)=>uae(e)?b_:z(new N_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),/*#__PURE__*/ wv()),Cb=(e,t,n)=>e===b_?n(t):jm(e,n);function wb(e){if(e._tag===`Middleware`)return(t,n,r)=>{let i=t===b_?e.decode(v_(x_(n)),r):e.decode(Om(t,x_),r);return Tb(i)};let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===b_?v_(t):e;case`Transform`:{let e=e=>e===__?y_:v_(t.transform(e));return(t,n)=>Cb(t,n,e)}case`TransformOptional`:{let e=e=>S_(t.transform(x_(e)));return(t,n)=>Cb(t,n,e)}case`TransformEffect`:return(e,n,r)=>Cb(e,n,e=>e===__?y_:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>Cb(e,n,e=>Tb(t.transform(x_(e),r)))}}const Tb=e=>jm(e,S_),Eb=(e,t,n,r)=>Sp(r,r=>lp(()=>rd(r,r=>new O_(e,r,t,n))));function dae(e,t){let n=wb(e.link.transformation),r;return(i,a)=>{if(i===__)return y_;if(e.isConstructed(i))return b_;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function fae(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==__&&r!==void 0)return t(r,i);let a=n;if(zc(a)&&a._tag===`Success`){let e=t(a[gr],i);return e===b_?a:e}return jm(Eb(e,r,i,a),e=>{let n=t(e,i);return n===b_?v_(e):n})}}function pae(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:fae(e,n)}function Db(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?aae(e):void 0,o=a?dae(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>wb(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(zc(r)){if(r._tag===`Success`){let i=r===b_?t:r[gr];if(t!==__&&i!==__){let i=hb(u,t,void 0,e,n);i&&(r=z(new M_(e,i,t,n)))}}}else r=B(r,r=>{if(t!==__&&r!==__){let r=hb(u,t,void 0,e,n);if(r)return z(new M_(e,r,t,n))}return F(r)})}if(s&&!n.disableChecks){if(zc(r)){if(r._tag===`Success`){let i=r===b_?t:r[gr];if(i===__)return r;let a=hb(s,i,void 0,e,n);a&&(r=z(new M_(e,a,i,n)))}}else r=B(r,t=>{if(t!==__){let r=hb(s,t,void 0,e,n);if(r)return z(new M_(e,r,t,n))}return F(t)})}return r},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[gr],o=t(a,r)):o=jm(o,e=>{let n=t(e,r);return n===b_?v_(e):n})}if(o._tag===`Success`){let e=o[gr],t=p(e,r);return t===b_?o:t}return o=Eb(e,n,r,o),jm(o,e=>{let t=p(e,r);return t===b_?v_(e):t})}:p}const mae=/*#__PURE__*/ Symbol(),Ob=/*#__PURE__*/ new WeakMap,hae=e=>Ab(e).parser,kb=e=>Ab(e).makeEffect,gae=e=>pae(e,kb);var _ae=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=Db(this.ast,hae)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=Db(this.ast,kb,gae)}};function Ab(e){let t=Ob.get(e);if(t!==void 0)return t;let n=new _ae(e);return Ob.set(e,n),n}function jb(e){let t=e.ast,n;return(e,r)=>(n??=Bb(Oae,rb(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Mb(e){let t=jb(e);return(e,n)=>{let r=vm(t(e,n));return Dd(r)?Pi(r.value):(tv(r.cause,`Option adapter can only return none for schema issues`),Ni())}}function Nb(e){return Eae(rb(e.ast))}function vae(e){return Pb(e.ast)}function yae(e){{let t=Vb(zb(e));return e=>{let n=t(e,Rv);return Dd(n)?!0:(tv(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function Pb(e){let t=rb(e),n=e=>(n=yae(t),n(e));return e=>n(e)}function Fb(e,t){let n=zb(e.ast);return t===void 0?n:(e,r)=>n(e,Lb(t,r))}function bae(e,t){return Cae(Fb(e,t))}function xae(e,t){return wae(Fb(e,t))}function Ib(e,t){let n=zb(ab(e.ast));return t===void 0?n:(e,r)=>n(e,Lb(t,r))}const Lb=(e,t)=>t?{...e,...t}:e,Rb=e=>e===__?z(new P_):F(e);function zb(e){return Bb(Dae,e)}function Sae(e,t){return e===b_?F(t):zc(e)?e[`~effect/Effect/args`]===__?Rb(__):e:jm(e,Rb)}function Bb(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Rv);return a===b_?F(r):zc(a)?a[`~effect/Effect/args`]===__?Rb(__):a:jm(a,Rb)}}function Vb(e){return(t,n)=>vm(e(t,n))}function Cae(e){let t=Vb(e);return(e,n)=>{let r=t(e,n);return Dd(r)?Pi(r.value):(tv(r.cause,`Option adapter can only return none for schema issues`),Ni())}}function wae(e){let t=Vb(e);return(e,n)=>{let r=t(e,n);return Dd(r)?ka(r.value):Aa(tv(r.cause,`Result adapter can only return schema issues`))}}function Tae(e,t){let n=vm(e);if(Dd(n))return n.value;let r=tv(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Eae(e){let t,n;return(r,i)=>{t??=Ab(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Rv,o=t.make;if(o!==void 0&&r!==__){let e;try{e=o(r,a)}catch(e){throw tv(Qu(e),`Constructor adapter can only throw schema issues`),e}if(e!==mae&&e!==__)return e}return Tae(Sae((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}const Dae=e=>Ab(e).parser,Oae=e=>Ab(e).makeEffect,Hb=`~effect/Schema/Schema`,Ub=/*#__PURE__*/ Symbol(),kae={[Hb]:Hb,get make(){let e=Nb(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=jb(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Mb(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Ot(this,arguments)},annotate(e){return this.rebuild(Uy(this.ast,e))},annotateKey(e){return this.rebuild(Qy(this.ast,e))},check(...e){return this.rebuild(Gy(this.ast,e))},rebuild(e){return Wb(e,this[Ub])}};function Wb(e,t){function n(){}let r=Object.setPrototypeOf(n,kae);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[Ub]=t,r.ast=e,r}function Aae(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Gb(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Kb(e){return encodeURI(Aae(e)).replace(/#/g,`%23`)}function qb(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function Jb(e){let t=qb(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(Gb)}function jae(e){return e.reduce((e,t)=>`${e}/${Kb(t)}`,`#`)}const Mae=[`example`,`discriminator`,`xml`,`externalDocs`];function Nae(e){let t=Object.keys(e.definitions),n=/* @__PURE__ */ new Map,r=new Set(t.filter(e=>Yb.test(e))),i=t.filter(e=>!Yb.test(e)).sort().map(e=>[e,Pae(e)]);for(let[e,t]of i)r.has(t)||(r.add(t),n.set(e,t));for(let[e,t]of i){if(n.has(e))continue;let i,a=0;do i=`${t}_${++a}`;while(r.has(i));r.add(i),n.set(e,i)}function a(t,r=!1){let i=Qb(t.$id),a=nn(t.$defs)?t.$defs:void 0;return Xb(t,(t,o)=>{Lae(t,Mae,`OpenAPI 3.1`,`Draft 2020-12`),Zb(t,(t,s)=>{let c=t.startsWith(`#`)?Jb(t):void 0;if(c===void 0||c[0]!==`$defs`||c.length<2)return t;let l=c[1];return i?(r&&!o&&Object.hasOwn(e.definitions,l)&&(a===void 0||!Object.hasOwn(a,l))&&ex(s,`OpenAPI 3.1`,`a schema resource cannot reference the shared definitions pool`),t):o?t:jae([`components`,`schemas`,n.get(l)??l,...c.slice(2)])})})}let o=e.schemas.map(e=>a(e,!0)),s={};for(let r of t)dr(s,n.get(r)??r,a(e.definitions[r]));return{dialect:`openapi-3.1`,schemas:o,definitions:s}}const Yb=/^[a-zA-Z0-9.\-_]+$/;function Pae(e){return e.length===0?`_`:e.replace(/[^a-zA-Z0-9._-]/gu,`_`)}function Xb(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!nn(e))return e;let a=r||!i&&Qb(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=Iae(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}dr(o,t,i)}return t(o,a),o}}function Fae(e,t){return Xb(e,e=>{Zb(e,t)})}function Zb(e,t){typeof e.$ref==`string`&&dr(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&dr(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function Iae(e,t){if(!nn(e))return;let n={};for(let r of Object.keys(e))dr(n,r,t(e[r],r));return n}function Qb(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}const $b=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...$b],[...$b];function ex(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Lae(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&ex(i,n,`it is not active in ${r} but would become active in the target`)}function Rae(e){return Wb(tx(e.ast),{schema:e})}const tx=/*#__PURE__*/ Xy(e=>{let t=Bae(e,tx),n=e.context;return t===e||n===void 0?t:Yy(t,nx(n))});function nx(e){return e.constructorDefault===void 0?e:new zv(e.isOptional,e.isMutable,void 0,e.annotations)}function rx(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function ix(e){return t=>{let n=[...t].sort((t,n)=>e(ib(t))-e(ib(n)));return n.some((e,n)=>e!==t[n])?n:t}}const zae=/*#__PURE__*/ ix(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Bae(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Jt(n))return By(e,[xb]);let r=n(e.typeParameters.map(e=>Wb(ib(e))));return r===void 0?e:By(e,[Ky(r,t)])}case`Unknown`:return By(e,[xb]);case`ObjectKeyword`:return By(e,[lae]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return rx(e),e.recur(t,db);case`Union`:{let n=zae(e.types);return n===e.types?e.recur(t):new Ty(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}function Vae(e){return Wb(sx(e.ast),{schema:e})}function Hae(e){return Wb(lx(e.ast))}const Uae=/*#__PURE__*/ ix(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wae(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>Wb(t(ib(e)))),i=e.annotations?.toCodecStringTree;if(Jt(i)){let n=i(r);return n===void 0?e:By(e,[Ky(n,t)])}let a=e.annotations?.toCodecJson,o=Jt(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??(Jt(s)?s(r):void 0);return c===void 0?n(e):By(e,[Ky(c,t)])}case`Null`:return By(e,[Gae]);case`Boolean`:return By(e,[Kae]);case`Unknown`:case`ObjectKeyword`:return By(e,[Sb]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return rx(e),e.recur(t,db);case`Union`:{let n=Uae(e.types);return n===e.types?e.recur(t):new Ty(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}const Gae=/*#__PURE__*/ new Lv(/*#__PURE__*/ new Yv(`null`),/*#__PURE__*/ new bv(/*#__PURE__*/ dv(()=>null),/*#__PURE__*/ dv(()=>`null`))),Kae=/*#__PURE__*/ new Lv(/*#__PURE__*/ new Ty([/*#__PURE__*/ new Yv(`true`),/*#__PURE__*/ new Yv(`false`)]),/*#__PURE__*/ new bv(/*#__PURE__*/ dv(e=>e===`true`),/*#__PURE__*/ gv())),ax=/*#__PURE__*/ new bv(/*#__PURE__*/ dv(e=>typeof e==`string`?[e]:e),/*#__PURE__*/ uv()),ox=e=>e.transformation===ax,sx=/*#__PURE__*/ Xy(e=>{let t=Wae(e,sx,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?Yy(t,nx(e.context)):t},{stopAt:ox}),cx=e=>tb(e)?$y(Kv):Kv,lx=/*#__PURE__*/ Xy(e=>{let t=qae(e);if(Nv(t)){let n=eb(new Ty([new ey(t.isMutable,t.elements.map(cx),t.rest.map(cx)),Zv],{mode:`anyOf`}),t,ax);return tb(e)?$y(n):n}return t},{stopAt:ox});function qae(e){return e._tag===`Declaration`||e._tag===`Arrays`||e._tag===`Objects`||e._tag===`Union`||e._tag===`Suspend`?e.recur(lx):e}globalThis.RegExp;const Jae=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function ux(e,t){return t.length>0&&(e+=`\n at ${Xn(t)}`),Error(e)}function dx(e){return`#/$defs/${Kb(e)}`}const Yae=/*#__PURE__*/ new Set([...g_,c_,...d_]);function fx(e,t){if(e===void 0)return;let n={},r=e.title;typeof r==`string`&&(n.title=r);let i=e.description,a=e.expected;typeof i==`string`?n.description=i:t?.generateDescriptions===!0&&typeof a==`string`&&(n.description=a);let o=e.default;yb(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&yb(s)&&(n.examples=s);let c=e.readOnly;typeof c==`boolean`&&(n.readOnly=c);let l=e.writeOnly;typeof l==`boolean`&&(n.writeOnly=l);let u=e.format;typeof u==`string`&&(n.format=u);let d=e.contentEncoding;typeof d==`string`&&(n.contentEncoding=d);let f=e.contentMediaType;typeof f==`string`&&(n.contentMediaType=f);let p=e.contentSchema;if(yb(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!Yae.has(r)&&t.includeAnnotationKey(r)&&yb(i)&&dr(n,r,i);return Object.keys(n).length===0?void 0:n}function px(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=px(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function Xae(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}function mx(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function Zae(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}function Qae(e,t,n){if(typeof e.$ref==`string`)return;let r={...e,...t};for(let i of n){if(!Object.hasOwn(e,i))continue;let n=e[i],a=t[i];if(typeof n!=`number`||typeof a!=`number`)return;if(`|minimum|exclusiveMinimum|minLength|minItems|minProperties|`.includes(`|${i}|`))r[i]=Math.max(n,a);else if(`|maximum|exclusiveMaximum|maxLength|maxItems|maxProperties|`.includes(`|${i}|`))r[i]=Math.min(n,a);else return}return typeof r.minimum==`number`&&typeof r.exclusiveMinimum==`number`&&delete r[r.exclusiveMinimum>=r.minimum?`minimum`:`exclusiveMinimum`],typeof r.maximum==`number`&&typeof r.exclusiveMaximum==`number`&&delete r[r.exclusiveMaximum<=r.maximum?`maximum`:`exclusiveMaximum`],r}const hx=`|title|description|default|examples|readOnly|writeOnly|`;function gx(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=Xae(e);if(i!==void 0||a){let r=px(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:mx(r.schema,hx)&&Zae(o,s)?{...o,...r.schema}:gx(o,r.schema,n)}}if(n){let n=Qae(e,t,r);if(n!==void 0)return n}let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function _x(e,t=/* @__PURE__ */ new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>_x(e,t)))}function $ae(e){return Array.isArray(e)}function vx(e,t,n,r){let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new WeakMap,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=qa(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!_x(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=g(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Dn(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=qa(u,h),f={};for(let e of l)a.has(e)||dr(f,e,h(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw ux(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=v(n[e],[`references`,e],a[1]),a}function h(e){return Fae(e,e=>{let t=qb(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(Gb(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,dx(r))})}function g(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[c_]:void 0}function _(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>v(e,[...n,`representation`,`schemas`,t],i))??[]}),c=$ae(s);c&&i.push(!1);let l=c?s[0]:s,u=fx(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`:`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames||title|description|default|examples|readOnly|writeOnly|`;return[d,e._tag===`Filter`&&mx(d,f)&&(u===void 0||mx(u,hx))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=_(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=fx(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function v(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:dx(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=y(e,t,a),c=fx(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&eoe(s.type)?s.type:void 0,i=_(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=gx(s,...i))}return o.set(e,[s,a]),p(s)}function y(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return v(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw ux(`Invalid numeric enum value ${globalThis.String(n)}`,[...t,`enums`,r,1]);return{type:typeof n,enum:[n],title:e}});return n.length===0?{not:{}}:{anyOf:n}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(yx).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw ux(`Invalid schema representation document`,[...t,`rest`]);let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=v(e.type,[...t,`elements`,i,`type`],n),s=fx(e.annotations,r);return s===void 0?o:p(gx(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=v(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw ux(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=v(s.type,[...t,`propertySignatures`,i,`type`],n),u=fx(s.annotations,r);dr(a,c,u===void 0?l:p(gx(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=v(i.type,[...t,`indexSignatures`,r,`type`],n);Dn(a,{not:{}})&&(a=!1),l.push(a);let o=b(i.parameter,[...t,`indexSignatures`,r,`parameter`],/* @__PURE__ */ new Set);if(o===void 0)u=!0,n.push(!1);else if(o.length===0)c.push(a);else for(let e of o){let t=s[e];dr(s,e,t===void 0?a:t===!1||a===!1?!1:p(gx(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(v(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>v(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=toe(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function b(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw ux(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return b(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=v(e,t,n);return _x(n)&&r.type===`string`&&typeof r.pattern==`string`&&mx(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(yx).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=b(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw ux(`Invalid schema representation document`,t)}}}function eoe(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function toe(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function yx(e){switch(e._tag){case`Literal`:return Jae(globalThis.String(e.literal));case`String`:return`[\\s\\S]*?`;case`Number`:return ry;case`TemplateLiteral`:return e.parts.map(yx).join(``);case`Union`:return`(?:${e.types.map(yx).join(`|`)})`;default:throw ux(`Invalid schema representation document`,[])}}function noe(e,t){let n=vx([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}function roe(e,t){return vx(e.representations,e.representations.map((e,t)=>[`representations`,t]),e.references,t)}const ioe=({identifier:e})=>e;function bx(e){return e===void 0?void 0:{annotations:e}}function aoe(e,t){let{references:n,representations:r}=xx([e],t);return{representation:r[0],references:n}}function xx(e,t){let n={},r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set;for(let t of e)f(t);let s=t?.referencePolicy??ioe;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:qa(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:Uy(e,{identifier:n}):p_(e)===r?e:Uy(e,{[c_]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),dr(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=Hy(e),n=zy(t),r=f_(t),i=r===void 0?(t===e?void 0:f_(e))??p_(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=/* @__PURE__ */ new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t))t.isRecursive=!0;else if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(rb(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?h(n):u(r,t.identifier===void 0?n:l(n,t,r))}function h(e){let t=g(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...v(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...bx(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...bx(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...bx(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...bx(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...bx(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=Hy(e),n=t.context?.annotations;return{isOptional:tb(t),type:m(e),...bx(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...bx(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=Hy(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:tb(t),isMutable:Zie(t),...bx(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...bx(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...bx(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...bx(e.annotations)}}}function g(e){return e?.map(_)??[]}function _(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...y(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:qa(e.checks,_),...y(e.annotations)}}}function v(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function y(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(rb(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function Sx(e){return Dd(e)?e.value:{issues:[{message:ud(e.cause)}]}}function ooe(e,t){let n=Fb(e),r={errors:`all`,...t?.parseOptions},i=W_(t),a=e=>{let t=new Eo(`sync`),a=pm(Pp(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?Sx(o):new Promise(e=>{a.addObserver(t=>{e(Sx(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}const soe=/*#__PURE__*/ j(2,(e,t)=>uoe(e,(e,n)=>loe(t,e)?void 0:[e,n])),coe=/*#__PURE__*/ j(2,(e,t)=>({...e,...t})),Cx=e=>e;function loe(e,t){return e.some(e=>e===t||typeof e==`number`&&String(e)===t)}function uoe(e,t){let n={};for(let r of Reflect.ownKeys(e)){if(!Object.prototype.propertyIsEnumerable.call(e,r))continue;let i=t(r,e[r]);if(i){let[e,t]=i;dr(n,e,t)}}return n}const wx=`~effect/Schema/SchemaError`;function Tx(e){return N(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...ar}),{...ar},{...ar},{...ar},{...ar},{...ar},{...ar},{...ar};const Ex=Hb;function Dx(){return(e,t,n)=>Bx(new Hv(e.map(hy),e=>t(e.map(e=>Bx(e))),n))}function Ox(e,t){return Dx()([],()=>(t,n,r)=>e(t)?F(t):z(new N_(n,t,r)),t)}var kx=class extends (/*#__PURE__*/ jo(`SchemaError`)){[wx]=wx;constructor(e){let t=sr();cr(0);try{super({issue:e})}finally{cr(t)}}get message(){return Z_(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[rr](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function doe(e){return Tx(e)}function Ax(e){return zc(e)?foe(e):Sp(e,e=>lp(()=>rd(e,e=>new kx(e))))}function foe(e){return Dd(e)?e:Sd(rd(e.cause,e=>new kx(e)))}function poe(e,t){let n;for(let r of e.reasons){if(!Yu(r)||!doe(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function jx(e){let t=vm(e);if(Dd(t))return t.value;throw poe(t.cause,`Sync adapter can only throw schema errors`)}function moe(e,t){return ooe(e,t)}const Mx=vae;function Nx(e,t){let n=Fb(e,t);return(e,t)=>Ax(n(e,t))}const Px=Nx,hoe=bae;function goe(e,t){let n=xae(e,t);return(e,t)=>Fa(n(e,t),e=>new kx(e))}function Fx(e,t){let n=Nx(e,t);return(e,t)=>jx(n(e,t))}const _oe=Fx;function Ix(e,t){let n=Ib(e,t);return(e,t)=>Ax(n(e,t))}const Lx=Ix;function Rx(e,t){let n=Ix(e,t);return(e,t)=>jx(n(e,t))}const zx=Rx,Bx=Wb;function Vx(e){return N(e,Ex)&&e[Ex]===Ex}const Hx=/*#__PURE__*/ Cx(e=>Bx($y(e.ast),{schema:e})),Ux=/*#__PURE__*/ Cx(e=>{let t=cS(e);return Bx(qie(e.ast),{schema:t})}),Wx=/*#__PURE__*/ Cx(e=>Bx(rb(e.ast),{schema:e})),voe=/*#__PURE__*/ Cx(e=>Bx(ib(e.ast),{schema:e}));function Gx(e){let t=Bx(new Yv(e),{literal:e,transform(n){return t.pipe(lS(Gx(n),{decode:dv(()=>n),encode:dv(()=>e)}))}});return t}function yoe(e){return e.map(e=>Vx(e)?e.ast:new Yv(e))}function Kx(e){return Bx(new kie(yoe(e)),{parts:e})}const qx=/*#__PURE__*/ Bx(Die),Jx=/*#__PURE__*/ Bx(Oie),Yx=/*#__PURE__*/ Bx(Kv),boe=/*#__PURE__*/ Bx(Uv),xoe=/*#__PURE__*/ Bx(Gv),U=/*#__PURE__*/ Bx(Zv),Xx=/*#__PURE__*/ Bx($v),Zx=/*#__PURE__*/ Bx(Mie),Qx=/*#__PURE__*/ Bx(Eie);function $x(e,t){return Bx(e,{fields:t,mapFields(e,t){let n=e(this.fields);return $x(my(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function W(e){return $x(my(e,void 0),e)}function eS(e){return Cx(t=>t.mapFields(coe(e)))}function tS(e,t){return Bx(Xie(e.ast,t.ast),{key:e,value:t})}function nS(e,t){return Bx(Rie(e.ast,t.map(hy)),{schema:e,records:t})}function rS(e,t){return Bx(e,{elements:t,mapElements(e,t){let n=e(this.elements);return rS(gy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function Soe(e){return rS(gy(e),e)}const G=/*#__PURE__*/ Cx(e=>Bx(new ey(!1,[],[e.ast]),{value:e})),iS=/*#__PURE__*/ Cx(e=>Bx(new ey(!1,[e.ast],[e.ast]),{value:e}));function aS(e,t){return Bx(e,{members:t,mapMembers(e,t){let n=e(this.members);return aS(_y(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function K(e,t){return aS(_y(e,t,void 0),e)}function oS(e){let t=e.map(Gx);return Bx(_y(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return K(e(this.members))},pick(e){return oS(e)},transform(e){return K(t.map((t,n)=>t.transform(e[n])))}})}const sS=/*#__PURE__*/ Cx(e=>K([e,boe])),cS=/*#__PURE__*/ Cx(e=>K([e,xoe]));function lS(e,t){return n=>Bx(eb(n.ast,e.ast,t?xv(t):wv()),{from:n,to:e})}function uS(){return(e,t)=>vS()(e,{decode:t,encode:cv})}const dS=/*#__PURE__*/ oS([`true`,`yes`,`on`,`1`,`y`]),fS=/*#__PURE__*/ oS([`false`,`no`,`off`,`0`,`n`]),Coe=/*#__PURE__*/ oS([...dS.literals,...fS.literals]).pipe(/*#__PURE__*/ lS(Zx,/*#__PURE__*/ Cv({decode:e=>e===`true`||e===`yes`||e===`on`||e===`1`||e===`y`,encode:e=>e?`true`:`false`})));function woe(e){return t=>lS(Wx(t),e)(t)}function pS(e){return t=>Bx(Jie(t.ast,e),{schema:t})}function mS(e){return Gx(e).pipe(pS(F(e)))}function hS(e,t){return W({_tag:mS(e),...t})}function gS(){return e=>e}function _S(e,t){return Ox(t=>t instanceof e,t)}function vS(){return(e,t)=>new Lv(e.ast,xv(t))}const yS=Py,bS=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function xS(e){let t=new globalThis.RegExp(bS);return yS(e=>e.trim()===e,{expected:`a string with no leading or trailing whitespace`,representation:{id:`effect/schema/isTrimmed`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isTrimmed()`}),arbitraryConstraint:{patterns:[{source:bS,flags:``}]},...e})}function SS(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${qn(n)})`:`new RegExp(${qn(n)}, ${qn(r)})`;return Iy(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}const CS=/*#__PURE__*/ Bx(Fy);function wS(e){let t=Mi(e.order),n=e.formatter??qn;return(r,i)=>yS(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function TS(e){let t=Mi(e.order),n=Ai(e.order),r=ji(e.order),i=Kee(e.order),a=e.formatter??qn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return yS(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function ES(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${qn(e)}`);return e}const DS=/*#__PURE__*/ wS({order:ki,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:ES(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${qn(e)})`})})}),OS=/*#__PURE__*/ TS({order:ki,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:ES(e.minimum),maximum:ES(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${qn(e.minimum)}, maximum: ${qn(e.maximum)}, exclusiveMinimum: ${qn(t)}, exclusiveMaximum: ${qn(n)} })`})}}});function kS(e){return yS(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>({type:`integer`,minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}const AS=/*#__PURE__*/ Xx.check(/*#__PURE__*/ kS());function jS(e,t){return e=PS(e),MS(e,Math.ceil(e/2),t)}function MS(e,t,n){return yS(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[s_]:!0,arbitraryConstraint:{minLength:e},...n})}function Toe(e){return MS(1,1,e)}function NS(e,t){return e=PS(e),yS(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[s_]:!0,arbitraryConstraint:{maxLength:e},...t})}function PS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Eoe(e,t){return e=PS(e),yS(t=>Reflect.ownKeys(t).length>=e,{expected:`a value with at least ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMinProperties`,payload:{minProperties:e}},toJsonSchema:({type:t})=>t===`object`?{minProperties:e}:[{minProperties:e},!0],toCode:()=>({runtime:`Schema.isMinProperties(${e})`}),[s_]:!0,arbitraryConstraint:{minProperties:e},...t})}function FS(e){return yS(e=>dte(e).length===e.length,{expected:`an array with unique items`,representation:{id:`effect/schema/isUnique`,payload:null},toJsonSchema:()=>({uniqueItems:!0}),toCode:()=>({runtime:`Schema.isUnique()`}),arbitraryConstraint:{uniqueBy:M},...e})}const IS=/*#__PURE__*/ U.check(/*#__PURE__*/ Toe()),Doe=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),LS=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},RS=[];function zS(e){let t=Doe(e),n=RS[t];if(n!==void 0)return n;let r=_C.pipe(lS(Yx,yie(LS(t))));return RS[t]=r,r}globalThis.RegExp,globalThis.URL;const BS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function VS(e,t){return BS.pipe(lS(e,bie(t)))}const HS=/*#__PURE__*/ VS(Yx);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;const US=/*#__PURE__*/ U.check(/*#__PURE__*/ xS()),WS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(/*#__PURE__*/ lS(US,/*#__PURE__*/ fie())),GS=/*#__PURE__*/ U.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),KS=/*#__PURE__*/ _S(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>vS()(GS,Dv)}),qS=/*#__PURE__*/ GS.pipe(/*#__PURE__*/ lS(KS,Dv));function JS(e,t){let n=Dx()([e,t],([e,t])=>(n,r,i)=>{if(!gre(n))return z(new N_(r,n,i));switch(n._tag){case`Fail`:return Am(Fb(e)(n.error,i),{onSuccess:$u,onFailure:e=>F_(r,`error`,e,n,i)});case`Die`:return Am(Fb(t)(n.defect,i),{onSuccess:ed,onFailure:e=>F_(r,`defect`,e,n,i)});case`Interrupt`:return F(n)}},{representation:{id:`effect/schema/CauseReason`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.CauseReason(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Failure<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause.Failure`,toCodec:([e,t])=>vS()(K([W({_tag:Gx(`Fail`),error:e}),W({_tag:Gx(`Die`),defect:t}),W({_tag:Gx(`Interrupt`),fiberId:cS(CS)})]),Cv({decode:e=>{switch(e._tag){case`Fail`:return $u(e.error);case`Die`:return ed(e.defect);case`Interrupt`:return td(e.fiberId)}},encode:e=>{switch(e._tag){case`Fail`:return{_tag:`Fail`,error:e.error};case`Die`:return{_tag:`Die`,defect:e.defect};case`Interrupt`:return{_tag:`Interrupt`,fiberId:e.fiberId}}}}))});return Bx(n.ast,{error:e,defect:t})}function YS(e,t){let n=Dx()([e,t],([e,t])=>{let n=G(JS(e,t));return(e,t,r)=>hre(e)?Am(Fb(n)(e.reasons,r),{onSuccess:Xu,onFailure:n=>F_(t,`failures`,n,e,r)}):z(new N_(t,e,r))},{representation:{id:`effect/schema/Cause`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Cause(${e[0].runtime}, ${e[1].runtime})`,Type:`Cause.Cause<${e[0].Type}, ${e[1].Type}>`,importDeclarations:[`import * as Cause from "effect/Cause"`]}),expected:`Cause`,toCodec:([e,t])=>vS()(G(JS(e,t)),Cv({decode:Xu,encode:({reasons:e})=>e}))});return Bx(n.ast,{error:e,defect:t})}const XS=/*#__PURE__*/ Sv({decode:(e,t)=>Li(Ch(e),{onNone:()=>z(new P_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>F(wh(e))}),encode:e=>F(Eh(e))});function ZS(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function QS(e,t){return AS.check(OS({minimum:e,maximum:t}))}const $S=/*#__PURE__*/ Ox(e=>yh(e)&&bh(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=ZS(e,-864e13,864e13);return uS()(QS(t,n),dv(Sh))},toCodecJson:()=>vS()(U,XS),toFormatter:()=>e=>e.toString()}),eC=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(/*#__PURE__*/ lS($S,XS));function tC(e,t,n){let r=Dx()([e,t,n],([e,t,n])=>{let r=YS(t,n);return(t,n,i)=>{if(!bd(t))return z(new N_(n,t,i));switch(t._tag){case`Success`:return Am(Fb(e)(t.value,i),{onSuccess:xd,onFailure:e=>F_(n,`value`,e,t,i)});case`Failure`:return Am(Fb(r)(t.cause,i),{onSuccess:Sd,onFailure:e=>F_(n,`cause`,e,t,i)})}}},{representation:{id:`effect/schema/Exit`,payload:null},toCode:({typeParameters:e})=>({runtime:`Schema.Exit(${e[0].runtime}, ${e[1].runtime}, ${e[2].runtime})`,Type:`Exit.Exit<${e[0].Type}, ${e[1].Type}, ${e[2].Type}>`,importDeclarations:[`import * as Exit from "effect/Exit"`]}),expected:`Exit`,toCodec:([e,t,n])=>vS()(K([W({_tag:Gx(`Success`),value:e}),W({_tag:Gx(`Failure`),cause:YS(t,n)})]),Cv({decode:e=>e._tag===`Success`?xd(e.value):Sd(e.cause),encode:e=>Dd(e)?{_tag:`Success`,value:e.value}:{_tag:`Failure`,cause:e.cause}}))});return Bx(r.ast,{value:e,error:t,defect:n})}function nC(e,t){let n=typeof t?.label==`string`?t.label:void 0,r=t?.disallowJsonEncode===!0,i=n===void 0?r?{disallowJsonEncode:!0}:void 0:r?{label:n,disallowJsonEncode:!0}:{label:n},a=n===void 0?void 0:Fb(Gx(n)),o=Dx()([e],([e])=>(t,n,r)=>{if(mg(t)){let i=a===void 0?L:km(a(t.label,r),e=>new k_([`label`],e));return jm(i,()=>Am(Fb(e)(_g(t),r),{onSuccess:e=>hg(e,{label:t.label}),onFailure:()=>new M_(n,[new k_([`value`],new P_(void 0,t,r))],t,r)}))}return z(new N_(n,t,r))},{representation:{id:`effect/schema/Redacted`,payload:i??null},toCode:({typeParameters:e})=>({runtime:i===void 0?`Schema.Redacted(${e[0].runtime})`:`Schema.Redacted(${e[0].runtime}, ${qn(i)})`,Type:`Redacted.Redacted<${e[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:`Redacted`,toCodecJson:([e])=>vS()(e,{decode:dv(e=>hg(e,{label:n})),encode:r?sv(e=>`Cannot serialize Redacted`+(Ii(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):dv(_g)}),toEquivalence:([e])=>vg(e)});return Bx(o.ast,{value:e})}const rC=/*#__PURE__*/ globalThis.Symbol.for(`immer-draftable`),iC={};function aC(e,t,n,r,i){let a=cC(n,t,r),o=sC(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===iC?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:iC,value:i}})}static[Ex]=Ex;get[o](){return o}static[rC]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return Ot(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return Nb(a(this))(e??{},t)}static makeOption(e,t){return Mb(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(Uy(this.ast,e))}static annotateKey(e){return this.rebuild(Qy(this.ast,e))}static check(...e){return this.rebuild(Gy(this.ast,e))}static extend(e){return(t,r)=>{let a=lC(t)?t:W(t),o={...n.fields,...a.fields},s=my(o,n.ast.checks,{identifier:e});return aC(this,e,$x(Gy(s,a.ast.checks),o),r,i)}}static mapFields(e,t){return n.mapFields(e,t)}};return i!==void 0&&Object.assign(s.prototype,i(t)),s}function oC(e){return new bv(dv(t=>new e(t,{"~payload":{token:iC,value:t}})),uv())}function sC(e){return`~effect/Schema/Class/${e}`}function cC(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=sC(t),o=e=>e instanceof i||N(e,a),s=oC(i);return r=lS(Bx(new Hv([e.ast],()=>(e,t,n)=>o(e)?F(e):z(new N_(t,e,n)),{identifier:t,[u_]:([e])=>({isConstructed:o,link:new Lv(e,s)}),toCodec:([e])=>new Lv(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[l_]:by(e.ast),...n})),s)(e)}}function lC(e){return Vx(e)}const uC=e=>(t,n)=>{let r=lC(t)?t:W(t);return aC(Do,e,r,n,e=>({toString(){return`${e}(${qn({...this})})`}}))},dC=e=>(t,n)=>{let r=lC(t)?t:W(t);return aC(ii,e,r,n,e=>({name:e}))},fC=e=>(t,n,r)=>{let i=lC(n)?n.mapFields(e=>({_tag:mS(t),...e}),{unsafePreserveChecks:!0}):hS(t,n);return dC(e??t)(i,r)};function pC(e,t){return noe(aoe(tx(e.ast),t),t)}const mC=Rae,hC=Vae,gC=Hae,_C=/*#__PURE__*/ Bx(/*#__PURE__*/ Uy(bb,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),q=/*#__PURE__*/ tS(U,_C);function vC(){return Object.assign(e=>e,{option:e=>Pi(e),result:e=>ka(e),is:e=>!0})}const yC=Zs,bC=Qs,xC=Vs,SC=Yne,CC=mu,Ooe=hu,wC=`~effect/MutableRef`,koe={[wC]:wC,...Sr,toJSON(){return{_id:`MutableRef`,current:ir(this.current)}}},TC=e=>{let t=Object.create(koe);return t.current=e,t},EC=/*#__PURE__*/ j(2,(e,t)=>(e.current=t,e)),DC=/*#__PURE__*/ Symbol.for(`effect/MutableList/Empty`),OC=()=>({head:void 0,tail:void 0,length:0}),kC=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},AC=()=>({array:[],mutable:!0,offset:0,next:void 0}),jC=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=AC(),e.tail=e.tail.next):e.head=e.tail=AC(),e.tail.array.push(t),e.length++},Aoe=(e,t)=>{e.head={array:[t],mutable:!0,offset:0,next:e.head},e.tail||=e.head,e.length++},joe=(e,t)=>Moe(e,Ba(t),!Array.isArray(t)),Moe=(e,t,n=!1)=>{if(t.length===0)return 0;let r={array:t,mutable:n,offset:0,next:void 0};return e.head?e.tail=e.tail.next=r:e.head=e.tail=r,e.length+=t.length,t.length},MC=e=>{e.head=e.tail=void 0,e.length=0},NC=(e,t)=>{if(t=Oa(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return MC(e),t}let n=Array(t),r=0,i=e.head;for(;i;){for(;i.offset<i.array.length;)if(n[r++]=i.array[i.offset],i.mutable&&(i.array[i.offset]=void 0),i.offset++,r===t)return e.head=i.offset===i.array.length&&i.next?i.next:i,e.length-=t,e.length===0?MC(e):kC(e),n;i=i.next}return MC(e),n},Noe=e=>NC(e,e.length),PC=e=>{if(!e.head)return DC;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:MC(e):kC(e),t},Poe=(e,t)=>{let n=[],r=e.head,i=0;for(;r;){for(let e=r.offset;e<r.array.length;e++)t(r.array[e],i++)&&n.push(r.array[e]);r=r.next}n.length===0?MC(e):(e.head=e.tail={array:n,mutable:!0,offset:0,next:void 0},e.length=n.length)},Foe=(e,t)=>Poe(e,e=>e!==t),Ioe=e=>I(()=>Zoe(e.atomicPubSub(),/* @__PURE__ */ new Map,Xd(),CC(!1),TC(!1),e.strategy(),TC(Ni()))),Loe=e=>Ioe({atomicPubSub:()=>Roe(e),strategy:()=>new Qoe}),Roe=e=>{let t=e?.replay;return new qoe(t&&t>0?new tse(Math.ceil(t)):void 0)},zoe=/*#__PURE__*/ j(2,(e,t)=>ap(()=>e.shutdownFlag.current||Ii(e.ended.current)?F(!1):e.pubsub.publish(t)?(e.strategy.completeSubscribersUnsafe(e.pubsub,e.subscribers),F(!0)):e.strategy.handleSurplus(e.pubsub,e.subscribers,[t],e.shutdownFlag,e.ended))),Boe=e=>rm(Rp(t=>{let n=va(t,Jd),r=tf(e.scope),i=Koe(e.pubsub,e.subscribers,e.strategy,e.ended);return $d(r,Voe(i)).pipe(mp(Qd(n,e=>nf(r,e))),vp(i))})),Voe=e=>rm(fp(t=>(EC(e.shutdownFlag,!0),ep(Noe(e.pollers),e=>Bd(e,t.id),{discard:!0,concurrency:`unbounded`}).pipe(hp(()=>I(()=>{e.subscribers.delete(e.subscription),e.subscription.unsubscribe(),e.replayWindow.close(),e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers)})),eie(e.shutdownHook.open),yp)))),Hoe=e=>ap(()=>{if(e.shutdownFlag.current)return em;if(e.replayWindow.remaining>0){let t=e.replayWindow.take();return F(t)}let t=e.pollers.length===0?e.subscription.poll():DC;return t===DC?Uoe(e):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),F(t))}),Uoe=e=>op(t=>{if(e.shutdownFlag.current)return t(em);if(Ii(e.ended.current)){let n=e.pollers.length===0?e.subscription.poll():DC;return n===DC?t(F(e.ended.current.value)):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),t(F(n)))}let n=Fd(),r=e.subscribers.get(e.subscription);return r||(r=/* @__PURE__ */ new Set,e.subscribers.set(e.subscription,r)),r.add(e.pollers),jC(e.pollers,n),e.strategy.completePollersUnsafe(e.pubsub,e.subscribers,e.subscription,e.pollers),n.effect?t(n.effect):(n.resumes=[t],I(()=>Foe(e.pollers,n)))}),FC=/*#__PURE__*/ Symbol.for(`effect/PubSub/AbsentValue`),Woe=(e,t,n)=>{e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(n)},Goe=(e,t,n)=>{if(!e.has(t))return;let r=e.get(t);r.delete(n),r.size===0&&e.delete(t)},Koe=(e,t,n,r)=>new Yoe(e,t,e.subscribe(),OC(),CC(!1),TC(!1),n,e.replayWindow(),r);var qoe=class{publisherHead={value:FC,replayIndex:void 0,subscribers:0,next:null};publisherTail=this.publisherHead;publisherIndex=0;subscribersIndex=0;capacity=2**53-1;replayBuffer;constructor(e){this.replayBuffer=e}replayWindow(){return this.replayBuffer?new nse(this.replayBuffer):rse}isEmpty(){return this.publisherHead===this.publisherTail}isFull(){return!1}size(){return this.publisherIndex-this.subscribersIndex}publish(e){let t=this.replayBuffer?.offer(e),n=this.publisherTail.subscribers;if(n!==0){let r={value:e,replayIndex:t,subscribers:n,next:null};this.publisherTail.next=r,this.publisherTail=this.publisherTail.next,this.publisherIndex+=1}return!0}publishAll(e){if(this.publisherTail.subscribers!==0)for(let t of e)this.publish(t);else this.replayBuffer&&this.replayBuffer.offerAll(e);return[]}slide(){if(this.publisherHead!==this.publisherTail){let e=this.publisherHead.next,t=e.value;this.publisherHead=this.publisherHead.next,this.publisherHead.value=FC,this.subscribersIndex+=1,this.replayBuffer?.slide(t,e.replayIndex)}}subscribe(){return this.publisherTail.subscribers+=1,new Joe(this,this.publisherTail,this.publisherIndex,!1)}},Joe=class{self;subscriberHead;subscriberIndex;unsubscribed;constructor(e,t,n,r){this.self=e,this.subscriberHead=t,this.subscriberIndex=n,this.unsubscribed=r}isEmpty(){if(this.unsubscribed)return!0;let e=!0,t=!0;for(;t;)this.subscriberHead===this.self.publisherTail?t=!1:this.subscriberHead.next.value===FC?(this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1):(e=!1,t=!1);return e}size(){return this.unsubscribed?0:this.self.publisherIndex-Math.max(this.subscriberIndex,this.self.subscribersIndex)}poll(){if(this.unsubscribed)return DC;let e=!0,t=DC;for(;e;)if(this.subscriberHead===this.self.publisherTail)e=!1;else{let n=this.subscriberHead.next.value;n!==FC&&(t=n,--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=FC,this.self.subscribersIndex+=1),e=!1),this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return t}pollUpTo(e){e=Oa(e);let t=[],n=0;for(;n!==e;){let r=this.poll();r===DC?n=e:(t.push(r),n+=1)}return t}unsubscribe(){if(!this.unsubscribed)for(this.unsubscribed=!0,--this.self.publisherTail.subscribers;this.subscriberHead!==this.self.publisherTail;)this.subscriberHead.next.value!==FC&&(--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=FC,this.self.subscribersIndex+=1)),this.subscriberHead=this.subscriberHead.next}},Yoe=class{"~effect/PubSub/Subscription"={_A:M};pubsub;subscribers;subscription;pollers;shutdownHook;shutdownFlag;strategy;replayWindow;ended;constructor(e,t,n,r,i,a,o,s,c){this.pubsub=e,this.subscribers=t,this.subscription=n,this.pollers=r,this.shutdownHook=i,this.shutdownFlag=a,this.strategy=o,this.replayWindow=s,this.ended=c}pipe(){return Ot(this,arguments)}},Xoe=class{"~effect/PubSub"={_A:M};pubsub;subscribers;scope;shutdownHook;shutdownFlag;strategy;ended;constructor(e,t,n,r,i,a,o){this.pubsub=e,this.subscribers=t,this.scope=n,this.shutdownHook=r,this.shutdownFlag=i,this.strategy=a,this.ended=o}pipe(){return Ot(this,arguments)}};const Zoe=(e,t,n,r,i,a,o)=>new Xoe(e,t,n,r,i,a,o);var Qoe=class{get shutdown(){return L}handleSurplus(e,t,n,r){return F(!1)}onPubSubEmptySpaceUnsafe(e,t){}completePollersUnsafe(e,t,n,r){return $oe(this,e,t,n,r)}completeSubscribersUnsafe(e,t){return ese(this,e,t)}};const $oe=(e,t,n,r,i)=>{let a=!0;for(;a&&!r.isEmpty();){let o=PC(i);if(o===DC)Goe(n,r,i),i.length===0?a=!1:Woe(n,r,i);else{let a=r.poll();a===DC?Aoe(i,o):(Wd(o,xd(a)),e.onPubSubEmptySpaceUnsafe(t,n))}}},ese=(e,t,n)=>{for(let[r,i]of n)for(let a of i)e.completePollersUnsafe(t,n,r,a)};var tse=class{capacity;head={value:FC,index:0,next:null};tail=this.head;slideValues=[];size=0;index=0;publisherIndex=0;constructor(e){this.capacity=e}slide(e,t){this.slideValues[this.index%this.capacity]={value:e,index:t},this.index++}offer(e){let t=this.publisherIndex++;return this.tail.value=e,this.tail.index=t,this.tail.next={value:FC,index:0,next:null},this.tail=this.tail.next,this.size===this.capacity?this.head=this.head.next:this.size+=1,t}offerAll(e){for(let t of e)this.offer(t)}},nse=class{buffer;values;index=0;remaining;slideIndex;newestIndex=-1;constructor(e){this.buffer=e,this.remaining=e.size,this.slideIndex=e.index,this.values=Array(this.remaining);let t=e.head;for(let e=0;e<this.remaining;e++)this.values[e]=t.value,this.newestIndex=t.index,t=t.next}close(){this.values.length=0,this.remaining=0}sync(){let e=this.buffer.index-this.slideIndex;if(e===0||this.remaining===0)return;let t=Math.min(e,this.buffer.capacity),n=this.buffer.index-t;for(let e=0;e<t;e++){let t=this.buffer.slideValues[(n+e)%this.buffer.capacity];t.index>this.newestIndex&&(this.index=(this.index+1)%this.values.length,this.values[(this.index+this.remaining-1)%this.values.length]=t.value,this.newestIndex=t.index)}this.slideIndex=this.buffer.index}take(){if(this.remaining===0)return;this.sync();let e=this.values[this.index];return this.values[this.index]=FC,this.index=(this.index+1)%this.values.length,this.remaining--,this.remaining===0&&this.close(),e}takeN(e){e=Oa(e);let t=Math.min(e,this.remaining),n=Array(t);for(let e=0;e<t;e++)n[e]=this.take();return n}takeAll(){return this.takeN(this.remaining)}};const rse={remaining:0,take:()=>void 0,takeN:()=>[],takeAll:()=>[],close:()=>void 0},IC={_A:M,_E:M},ise={"~effect/Queue":IC,"~effect/Queue/Enqueue":IC,"~effect/Queue/Dequeue":IC,...Sr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:nw(this)}}},LC=e=>ni(t=>{let n=Object.create(ise);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=OC(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Set,awaiters:/* @__PURE__ */ new Set},tc(n)}),RC=e=>LC({capacity:e}),zC=e=>LC({capacity:e,strategy:`dropping`}),BC=/*#__PURE__*/ j(2,(e,t)=>ac(()=>VC(e,t)?iw:e.state._tag===`Open`&&e.strategy===`suspend`?pw(e,t):rw)),VC=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(PC(e.messages),jC(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(jC(e.messages,t),sw(e),!0):(jC(e.messages,t),cw(e),!0):!1,HC=/*#__PURE__*/ j(2,(e,t)=>vc(n=>{let r=UC(e,t);return r.length===0||e.strategy===`dropping`?n(Xr(r)):mw(e,{_tag:`Array`,remaining:r,offset:0,resume:n})})),UC=(e,t)=>{if(e.state._tag!==`Open`)return Ba(t);if(e.capacity===1/0||e.strategy===`sliding`)return joe(e.messages,t),e.strategy===`sliding`&&NC(e.messages,e.messages.length-e.capacity),cw(e),[];let n=e.capacity<=0?e.state.takers.size:e.capacity-e.messages.length;if(n===0)return Ba(t);let r=[],i=0;for(let a of t)i<n?jC(e.messages,a):r.push(a),i++;return cw(e),r},WC=/*#__PURE__*/ j(2,(e,t)=>ic(()=>GC(e,t))),GC=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=$r(t),r=ane(n,aw);return e.state.offers.size===0&&e.messages.length===0?(vw(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},cw(e),!0)},KC=e=>WC(e,zr(di())),qC=e=>GC(e,zr(di())),JC=e=>ic(()=>YC(e)),YC=e=>{if(e.state._tag===`Done`)return!1;MC(e.messages);let t=e.state.offers;vw(e,e.state._tag===`Open`?ow:e.state.exit);for(let e of t)hw(e);return!0},XC=e=>QC(e,1,1/0),ZC=e=>ac(()=>{let t=Ga();return Ec(Uf(Zl({while:Mt,body:jt(XC(e)),step(e){for(let n=0;n<e.length;n++)t.push(e[n])}}),()=>fc),t)}),QC=/*#__PURE__*/ j(3,(e,t,n)=>(t=Oa(t),n=Oa(n),uw(()=>lw(e,t,n)??Pc(fw(e,()=>dw(e,t)),QC(e,t,n))))),$C=e=>uw(()=>tw(e)??Pc(fw(e,()=>dw(e,1)),$C(e))),ew=e=>uw(()=>{let t=tw(e);return t===void 0?tc(Ni()):t._tag===`Success`?tc(Pi(t.value)):tc(Ni())}),tw=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=PC(e.messages);return _w(e),Xr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=gw(e.state.offers);return _w(e),Xr(t)}},nw=e=>e.state._tag===`Done`?0:e.messages.length,rw=/*#__PURE__*/ Xr(!1),iw=/*#__PURE__*/ Xr(!0),aw=/*#__PURE__*/ ei(/*#__PURE__*/ di()),ow=/*#__PURE__*/ Vc(),sw=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(Wc),e.messages.length===0))break}},cw=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,sw(e)},0))},lw=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Xr([]);if(!dw(e,t))return;let r=e.messages.length>0?NC(e.messages,n):[gw(e.state.offers)];return _w(e),Xr(r)},uw=/*#__PURE__*/ Jr({op:`QueueTake`,[_r](e){let t=this[gr]();return wr(t)?t[_r](e):t}}),dw=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,fw=(e,t)=>vc(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(Wc);let r={ready:t,resume:n};return e.state.takers.add(r),ic(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),pw=(e,t)=>vc(n=>VC(e,t)?n(iw):mw(e,{_tag:`Single`,message:t,resume:n})),mw=(e,t)=>{if(e.state._tag!==`Open`)return hw(t);let n=e.state.offers;return n.add(t),ic(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&vw(e,e.state.exit))})},hw=e=>e._tag===`Single`?e.resume(rw):e.resume(Xr(e.remaining.slice(e.offset))),gw=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(iw),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Xr([]))),n},_w=e=>{if(e.state._tag===`Done`)return Wf(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(vw(e,e.state.exit),Wf(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)jC(e.messages,t.message),e.state.offers.delete(t),t.resume(iw);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;jC(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Xr([]))}let r=e.state;if(r._tag===`Done`)return Wf(r.exit.cause)}return!1},vw=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},yw=e=>new xw(e),bw=(e,t,n)=>vc(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),ic(()=>{e.waiters.delete(i)})});var xw=class{waiters=/*#__PURE__*/ new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=ac(()=>this.free<e?bw(this,e,t):(this.taken+=e,tc(e)));return t}takeIfAvailable(e){return ac(()=>this.free<e?tc(!1):(this.taken+=e,tc(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return ni(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),fc))}release(e){return ni(t=>tc(this.releaseUnsafe(t,e)))}get releaseAll(){return ni(e=>tc(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>Yl(n=>{let r=ac(()=>{if(this.free<e){let t=bw(this,e,fc);return Rc(n(t),()=>r)}return this.taken+=e,Ml(n(t),()=>{this.releaseUnsafe(Vs(),e)},!0)});return r})}withPermit=/*#__PURE__*/ this.withPermits(1);withPermitsIfAvailable(e){return t=>Yl(n=>this.free<e?cc:(this.taken+=e,Ml(n(Nc(t)),()=>{this.releaseUnsafe(Vs(),e)},!0)))}};const Sw=e=>ic(()=>new xw(e)),Cw=`~effect/Channel`,ww=e=>N(e,Cw),Tw={[Cw]:{_Env:M,_InErr:M,_InElem:M,_OutErr:M,_OutElem:M},pipe(){return Ot(this,arguments)}},Ew=e=>{let t=Object.create(Tw);return t.transform=(t,n)=>Sp(e(t,n),e=>F(cp(e))),t},Dw=(e,t)=>Ew((n,r)=>B(Aw(e)(n,r),e=>t(e,r))),Ow=e=>Ew((t,n)=>e),kw=e=>Ew(H(function*(t,n){let r=tf(n),i=e=>nf(r,qf(e)),a=yield*Xp(e(t,n,r),i);return Xp(a,i)})),Aw=e=>e.transform,jw=(e,t,n)=>LC({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(hp(t=>$d(e,JC(t))),hp(n=>Zd(t(n),e).pipe(Sp(e=>WC(n,e)),dm(e)))),Mw=(e,t)=>Ew((n,r)=>V(jw(r,e,t),XC)),Nw=e=>Ew((t,n)=>ap(()=>Aw(e())(t,n))),Pw=e=>Ow(I(()=>{let t=e();return ap(()=>{let e=t.next();return e.done?md(e.value):F(e.value)})})),Fw=e=>Bw(F(e)),Iw=/*#__PURE__*/ Ow(/*#__PURE__*/ F(/*#__PURE__*/ md())),Lw=e=>Ow(F(z(e))),Rw=e=>Ow(cp(e)),zw=e=>Rw(Qu(e)),Bw=e=>Ow(I(()=>{let t=!1;return ap(()=>t?md():(t=!0,e))})),Vw=e=>Ow(B(e,()=>md())),Hw=e=>Ow(F(XC(e))),Uw=e=>Ew((t,n)=>Ww({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),Ww=e=>{let t=e.readable.getReader(),n=e.exit??TC(void 0),r=ap(()=>n.current?n.current:Fp(rp({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??cp(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?md():F(Ka(t))}));return vp($d(e.scope,e.releaseLockOnEnd?I(()=>t.releaseLock()):np(()=>t.cancel().catch(Ft))),r)},Gw=/*#__PURE__*/ j(2,(e,t)=>Dw(e,e=>I(()=>{let n=0;return V(e,e=>t(e,n++))}))),Kw=/*#__PURE__*/ j(2,(e,t)=>qw(e,e=>F(t(e)))),qw=/*#__PURE__*/ j(2,(e,t)=>Dw(e,e=>F(Uf(e,e=>B(t(e),md))))),Jw=e=>e===void 0||e!==`unbounded`&&e<=1,Yw=/*#__PURE__*/ j(e=>ww(e[0]),(e,t,n)=>Jw(n?.concurrency)?Xw(e,t):Zw(e,t,n)),Xw=(e,t)=>Ew((n,r)=>{let i=0;return V(Aw(e)(n,r),B(e=>t(e,i++)))}),Zw=(e,t,n)=>kw(H(function*(r,i,a){let o=0,s=yield*Aw(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*RC(0);yield*$d(a,JC(l));let u=mm(yield*Lp()),d=SC(a);if(n.unordered){let e=yw(c),n=jt(e.release(1)),r=Fp({onFailure:e=>B(WC(l,e),n),onSuccess:e=>B(BC(l,e),n)});yield*e.take(1).pipe(B(()=>s),B(e=>{let n=o++;return d(u(r(ap(()=>t(e,n))))),L}),am({disableYield:!0}),Sp(t=>e.withPermits(c-1)(WC(l,t))),dm(a))}else{let e=yield*RC(c-2);yield*$d(a,JC(e)),yield*$C(e).pipe(Gre,B(e=>BC(l,e)),am({disableYield:!0}),Sp(e=>WC(l,e)),dm(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,GC(l,e.cause))};yield*s.pipe(B(i=>{if(n)return cp(n);let a=o++,s=u(ap(()=>t(i,a)));return d(s),s.addObserver(r),BC(e,yC(s))}),am({disableYield:!0}),Sp(t=>BC(e,Sd(t)).pipe(mp(WC(e,t)))),dm(a))}return $C(l)})),Qw=/*#__PURE__*/ j(e=>ww(e[0]),(e,t,n)=>Jw(n?.concurrency)?$w(e,t):eT(e,t,n)),$w=(e,t)=>Ew((n,r)=>V(Aw(e)(n,r),e=>{let i,a,o=B(e,e=>(a??=tf(r),jm(Aw(t(e))(n,a),e=>(i=s(e),i)))),s=Uf(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=nf(a,Ed);return a=void 0,B(t,()=>o)});return ap(()=>i??o)})),eT=(e,t,n)=>e.pipe(Gw(t),sT(n)),tT=e=>Qw(e,M),nT=/*#__PURE__*/ j(2,(e,t)=>Ew((n,r)=>{let i=tf(r);return V(Aw(e)(n,i),e=>{let a=e.pipe(Sp(e=>{if(Wf(e))return cp(e);let o=i;return i=tf(r),nf(o,Sd(e)).pipe(mp(Aw(t(e))(n,i)),B(e=>(a=e,e)))}));return ap(()=>a)})})),rT=/*#__PURE__*/ j(2,(e,t)=>nT(e,e=>Vw(B(t(e),t=>cp(e))))),iT=/*#__PURE__*/ j(3,(e,t,n)=>nT(e,e=>{let r=t(e);return Na(r)?Rw(r.failure):n(r.success,e)})),aT=/*#__PURE__*/ j(2,(e,t)=>iT(e,od,e=>t(e))),oT=e=>aT(e,zw),sT=/*#__PURE__*/ j(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>kw(H(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:yw(s),l=yield*Ooe(!0),u=/* @__PURE__ */ new Set,d=yield*RC(t);yield*$d(o,JC(d));let f=yield*Aw(e)(i,a);return yield*R(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*um(f),yield*Np(c.take(1),mp(yC(e),sp))));let t=e===void 0?yield*f:yield*yC(e),n=tf(o),r=yield*Aw(t)(i,n);for(;u.size>=s;){let e=Zee(u);u.delete(e),u.size===0&&(yield*l.open),yield*bC(e)}let a=yield*r.pipe(hp(()=>Wre),B(e=>BC(d,e)),am({disableYield:!0}),Xp(H(function*(e){let t=qf(e),r=yield*_p(nf(n,t));if(!u.has(a))return;let i=Ad([t,r]);Od(i)&&(yield*WC(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),um);l.closeUnsafe(),u.add(a)}}).pipe(Sp(e=>{let t=Kf(e);return Pa(t)?l.whenOpen(WC(d,e)):WC(d,e)}),dm(o)),$C(d)}))),cT=/*#__PURE__*/ j(e=>ww(e[0])&&ww(e[1]),(e,t,n)=>kw(H(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*RC(0);yield*$d(a,JC(s));let c=0;function l(e,t){if(c++,!Wf(t))return WC(s,t);switch(o){case`both`:return c===2?WC(s,t):L;case`left`:case`right`:return e===o?WC(s,t):L;case`either`:return WC(s,t)}}let u=(e,t,n)=>Aw(t)(r,n).pipe(B(e=>e.pipe(B(e=>BC(s,e)),am)),Xp(t=>Zp(qf(t),e=>nf(n,e)).pipe(Fp({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),dm(a));return yield*u(`left`,e,tf(a)),yield*u(`right`,t,tf(a)),$C(s)}))),lT=()=>Ew((e,t)=>I(()=>{let t=``,n=!1,r=Ni();function i(e){let r=[];function i(e){t.length===0?r.push(e):(r.push(t+e),t=``)}for(let r=0;r<e.length;r++){let a=e[r];if(a.length!==0){let e=0,r=a.indexOf(`\r`),o=a.indexOf(`
17
+ `);for(n&&=(o===0&&(e=1,o=a.indexOf(`
18
+ `,e)),!1);r!==-1||o!==-1;)r===-1||o!==-1&&o<r?(i(a.substring(e,o)),e=o+1,o=a.indexOf(`
19
+ `,e)):(i(a.substring(e,r)),a.length===r+1?(n=!0,e=a.length,r=-1):(e=r+(o===r+1?2:1),r=a.indexOf(`\r`,e),o=a.indexOf(`
20
+ `,e)));t+=a.substring(e)}}return Wa(r)?r:null}let a=ap(()=>r._tag===`Some`?md(r.value):Pre(e,{onSuccess:o,onFailure:cp,onDone:e=>{if(r=Pi(e),t.length>0){let e=t;return t=``,n=!1,F([e])}return md(e)}}));function o(e){let t=i(e);return t===null?a:F(t)}return a})),uT=/*#__PURE__*/ j(2,(e,t)=>Ew((n,r)=>B(Aw(e)(n,r),e=>Aw(t)(e,r)))),dT=/*#__PURE__*/ j(2,(e,t)=>Ew((n,r)=>B(Aw(e)(n,r),e=>{let n=Sp(e,e=>Wf(e)?cp(e):up(pd(e)));return V(Aw(t)(n,r),e=>Cp(e,e=>fd(e)?cp(e.value):up(e)))}))),fT=e=>Ew((t,n)=>{let r;return F(ap(()=>r||e.pipe(Zd(n),B(e=>Aw(e)(t,n)),B(e=>r=e))))}),pT=/*#__PURE__*/ j(2,(e,t)=>kw((n,r,i)=>Qd(i,t).pipe(mp(Aw(e)(n,r))))),mT=/*#__PURE__*/ j(2,(e,t)=>pT(e,e=>t)),hT=(e,t,n)=>ap(()=>{let r=Xd(),i=Aw(e)(md(),r);return Uf(B(i,t),n||F).pipe(Qp(e=>nf(r,e)))}),gT=/*#__PURE__*/ j(2,(e,t)=>Ew((n,r)=>V(Bp(Aw(e)(n,r),t),Bp(t)))),_T=/*#__PURE__*/ j(2,(e,t)=>hT(e,e=>am(B(e,t),{disableYield:!0}))),vT=/*#__PURE__*/ j(3,(e,t,n)=>ap(()=>{let r=t();return hT(e,e=>tp({while:Mt,body:()=>e,step:e=>{r=n(r,e)}}),()=>F(r))})),yT=(e,t)=>Aw(e)(md(),t),bT=`~effect/PlatformError`;var xT=class extends (/*#__PURE__*/ jo(`BadArgument`)){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:``}`}},ST=class extends Ao{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor===void 0?``:` (${this.pathOrDescriptor})`}${this.description?`: ${this.description}`:``}`}},CT=class extends (/*#__PURE__*/ jo(`PlatformError`)){constructor(e){`cause`in e?super({reason:e,cause:e.cause}):super({reason:e})}[bT]=bT;get message(){return this.reason.message}};const wT=e=>new CT(new ST(e)),TT=e=>new CT(new xT(e)),ET={_R:M,_E:M,_A:M},DT=function(e){this.channel=e};DT.prototype={"~effect/Stream":ET,pipe(){return Ot(this,arguments)}};const OT=e=>new DT(e),kT=`~effect/Sink`,AT=/*#__PURE__*/ F([void 0]),jT={_A:M,_In:M,_L:M,_E:M,_R:M},MT={[kT]:jT,pipe(){return Ot(this,arguments)}},NT=e=>N(e,kT),PT=e=>FT((t,n)=>Aw(e)(t,n).pipe(B(am({disableYield:!0})),Uf(F))),FT=e=>{let t=Object.create(MT);return t.transform=e,t},ase=e=>Ew((t,n)=>F(B(e.transform(t,n),md))),IT=/*#__PURE__*/ FT(e=>Uf(am(e,{disableYield:!0}),()=>AT)),ose=e=>sse(ep(t=>e(t),{discard:!0})),sse=e=>FT(t=>t.pipe(B(e),am({disableYield:!0}),Uf(()=>AT))),cse=e=>PT(fT(V(e,ase))),LT=`~effect/RcMap`,lse=e=>({[LT]:LT,lookup:e.lookup,context:e.context,scope:e.scope,idleTimeToLive:e.idleTimeToLive,capacity:e.capacity,state:{_tag:`Open`,map:Rre()},pipe(){return Ot(this,arguments)}}),use=e=>fp(t=>{let n=t.context,r=va(n,Jd),i=lse({lookup:e.lookup,context:n,scope:r,idleTimeToLive:typeof e.idleTimeToLive==`function`?vee(e.idleTimeToLive,ao):jt(ao(e.idleTimeToLive??fo)),capacity:Math.max(e.capacity??1/0,0)});return vp(Qd(r,()=>{if(i.state._tag===`Closed`)return L;let e=i.state.map;return i.state={_tag:`Closed`},ep(e,([,e])=>_p(zT(e))).pipe(hp(()=>I(()=>{Hre(e)})))}),i)}),RT=/*#__PURE__*/ j(2,(e,t)=>im(n=>{if(e.state._tag===`Closed`)return em;let r=e.state,i=xC(),a=Yf(r.map,t),o;if(a._tag===`Some`)o=a.value,o.refCount++;else if(Number.isFinite(e.capacity)&&Ure(e.state.map)>=e.capacity)return z(new gd(`RcMap attempted to exceed capacity of ${e.capacity}`));else{o={deferred:Fd(),scope:Xd(),idleTimeToLive:e.idleTimeToLive(t),finalizer:void 0,fiber:void 0,expiresAt:0,refCount:1},o.finalizer=fse(e,t,o),Bre(r.map,t,o);let n=new Map(e.context.mapUnsafe);i.context.mapUnsafe.forEach((e,t)=>{n.set(t,e)}),n.set(Jd.key,o.scope);let a=ra(n);ap(()=>e.lookup(t)).pipe(mm(a),SC(o.scope)).addObserver(n=>{kd(n)&&dse(e,t,o,a),Wd(o.deferred,n)})}let s=_a(i.context,Jd);return $d(s,o.finalizer).pipe(mp(n(Ld(o.deferred))))})),dse=(e,t,n,r)=>{if(e.state._tag===`Closed`)return;let i=Yf(e.state.map,t);i._tag!==`None`&&i.value===n&&(Zf(e.state.map,t),!(n.refCount>0)&&zT(n).pipe(mm(r),SC(e.scope)))},zT=e=>e.fiber?bC(e.fiber).pipe(mp(nf(e.scope,Ed))):nf(e.scope,Ed),fse=(e,t,n)=>fp(r=>{if(n.refCount--,n.refCount>0)return L;if(e.state._tag===`Closed`)return zT(n);let i=Yf(e.state.map,t);if(i._tag===`None`||i.value!==n)return zT(n);if(uo(n.idleTimeToLive))return Zf(e.state.map,t),zT(n);if(!lo(n.idleTimeToLive))return L;let a=r.getRef(Mf);return n.expiresAt=a.currentTimeMillisUnsafe()+yo(n.idleTimeToLive),n.fiber||=im(function r(i){let o=a.currentTimeMillisUnsafe(),s=n.expiresAt-o;if(s<=0){if(e.state._tag===`Closed`||n.refCount>0)return L;let r=Yf(e.state.map,t);return r._tag===`None`||r.value!==n?L:(Zf(e.state.map,t),nf(n.scope,Ed))}return B(i(a.sleep(go(s))),()=>r(i))}).pipe(Yp(I(()=>{n.fiber=void 0})),mm(r.context),SC(e.scope)),L}),BT={_tag:`Empty`},pse={_tag:`Closed`},mse={_A:M,_E:M};var hse=class{"~effect/RcRef"=mse;pipe(){return Ot(this,arguments)}state=BT;acquire;context;scope;idleTimeToLive;constructor(e,t,n,r){this.acquire=e,this.context=t,this.scope=n,this.idleTimeToLive=r}};const gse=e=>fp(t=>{let n=t.context,r=va(n,Jd),i=new hse(e.acquire,n,r,e.idleTimeToLive===void 0?void 0:ao(e.idleTimeToLive));return vp(Qd(r,()=>{let e=i.state;return i.state=pse,e._tag===`Acquired`?nf(e.scope,Ed):e._tag===`Acquiring`?bC(e.fiber):L}),i)}),_se=(e,t)=>{switch(e.state._tag){case`Closed`:return em;case`Acquired`:{let t=e.state;return t.refCount++,t.fiber?vp(bC(t.fiber),t):F(t)}case`Acquiring`:{let n=e.state;return n.awaiters++,VT(e,n,t)}case`Empty`:{let n={_tag:`Acquiring`,fiber:void 0,awaiters:1,acquired:void 0};e.state=n;let r=Xd(),i=Bp(e.acquire,fa(e.context,Jd,r)).pipe(B(t=>{if(e.state!==n)return em;let i={_tag:`Acquired`,value:t,scope:r,fiber:void 0,refCount:n.awaiters,invalidated:!1};return e.state=i,n.acquired=i,F(i)}),Qp(t=>Dd(t)?L:(e.state===n&&(e.state=BT),nf(r,t))));return n.fiber=mm(xC().context)(i),VT(e,n,t)}}},VT=(e,t,n)=>Qp(n(yC(t.fiber)),n=>{let r=t.acquired;return r===void 0?--t.awaiters>0||e.state!==t?L:(e.state=BT,bC(t.fiber)):Od(n)?HT(e,r):L}),vse=e=>{let t=e;return im(e=>B(Gp,n=>B(_se(t,e),e=>vp(Qd(n,()=>HT(t,e)),e.value))))},HT=(e,t)=>{if(t.refCount--,t.refCount>0)return L;let n=e.idleTimeToLive;return n===void 0||t.invalidated?(e.state===t&&(e.state=BT),nf(t.scope,Ed)):(lo(n)&&(t.fiber=im(r=>B(r(Mp(n)),()=>e.state===t&&t.refCount===0?(e.state=BT,nf(t.scope,Ed)):L)).pipe(Yp(I(()=>{t.fiber=void 0})),mm(e.context),SC(e.scope))),L)},yse=gse,UT=vse,WT=e=>N(e,`~effect/Stream`),GT=OT,bse=e=>GT(Bw(V(e,Ka))),xse=e=>KT(I(()=>{let t=!0,n=F(Ka(void 0)),r=Zre(n,e);return ap(()=>t?(t=!1,n):r)})),KT=e=>GT(Ow(e)),qT=(e,t)=>GT(Ew((n,r)=>B(yT(e.channel,r),e=>t(e,r)))),JT=e=>e.channel,Sse=(e,t)=>GT(Mw(e,t)),YT=/*#__PURE__*/ GT(Iw),XT=e=>GT(Nw(()=>e().channel)),Cse=e=>GT(Lw(e)),wse=e=>Wa(e)?GT(Fw(e)):YT,ZT=e=>GT(Hw(e)),QT=e=>GT(Uw(e)),$T=e=>GT(fT(V(e,JT))),eE=/*#__PURE__*/ j(2,(e,t)=>XT(()=>{let n=0;return GT(Gw(e.channel,qa(e=>t(e,n++))))})),Tse=/*#__PURE__*/ j(2,(e,t)=>GT(Yw(e.channel,t))),Ese=/*#__PURE__*/ j(2,(e,t)=>{let n=GT(tT(Pw(()=>Dse(e,t))));return tE.set(n,[e,t]),n}),tE=/*#__PURE__*/ new WeakMap;function*Dse(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=tE.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}const nE=/*#__PURE__*/ j(e=>WT(e[0])&&WT(e[1]),(e,t,n)=>GT(cT(JT(e),JT(t),n))),Ose=/*#__PURE__*/ j(2,(e,t)=>e.channel.pipe(nT(e=>t(e).channel),GT)),kse=/*#__PURE__*/ j(2,(e,t)=>e.channel.pipe(rT(t),GT)),Ase=e=>GT(oT(e.channel)),jse=/*#__PURE__*/ j(2,(e,t)=>{let n=Oa(t);return n===0?e:qT(e,(e,t)=>I(()=>{let t=0,r=e.pipe(B(e=>t>=n?F(e):(t+=e.length,t<=n?r:F(e.slice(n-t)))));return r}))}),rE=/*#__PURE__*/ j(2,(e,t)=>qT(e,(e,n)=>I(()=>{let r,i,a=ap(()=>{if(i!==void 0){let e=i;return i=void 0,F(e)}return e}).pipe(bp(e=>(r=Cd(e),md()))),o=V(ap(()=>t.transform(a,n)),([e,t])=>(i=t,Ka(e)));return ap(()=>r||o)}))),Mse=/*#__PURE__*/ j(2,(e,t)=>GT(dT(e.channel,t))),Nse=/*#__PURE__*/ j(e=>WT(e[0]),(e,t)=>XT(()=>{let n=new TextDecoder(t?.encoding);return eE(e,e=>n.decode(e,{stream:!0}))})),Pse=e=>XT(()=>{let t=new TextEncoder;return eE(e,e=>t.encode(e))}),Fse=e=>e.channel.pipe(uT(lT()),GT),Ise=/*#__PURE__*/ j(2,(e,t)=>GT(mT(e.channel,t))),iE=/*#__PURE__*/ j(2,(e,t)=>GT(gT(e.channel,t))),aE=/*#__PURE__*/ j(2,(e,t)=>rie(n=>yT(e.channel,n).pipe(B(e=>t.transform(e,n)),V(([e])=>e)))),Lse=e=>vT(e.channel,()=>[],(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n]);return e}),Rse=/*#__PURE__*/ j(2,(e,t)=>_T(e.channel,e=>{let n=0;return tp({while:()=>n<e.length,body:()=>t(e[n++]),step:Ft})})),oE=/*#__PURE__*/ j(2,(e,t)=>_T(e.channel,t)),zse=e=>vT(e.channel,()=>``,(e,t)=>e+t.join(``)),sE=/*#__PURE__*/ j(e=>WT(e[0]),(e,t,n)=>{let r,i,a=!1,o=CC(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=pm(Bp(oE(e,e=>o.whenOpen(I(()=>{o.closeUnsafe();for(let t=0;t<e.length;t++)n.enqueue(e[t]);r(),r=void 0}))),t)),i.addObserver(e=>{s?.removeEventListener(`abort`,c),!a&&(e._tag===`Failure`&&s?.aborted!==!0?n.error(ad(e.cause)):n.close())}),s!==void 0&&i.pollUnsafe()===void 0&&(s.aborted?c():s.addEventListener(`abort`,c,{once:!0}))},pull(){return new Promise(e=>{r=e,o.openUnsafe()})},cancel(){if(i)return a=!0,hm(yp(bC(i)))}},n?.strategy)}),Bse=/*#__PURE__*/ j(e=>WT(e[0]),(e,t)=>V(Lp(),n=>sE(e,n,t))),cE=`~effect/FileSystem`,lE=/*#__PURE__*/ P(`effect/FileSystem`),Vse=e=>lE.of({...e,[cE]:cE,exists:t=>It(e.access(t),vp(!0),xp(`PlatformError`,e=>e.reason._tag===`NotFound`?F(!1):z(e))),readFileString:(t,n)=>B(e.readFile(t),e=>dp({try:()=>new TextDecoder(n).decode(e),catch:e=>TT({module:`FileSystem`,method:`readFileString`,description:`invalid encoding`,cause:e})})),stream:H(function*(t,n){let r=yield*e.open(t,{flag:`r`}),i=n?.offset===void 0?void 0:hh(n.offset);i&&(yield*r.seek(i,`start`));let a=n?.bytesToRead===void 0?void 0:hh(n.bytesToRead),o=BigInt(0),s=Number(BigInt(n?.chunkSize??65536)),c=r.readAlloc(s);return KT(F(B(ap(()=>a!==void 0&&a<=o?md():a!==void 0&&a-o<s?r.readAlloc(Number(a-o)):c),Li({onNone:()=>md(),onSome:e=>(o+=BigInt(e.length),F(Ka(e)))}))))},$T),sink:(t,n)=>It(e.open(t,{...n,flag:n?.flag??`w`}),V(e=>ose(t=>e.writeAll(t))),cse),writeFileString:(t,n,r)=>B(dp({try:()=>new TextEncoder().encode(n),catch:e=>TT({module:`FileSystem`,method:`writeFileString`,description:`could not encode string`,cause:e})}),n=>e.writeFile(t,n,r))}),uE=`~effect/FileSystem/File`;var dE=class extends (/*#__PURE__*/ P()(`effect/FileSystem/WatchBackend`)){};const fE=`~effect/Path`,pE=/*#__PURE__*/ P(`effect/Path`),Hse=e=>pE.of({...e,[fE]:fE,resolveWithin(t,n){if(e.parse(n).root!==``)return Ni();let r=e.resolve(t),i=e.resolve(r,n),a=e.relative(r,i);return a===`..`||a.startsWith(`..${e.sep}`)||e.isAbsolute(a)?Ni():Pi(i)}});function Use(e){return{_tag:`Value`,value:e}}function Wse(e,t){return{_tag:`Record`,keys:e,value:t}}function Gse(e,t){return{_tag:`Array`,length:e,value:t}}const Kse=/*#__PURE__*/ Ea(`effect/ConfigProvider`,{defaultValue:()=>$se()}),qse={...Sr,toJSON(){return{_id:`ConfigProvider`}}},Jse=e=>e;function Yse(e,t){let n=Object.create(qse);return n.load=e,n.mapInput=t,n}function mE(e,t){return Yse(n=>e(t(n)),n=>mE(e,e=>n(t(e))))}function Xse(e){return mE(e,Jse)}function Zse(e,t){return e===``&&!t?void 0:e}function Qse(e,t){let n=t?.preserveEmptyStrings===!0,r=ece(e);return Xse(t=>F(tce(r,e,t,n)))}function $se(e){return Qse(e?.env??{...globalThis.process?.env,...import.meta.env},{preserveEmptyStrings:e?.preserveEmptyStrings})}function ece(e){let t={};for(let[n,r]of Object.entries(e)){if(r===void 0)continue;let e=n.split(`_`),i=t;for(let t of e){let e=i.children??=Object.create(null);i=e[t]??={}}}return t}function tce(e,t,n,r){let i=n.map(String).join(`_`),a=Zse(Object.hasOwn(t,i)?t[i]:void 0,r),o=nce(e,n),s=o?.children?Object.keys(o.children):[];return s.length===0?a===void 0?void 0:Use(a):s.every(ate)?Gse(Math.max(...s.map(e=>parseInt(e,10)))+1,a):Wse(new Set(s),a)}function nce(e,t){if(t.length===0)return e;let n=e;for(let e of t)if(n=n?.children?.[String(e)],!n)return;return n}const rce=/*#__PURE__*/ Mi(Uu),hE=`~effect/Config`;var gE=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}};const ice={.../*#__PURE__*/ fi({label:`Config`,evaluate(e){return this.parse(e.getRef(Kse))}}),[hE]:hE,toJSON(){return{_id:`Config`}}};function _E(e){let t=Object.create(ice);return t.evaluator=e,t.parse=t=>jm(e(t,[]),pp),t}const ace=(e,t,n)=>e.evaluator(t,n),vE=/*#__PURE__*/ j(2,(e,t)=>_E((n,r)=>Om(ace(e,n,r),e=>Na(e)?ka(t):e))),oce=e=>on(e,`SourceError`),sce=()=>`<configuration>`,yE=e=>t=>Sp(t,t=>cp(Xu(t.reasons.map(e)))),bE=(e,t)=>e.load(t).pipe(yE(e=>Yu(e)?ed(e.error).annotate(vd(e)):e),Om(n=>({provider:e,path:t,node:n,toString:sce}))),xE=(e,t)=>bE(e.provider,[...e.path,t]),SE=(e,t)=>eb(Kv,e,new bv(fv(e=>t(e)),uv())),CE=e=>{switch(e._tag){case`Union`:return e.types.every(CE);case`Objects`:case`Arrays`:case`Suspend`:return!1;default:return!0}},wE=(e,t)=>{switch(e._tag){case`Objects`:return t?._tag===`Record`;case`Arrays`:return t?._tag===`Array`;case`Union`:return e.types.some(e=>wE(e,t));case`Suspend`:return wE(e.thunk(),t);default:return t?.value!==void 0}},cce=/*#__PURE__*/ Lt(e=>{let t=/* @__PURE__ */ new WeakSet,n=Wie(e=>{switch(t.add(e),e._tag){case`Objects`:{let t=e.indexSignatures.map(e=>Pb(e.parameter)),r=H(function*(n){if(n.node?._tag!==`Record`)return;let r=n.node,i=/* @__PURE__ */ new Set;for(let t of e.propertySignatures)typeof t.name==`string`&&i.add(t.name);if(t.length>0)for(let e of r.keys)t.some(t=>t(e))&&i.add(e);let a={};for(let e of i){let t=yield*xE(n,e);t.node!==void 0&&dr(a,e,t)}return a});return SE(e.recur(n,e=>e),r)}case`Arrays`:{let t=H(function*(e){if(e.node?._tag!==`Array`)return;let t=[];for(let n=0;n<e.node.length;n++)t.push(yield*xE(e,n));return t});return SE(e.recur(n),t)}case`Union`:for(let t of e.types)n(t);if(!CE(e))return e.recur(n);break;case`Suspend`:{let r=e.thunk();return t.has(r)||n(r),e.recur(n)}case`Declaration`:case`Any`:throw new globalThis.Error(`Config.schema does not support opaque StringTree encodings`,{cause:e})}return SE(e,e=>F(e.node?.value))});return n(e)});function TE(e,t){let n=hC(e),r=ib(n.ast),i=Fb(Bx(cce(n.ast))),a=typeof t==`string`?[t]:t??[];return _E((e,t)=>{let n=[...t,...a];return bE(e,n).pipe(jm(e=>i(e).pipe(Om(ka),Mm(t=>{let i=new gE(new kx(n.length>0?new k_(n,t):t));return wE(r,e.node)?z(i):F(Aa(i))}))),yE(e=>_re(e)&&oce(e.defect)?$u(new gE(e.defect)).annotate(vd(e)):e))})}const lce=/*#__PURE__*/ AS.check(/*#__PURE__*/ OS({minimum:1,maximum:65535})),uce=e=>Ut(e)||globalThis.Array.isArray(e);function EE(e){return TE(U,e)}function dce(e,t,n){let r=uce(t),i=r?n:t,a=G(e),o=i?.separator??`,`;return TE(K([U.pipe(lS(hC(a),{decode:sie(i),encode:av(uv({strict:!1}),dv(e=>e.join(o)))})),a]),r?t:void 0)}function DE(e){return TE(Coe,e)}function fce(e){return TE(lce,e)}function pce(e){return TE(nC(U),e)}const mce=2**48-1,OE=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,hce=(e,t)=>{if(t.length!==10)throw Error(`ULID randomness must be exactly 10 bytes, received ${t.length}`);let n=Math.min(Math.max(0,Math.trunc(e)),mce),r=``;for(let e=45;e>=0;e-=5)r+=OE[Math.floor(n/2**e)&31];let i=0,a=0;for(let e of t){for(i=i<<8|e,a+=8;a>=5;)a-=5,r+=OE[i>>>a&31];i&=(1<<a)-1}return r},gce=e=>e.toString(16).padStart(2,`0`),kE=e=>[e.subarray(0,4),e.subarray(4,6),e.subarray(6,8),e.subarray(8,10),e.subarray(10,16)].map(e=>Array.from(e,gce).join(``)).join(`-`),AE=()=>globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));function _ce(e=AE()){return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e}const vce=2**48-1;function yce(e,t=AE()){let n=Math.min(Math.max(0,Math.trunc(e)),vce);return t[0]=Math.floor(n/2**40),t[1]=Math.floor(n/2**32)&255,t[2]=Math.floor(n/2**24)&255,t[3]=Math.floor(n/2**16)&255,t[4]=Math.floor(n/256)&255,t[5]=n&255,t[6]=t[6]&15|112,t[8]=t[8]&63|128,t}const jE=`~effect/Crypto`,ME=/*#__PURE__*/ P(`effect/Crypto`),bce=e=>{let t=e.randomBytes,n=e=>V(xce(`randomBytes`,e),t),r=e=>(e[0]&31)*2**48+e[1]*2**40+e[2]*2**32+e[3]*2**24+e[4]*2**16+e[5]*256+e[6],i=()=>r(t(7))/2**53,a=()=>{for(;;){let e=t(7),n=r(e);if(!(e[0]&32))return n+-(2**53-1);if(n<2**53-1)return n+1}};return ME.of({[jE]:jE,randomBytes:n,nextDoubleUnsafe:i,nextIntUnsafe:a,digest:e.digest,random:I(()=>i()),randomBoolean:I(()=>i()>.5),randomInt:I(()=>a()),randomBetween:(e,t)=>I(()=>Mre(e,t,i())),randomIntBetween(e,t,n){let r=n?.halfOpen===!0?0:1;return I(()=>{let n=Math.ceil(e),a=Math.floor(t);return Math.floor(i()*(a-n+r))+n})},randomShuffle:e=>I(()=>{let t=Array.from(e);for(let e=t.length-1;e>=1;--e){let n=Math.min(e,Math.floor(i()*(e+1))),r=t[e];t[e]=t[n],t[n]=r}return t}),randomUUIDv4:e=>I(()=>{let n=_ce(t(16));return e?.format===`bytes`?n:kE(n)}),randomUUIDv7:e=>bm(n=>{let r=yce(n.currentTimeMillisUnsafe(),t(16));return F(e?.format===`bytes`?r:kE(r))}),randomULID:bm(e=>F(hce(e.currentTimeMillisUnsafe(),t(10))))})},xce=(e,t)=>Number.isSafeInteger(t)&&t>=0?F(t):z(TT({module:`Crypto`,method:e,description:`size must be a non-negative safe integer`})),Sce=e=>fp(t=>(Ju(t,e),L)),NE=`~effect/ErrorReporter/ignore`,PE=`~effect/Match/Matcher`,Cce={[PE]:{_input:M,_filters:M,_remaining:M,_result:M,_return:M,_args:M},_tag:`TypeMatcher`,add(e){return FE(this.select,[...this.cases,e])},pipe(){return Ot(this,arguments)}};function FE(e,t){let n=Object.create(Cce);return n.select=e,n.cases=t,n}const wce={[PE]:{_input:M,_filters:M,_result:M,_return:M,_flavor:M},_tag:`ValueMatcher`,add(e){return Pa(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?IE(this.provided,ka(e.evaluate(this.provided))):this},pipe(){return Ot(this,arguments)}};function IE(e,t){let n=Object.create(wce);return n.provided=e,n.value=t,n}const LE=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),RE=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(RE),n=t.length;return e=>{if(!Array.isArray(e))return!1;for(let r=0;r<n;r++)if(t[r](e[r])===!1)return!1;return!0}}if(typeof e==`object`&&e){let t=Reflect.ownKeys(e).map(t=>[t,RE(e[t])]),n=t.length;return e=>{if(typeof e!=`object`||!e)return!1;for(let r=0;r<n;r++){let[n,i]=t[r];if(!(n in e)||i(e[n])===!1)return!1}return!0}}return t=>t===e},Tce=()=>FE(M,[]),Ece=e=>IE(e,Aa(e)),Dce=(e,t)=>n=>n.add(LE(RE(e),t)),Oce=e=>(...t)=>{let n=t[t.length-1],r=t.slice(0,-1),i=r.length===1?t=>t!=null&&t[e]===r[0]:t=>t!=null&&r.includes(t[e]);return e=>e.add(LE(i,n))},kce=e=>t=>{let n=LE(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},Ace=/*#__PURE__*/ Oce(`_tag`),jce=/*#__PURE__*/ kce(`_tag`),Mce=(...e)=>{let t=e.length;return n=>{for(let r=0;r<t;r++)if(n===e[r])return!0;return!1}},Nce=e=>t=>{let n=zE(t);return Ma(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return Pa(r)?r.success:e(r.failure,...t)}},zE=e=>{if(e._tag===`ValueMatcher`)return e.value;let t=e.cases.length;if(t===1){let t=e.cases[0];return(...n)=>{let r=e.select(...n);return t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1?ka(t.evaluate(r,...n)):Aa(r)}}return(...n)=>{let r=e.select(...n);for(let i=0;i<t;i++){let t=e.cases[i];if(t._tag===`When`&&t.guard(r)===!0||t._tag===`Not`&&t.guard(r)===!1)return ka(t.evaluate(r,...n))}return Aa(r)}},BE=`effect/match/Match/exhaustive: absurd`,Pce=e=>{let t=zE(e);if(Ma(t)){if(Pa(t))return t.success;throw Error(BE)}return(...e)=>{let n=t(...e);if(Pa(n))return n.success;throw Error(BE)}},VE=Tce,HE=Ece,UE=Dce,WE=Ace,GE=jce,KE=Mce,Fce=Ut,Ice=Wt,Lce=Gt,qE=Nce,JE=Pce,Rce={"~effect/Ref":{_A:M},...Sr,toJSON(){return{_id:`Ref`,ref:this.ref}}},zce=e=>{let t=Object.create(Rce);return t.ref=TC(e),t},Bce=e=>I(()=>zce(e)),Vce=e=>I(()=>e.ref.current),Hce=/*#__PURE__*/ j(2,(e,t)=>I(()=>EC(e.ref,t))),YE=/*#__PURE__*/ j(2,(e,t)=>e===void 0?void 0:t(e)),XE=`~effect/Stdio`,Uce=/*#__PURE__*/ P(XE),Wce=e=>({[XE]:XE,stdinIsTerminal:F(!1),stdoutIsTerminal:F(!1),stderrIsTerminal:F(!1),...e}),ZE=`~effect/Terminal`,QE=`~effect/Terminal/QuitError`;var $E=class extends (/*#__PURE__*/ dC(`QuitError`)({_tag:/*#__PURE__*/ mS(`QuitError`)})){[QE]=QE};const eD=/*#__PURE__*/ P(`effect/Terminal`),tD=e=>eD.of({...e,[ZE]:ZE}),nD=/*#__PURE__*/ vC(),rD=/*#__PURE__*/ vC(),iD=`~effect/process/ChildProcessSpawner/ChildProcessHandle`,aD={[iD]:iD,...ar,toJSON(){return{_id:`ChildProcessHandle`,pid:this.pid}}},oD=e=>Object.setPrototypeOf({...e},aD),sD=e=>{let t=(t,n)=>e(t).pipe(V(e=>Nse(n?.includeStderr===!0?e.all:e.stdout)),$T),n=(e,n)=>Fse(t(e,n));return cD.of({spawn:e,exitCode:t=>Kp(B(e(t),e=>e.exitCode)),streamString:t,streamLines:n,lines:(e,t)=>Lse(n(e,t)),string:(e,n)=>zse(t(e,n))})};var cD=class extends (/*#__PURE__*/ P()(`effect/process/ChildProcessSpawner`)){};const lD=`~effect/process/ChildProcess`,uD={.../*#__PURE__*/ fi({label:`Command`,evaluate(e){return _a(e.context,cD).spawn(this)}}),[lD]:lD},dD=(e,t,n)=>Object.assign(Object.create(uD),{_tag:`StandardCommand`,command:e,args:t,options:n}),fD=function(...e){if(pD(e[0])){let[t,...n]=e,r=gD(t,n);return dD(r[0]??``,r.slice(1),{})}if(typeof e[0]==`object`&&!Array.isArray(e[0])&&!pD(e[0])){let t=e[0];return function(e,...n){let r=gD(e,n);return dD(r[0]??``,r.slice(1),t)}}if(typeof e[0]==`string`&&!Array.isArray(e[1])){let[t,n={}]=e;return dD(t,[],n)}let[t,n=[],r={}]=e;return dD(t,n,r)},pD=e=>Array.isArray(e)&&`raw`in e&&Array.isArray(e.raw),mD=e=>{let t=/^fd(\d+)$/.exec(e);if(t===null)return;let n=parseInt(t[1],10);return n>=3?n:void 0},hD=e=>`fd${e}`,gD=(e,t)=>{let n=[];for(let[r,i]of e.entries())n=_D(e,t,n,i,r);return n},_D=(e,t,n,r,i)=>{let a=e.raw[i];if(a===void 0)throw Error(`Invalid backslash sequence: ${e.raw[i]}`);let{hasLeadingWhitespace:o,hasTrailingWhitespace:s,tokens:c}=xD(r,a),l=SD(n,c,o);if(i===t.length)return l;let u=t[i],d=Array.isArray(u)?u.map(e=>vD(e)):[vD(u)];return SD(l,d,s)},vD=e=>typeof e==`string`?e:String(e),yD=/*#__PURE__*/ new Set([` `,` `,`\r`,`
21
+ `]),bD={x:3,u:5},xD=(e,t)=>{if(t.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let n=yD.has(t[0]),r=[],i=0;for(let n=0,a=0;n<e.length;n+=1,a+=1){let o=t[a];if(yD.has(o))i!==n&&r.push(e.slice(i,n)),i=n+1;else if(o===`\\`){let e=t[a+1];if(e===`
22
+ `)--n,a+=1;else if(e===`u`&&t[a+2]===`{`){let e=t.indexOf(`}`,a+3);parseInt(t.slice(a+3,e),16)>65535&&(n+=1),a=e}else a+=bD[e]??1}}let a=i===e.length;return a||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:a}},SD=(e,t,n)=>n||e.length===0||t.length===0?[...e,...t]:[...e.slice(0,-1),`${e.at(-1)}${t.at(0)}`,...t.slice(1)],CD=(e,t,n)=>{let r=e.detached??n!==`win32`;return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}},wD=(e,t)=>(n,[r])=>{let i=`Unknown`;switch(n.code){case`ENOENT`:i=`NotFound`;break;case`EACCES`:i=`PermissionDenied`;break;case`EEXIST`:i=`AlreadyExists`;break;case`EISDIR`:i=`BadResource`;break;case`ENOTDIR`:i=`BadResource`;break;case`EBUSY`:i=`Busy`;break;case`ELOOP`:i=`BadResource`}return wT({_tag:i,module:e,method:t,pathOrDescriptor:r,syscall:n.syscall,cause:n})},TD=e=>PT(Kw(ED(e),e=>[e])),ED=e=>Ew(t=>{let n=e.evaluate();return F(DD({...e,writable:n,pull:t}))}),DD=e=>e.pull.pipe(B(t=>{let n=0;return op(r=>{let i=!1,a=()=>{for(;n<t.length;){if(i)return;if(!e.writable.write(t[n++],e.encoding)){i||e.writable.once(`drain`,a);return}}i||r(L)};return a(),I(()=>{i=!0,e.writable.off(`drain`,a)})})}),am({disableYield:!0}),e.endOnDone===!1?M:Uf(t=>`closed`in e.writable&&e.writable.closed?md(t):op(n=>{let r=()=>n(md(t));return e.writable.once(`finish`,r),e.writable.end(),I(()=>{e.writable.off(`finish`,r)})})),Np(op(t=>{let n=n=>t(z(e.onError(n)));return e.writable.once(`error`,n),I(()=>{e.writable.off(`error`,n)})}))),OD=e=>GT(kD(e)),kD=e=>Ew((t,n)=>PD({scope:n,readable:e.evaluate(),onError:e.onError??FD,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),AD=e=>Ew((t,n)=>{let r=e.evaluate(),i=TC(void 0),a=CC(!1);return DD({pull:t,writable:r,onError:e.onError??FD,endOnDone:e.endOnDone,encoding:e.encoding}).pipe(Sp(e=>(Wf(e)||(i.current=Sd(e),a.openUnsafe()),L)),dm(n),B(()=>PD({scope:n,exit:i,latch:a,readable:r,onError:e.onError??FD,chunkSize:e.chunkSize})))}),jD=/*#__PURE__*/ j(2,(e,t)=>Mse(e,AD(t))),MD=(e,t)=>{let n=ID(t?.maxBytes),r=t?.onError??FD;return op(t=>{let i=e(),a=[],o=0;return i.once(`error`,e=>{`closed`in i&&!i.closed&&i.destroy(),t(z(r(e)))}),i.once(`end`,()=>{let e=a.length===1?a[0]:Buffer.concat(a);if(e.byteOffset===0&&e.buffer.byteLength===e.byteLength)return t(F(e.buffer));t(F(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)))}),i.on(`data`,e=>{a.push(e),o+=e.length,n!==void 0&&o>n&&(`closed`in i&&!i.closed&&i.destroy(),t(z(r(/* @__PURE__ */ Error(`maxBytes exceeded`)))))}),I(()=>{`closed`in i&&!i.closed&&i.destroy()})})},ND=(e,t)=>V(MD(e,t),e=>new Uint8Array(e)),PD=e=>{let t=e.readable,n=e.closeOnDone??!0,r=e.exit??TC(void 0),i=e.latch??CC(!1);function a(){i.openUnsafe()}function o(t){r.current=Cd(e.onError(t)),i.openUnsafe()}function s(){r.current=Cd(pd()),i.openUnsafe()}t.on(`readable`,a),t.once(`error`,o),t.once(`end`,s);let c=ap(function n(){let a=e.readable.read(e.chunkSize);if(a===null)return r.current?r.current:t.readableEnded?z(pd()):(i.closeUnsafe(),B(i.await,n));let o=Ka(a);for(;a=e.readable.read(e.chunkSize),a!==null;)o.push(a);return F(o)});return vp($d(e.scope,I(()=>{t.off(`readable`,a),t.off(`error`,o),t.off(`end`,s),n&&`closed`in e.readable&&!e.readable.closed&&e.readable.destroy()})),c)},FD=e=>new _d(e),ID=e=>e===void 0||e===1/0?void 0:Number(hh(e)),LD=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),RD=(e,t,n)=>{let{commands:r}=WD(n),i=r.reduce((e,t)=>{let n=`${t.command} ${t.args.join(` `)}`;return e.length===0?n:`${e} | ${n}`},``);return wD(`ChildProcess`,e)(t,[i])},zD=1e3,BD=e=>{let t=()=>{};e.on(`error`,t),e.once(`close`,()=>e.off(`error`,t))},VD=(e,t)=>{if(!Hd(t))return!0;if(globalThis.process.platform===`win32`)return!1;try{return globalThis.process.kill(-e.pid,0),!0}catch{return!1}},HD=(e,t=()=>{})=>{e.exitCode!==null||e.signalCode!==null?t(null):ft.execFile(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{windowsHide:!0},t)},UD=/*#__PURE__*/ bf(cD,/* @__PURE__ */ R(function*(){let e=yield*lE,t=yield*pE,n=H(function*(n){if(!Yt(n.cwd))return yield*e.access(n.cwd),t.resolve(n.cwd)}),r=e=>e.extendEnv?{...globalThis.process.env,...e.env}:e.env,i=e=>WT(e)?`pipe`:e,a=e=>NT(e)?`pipe`:e,o=e=>{let t={stream:`pipe`,encoding:`utf-8`,endOnDone:!0};return Yt(e.stdin)?t:typeof e.stdin==`string`||WT(e.stdin)?{...t,stream:e.stdin}:{stream:e.stdin.stream,encoding:e.stdin.encoding??t.encoding,endOnDone:e.stdin.endOnDone??t.endOnDone}},s=(e,t)=>{let n=e[t];return Yt(n)?{stream:`pipe`}:typeof n==`string`||NT(n)?{stream:n}:{stream:n.stream}},c=e=>{if(Yt(e.additionalFds))return[];let t=[];for(let[n,r]of Object.entries(e.additionalFds)){let e=mD(n);Xt(e)&&t.push({fd:e,config:r})}return t.sort((e,t)=>e.fd-t.fd)},l=(e,t,n,r)=>{let o=[i(e.stream),a(t.stream),a(n.stream)];if(r.length===0)return o;let s=r.reduce((e,{fd:t})=>Math.max(e,t),2);for(let e=3;e<=s;e++)o[e]=`ignore`;for(let{fd:e}of r)o[e]=`pipe`;return o},u=H(function*(e,t,n){if(n.length===0)return{getInputFd:()=>IT,getOutputFd:()=>YT};let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let{config:a,fd:o}of n){let n=t.stdio[o];switch(a.type){case`input`:{let t=IT;n&&`write`in n&&(BD(n),t=TD({evaluate:()=>n,onError:t=>RD(`fromWritable(fd${o})`,LD(t),e)})),a.stream&&(yield*fm(aE(a.stream,t))),r.set(o,t);break}case`output`:{let t=YT;if(n&&`read`in n){let r=new pt;n.on(`error`,e=>r.destroy(e)),n.pipe(r),t=OD({evaluate:()=>r,onError:t=>RD(`fromReadable(fd${o})`,LD(t),e)})}a.sink&&(t=rE(t,a.sink)),i.set(o,t);break}}}return{getInputFd:e=>r.get(e)??IT,getOutputFd:e=>i.get(e)??YT}}),d=(e,t,n)=>ap(()=>{let r=IT;return Zt(t.stdin)&&(BD(t.stdin),r=TD({evaluate:()=>t.stdin,onError:t=>RD(`fromWritable(stdin)`,LD(t),e),endOnDone:n.endOnDone,encoding:n.encoding})),WT(n.stream)?vp(fm(aE(n.stream,r)),r):F(r)}),f=(e,t,n,r)=>{let i=t.stdout?(()=>{let n=new pt;return t.stdout.on(`error`,e=>n.destroy(e)),t.stdout.pipe(n),OD({evaluate:()=>n,onError:t=>RD(`fromReadable(stdout)`,LD(t),e)})})():YT,a=t.stderr?(()=>{let n=new pt;return t.stderr.on(`error`,e=>n.destroy(e)),t.stderr.pipe(n),OD({evaluate:()=>n,onError:t=>RD(`fromReadable(stderr)`,LD(t),e)})})():YT;NT(n.stream)&&(i=rE(i,n.stream)),NT(r.stream)&&(a=rE(a,r.stream));let o=nE(i,a);return{stdout:i,stderr:a,all:o}},p=(e,t)=>op(n=>{let r=Fd(),i=ft.spawn(e.command,e.args,t);return i.on(`error`,t=>{n(z(RD(`spawn`,t,e)))}),i.on(`exit`,(...e)=>{Wd(r,xd(e))}),i.on(`spawn`,()=>{n(F([i,r]))}),I(()=>{i.kill(`SIGTERM`)})}),m=(e,t,n)=>globalThis.process.platform===`win32`?op(n=>{HD(t,t=>{n(t?z(RD(`kill`,LD(t),e)):L)})}):dp({try:()=>{globalThis.process.kill(-t.pid,n)},catch:t=>RD(`kill`,LD(t),e)}),h=(e,t)=>{if(globalThis.process.platform===`win32`)HD(e);else try{globalThis.process.kill(-e.pid,t)}catch{}},g=(e,t,n)=>ap(()=>{if(!t.kill(n)){let t=new globalThis.Error(`Failed to kill child process`);return z(RD(`kill`,t,e))}return L}),_=(e,t,n)=>op(r=>{let i=Date.now()+n,a,o=()=>{clearTimeout(a),e.removeListener(`exit`,s)},s=()=>{clearTimeout(a),Date.now()>=i||!VD(e,t)?(o(),r(L)):a=setTimeout(s,10)};return e.on(`exit`,s),s(),I(o)}),v=H(function*(e,t,n,r){let i=n=>m(e,t,n).pipe(bp(()=>g(e,t,n)));yield*i(r?.killSignal??`SIGTERM`),Yt(r?.forceKillAfter)?yield*_(t,n,zD):(yield*_(t,n,yo(r.forceKillAfter)),VD(t,n)&&(yield*i(`SIGKILL`),yield*_(t,n,zD))),yield*Ld(n)}),y=(e,t)=>{let n=t??`stdout`;switch(n){case`stdout`:return e.stdout;case`stderr`:return e.stderr;case`all`:return e.all;default:{let t=mD(n);return Xt(t)?e.getOutputFd(t):e.stdout}}},b=H(function*(e){switch(e._tag){case`StandardCommand`:{let t=o(e.options),i=s(e.options,`stdout`),a=s(e.options,`stderr`),m=c(e.options),g=!0,_=yield*n(e.options),y=r(e.options),b=l(t,i,a,m),[x,S]=yield*qp(p(e,CD(e.options,{cwd:_,env:y,stdio:b},process.platform)),H(function*([t,n]){if(yield*Vd(n)){let[r]=yield*Ld(n);(r!==0&&Zt(r)||g&&process.platform!==`win32`&&e.options.detached!==!1)&&(yield*kp(v(e,t,n,e.options)))}else g&&(yield*kp(v(e,t,n,e.options)))})),ee=rD(x.pid);x.on(`exit`,t=>{t!==0&&Zt(t)&&h(x,e.options.killSignal??`SIGTERM`)});let C=I(()=>{g||=(x.ref(),!0)}),te=I(()=>(g&&=(x.unref(),!1),C)),ne=yield*d(e,x,t),{all:w,stderr:T,stdout:re}=f(e,x,i,a),{getInputFd:ie,getOutputFd:ae}=yield*u(e,x,m),oe=V(Vd(S),e=>!e),se=B(Ld(S),([t,n])=>{if(Zt(t))return F(nD(t));let r=new globalThis.Error(`Process interrupted due to receipt of signal: '${n}'`);return z(RD(`exitCode`,r,e))});return oD({pid:ee,exitCode:se,isRunning:oe,kill:t=>v(e,x,S,t),stdin:ne,stdout:re,stderr:T,all:w,getInputFd:ie,getOutputFd:ae,unref:te})}case`PipedCommand`:{let{commands:t,pipeOptions:n}=WD(e),[r,...i]=t,a=[yield*b(r)];for(let e=0;e<i.length;e++){let t=i[e],r=n[e]??{},s=o(t.options),c=$T(F(y(a[a.length-1],r.from))),l=r.to??`stdin`;if(l===`stdin`)a.push(yield*b(fD(t.command,t.args,{...t.options,stdin:{...s,stream:c}})));else{let e=mD(l);if(Xt(e)){let n=hD(e),r=t.options.additionalFds??{};a.push(yield*b(fD(t.command,t.args,{...t.options,additionalFds:{...r,[n]:{type:`input`,stream:c}}})))}else a.push(yield*b(fD(t.command,t.args,{...t.options,stdin:{...s,stream:c}})))}}let s=a[a.length-1],c=e=>ep([...a].reverse(),t=>kp(t.kill(e)),{discard:!0}),l=R(function*(){let e=[];for(let t of a)e.push(yield*t.unref);return ep([...e].reverse(),e=>e,{discard:!0})});return oD({pid:s.pid,exitCode:s.exitCode,isRunning:s.isRunning,kill:c,stdin:a[0].stdin,stdout:s.stdout,stderr:s.stderr,all:s.all,getInputFd:s.getInputFd,getOutputFd:s.getOutputFd,unref:l})}}});return sD(b)})),WD=e=>{let t=[],n=[],r=e=>{switch(e._tag){case`StandardCommand`:t.push(e);break;case`PipedCommand`:r(e.left),n.push(e.options),r(e.right)}};if(r(e),t.length===0)throw Error(`flattenCommand produced empty commands array`);let[i,...a]=t;return{commands:[i,...a],pipeOptions:n}},GD=`~effect/http/HttpBody`,KD=`~effect/http/HttpBody/HttpBodyError`;var qD=class extends (/*#__PURE__*/ jo(`HttpBodyError`)){[KD]=KD},JD=class{[GD];constructor(){this[GD]=GD}[rr](){return this.toJSON()}toString(){return qn(this,{ignoreToString:!0})}};const YD=/*#__PURE__*/ new class extends JD{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}};var XD=class extends JD{_tag=`Raw`;body;contentType;contentLength;constructor(e,t,n){super(),this.body=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Raw`,body:this.body,contentType:this.contentType,contentLength:this.contentLength}}};const ZD=(e,t)=>new XD(e,t?.contentType,t?.contentLength);var QD=class extends JD{_tag=`Uint8Array`;contentType;contentLength;text;_body;constructor(e,t,n,r){super(),this._body=e,this.text=r,this.contentType=t,this.contentLength=n}get body(){return this._body??=nO(this.text)}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}};const $D=(e,t)=>new QD(e,t??`application/octet-stream`,e.length),eO=/*#__PURE__*/ new TextEncoder,tO=globalThis.Buffer,nO=tO===void 0?e=>eO.encode(e):e=>tO.from(e,`utf8`),rO=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),tO!==void 0)return new QD(void 0,t??`text/plain`,tO.byteLength(e,`utf8`),e);let n=eO.encode(e);return new QD(n,t??`text/plain`,n.length,e)},iO=(e,t)=>rO(JSON.stringify(e),t??`application/json`),aO=(e,t)=>dp({try:()=>rO(JSON.stringify(e),t??`application/json`),catch:e=>new qD({reason:{_tag:`JsonError`},cause:e})}),oO=(e,t)=>{let n=Ib(mC(e));return(e,r)=>n(e,t).pipe(Tp(e=>new qD({reason:{_tag:`SchemaError`,issue:e},cause:e})),B(e=>aO(e,r)))};var sO=class extends JD{_tag=`Stream`;stream;contentType;contentLength;constructor(e,t,n){super(),this.stream=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Stream`,contentType:this.contentType,contentLength:this.contentLength}}};const cO=(e,t,n)=>new sO(e,t??`application/octet-stream`,n),lO=`~effect/http/HttpClientError`;var uO=class extends (/*#__PURE__*/ jo(`HttpClientError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[lO]=lO;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}};const dO=e=>e.endsWith(`Error`)?e.slice(0,-5):e,fO=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,pO=e=>`${e.method} ${Xg(e.url)}`;var mO=class extends (/*#__PURE__*/ jo(`TransportError`)){get methodAndUrl(){return pO(this.request)}get message(){return fO(dO(this._tag),this.description,this.methodAndUrl)}},hO=class extends (/*#__PURE__*/ jo(`InvalidUrlError`)){get methodAndUrl(){return pO(this.request)}get message(){return fO(dO(this._tag),this.description,this.methodAndUrl)}},gO=class extends (/*#__PURE__*/ jo(`StatusCodeError`)){get methodAndUrl(){return pO(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return fO(dO(this._tag),this.description,e)}},_O=class extends (/*#__PURE__*/ jo(`DecodeError`)){get methodAndUrl(){return pO(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return fO(dO(this._tag),this.description,e)}},vO=class extends (/*#__PURE__*/ jo(`EmptyBodyError`)){get methodAndUrl(){return pO(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return fO(dO(this._tag),this.description,e)}};const yO=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,bO=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],xO=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?kg(kg(e,`content-type`),`content-length`):(e=t.contentType===void 0?kg(e,`content-type`):Eg(e,`content-type`,t.contentType),t.contentLength===void 0?kg(e,`content-length`):Eg(e,`content-length`,t.contentLength.toString())),SO=e=>{if(e==null||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0};var CO=class extends (/*#__PURE__*/ jo(`UrlError`)){};const wO=(e,t,n)=>ja({try:()=>{let r=new URL(e,TO());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Pg(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new CO({cause:e})}),TO=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},EO=`~effect/http/HttpClientRequest`,DO={[EO]:EO,...ar,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Xg(this.url),urlParams:this.urlParams,hash:this.hash,headers:Hn(this.headers),body:this.body.toJSON()}},pipe(){return Ot(this,arguments)}};function OO(e,t,n,r,i,a){let o=Object.create(DO);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}const kO=/*#__PURE__*/ OO(`GET`,``,Wg,/*#__PURE__*/ Ni(),Cg,YD),AO=e=>(t,n)=>NO(kO,{method:e,url:t,...n??void 0}),jO=/*#__PURE__*/ AO(`GET`),MO=/*#__PURE__*/ AO(`POST`),NO=/*#__PURE__*/ j(2,(e,t)=>{let n=e;return t.method&&(n=PO(n,t.method)),t.url&&(n=zO(n,t.url)),t.headers&&(n=IO(n,t.headers)),t.urlParams&&(n=BO(n,t.urlParams)),t.hash&&(n=VO(n,t.hash)),t.body&&(n=HO(n,t.body)),t.accept&&(n=LO(n,t.accept)),t.acceptJson&&(n=RO(n)),n}),PO=/*#__PURE__*/ j(2,(e,t)=>OO(t,e.url,e.urlParams,e.hash,e.headers,e.body)),FO=/*#__PURE__*/ j(3,(e,t,n)=>OO(e.method,e.url,e.urlParams,e.hash,Eg(e.headers,t,n),e.body)),IO=/*#__PURE__*/ j(2,(e,t)=>OO(e.method,e.url,e.urlParams,e.hash,Dg(e.headers,t),e.body)),LO=/*#__PURE__*/ j(2,(e,t)=>FO(e,`Accept`,t)),RO=/*#__PURE__*/ LO(`application/json`),zO=/*#__PURE__*/ j(2,(e,t)=>{if(typeof t==`string`)return OO(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=zg(n.searchParams),i=zi(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,OO(e.method,n.toString(),r,i,e.headers,e.body)}),BO=/*#__PURE__*/ j(2,(e,t)=>OO(e.method,e.url,Gg(e.urlParams,t),e.hash,e.headers,e.body)),VO=/*#__PURE__*/ j(2,(e,t)=>OO(e.method,e.url,e.urlParams,Pi(t),e.headers,e.body)),HO=/*#__PURE__*/ j(2,(e,t)=>OO(e.method,e.url,e.urlParams,e.hash,xO(e.headers,t),t)),UO=/*#__PURE__*/ j(2,(e,t)=>HO(e,iO(t)));function WO(e){let t=wO(e.url,e.urlParams,Vi(e.hash));return Pa(t)?Pi(t.success):Ni()}const GO=`~effect/http/HttpIncomingMessage`,KO=(e,t)=>{let n=Px(mC(e)),r=t?.reviver===void 0?void 0:Px(VS(mC(e),t));return e=>r===void 0?B(e.json,e=>n(e,t)):B(e.text,i=>i===``?B(e.json,e=>n(e,t)):r(i,t))},qO=/*#__PURE__*/ Ea(`effect/http/HttpIncomingMessage/MaxBodySize`,{defaultValue:()=>void 0}),JO=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=_m(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=_m(e.text)}catch{}let i={...t,headers:Hn(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},YO=`~effect/http/HttpClientResponse`,XO=(e,t)=>new ZO(e,t);var ZO=class extends or{[GO];[YO];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[GO]=GO,this[YO]=YO}toJSON(){return JO(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split(`#`)[0];let e=WO(this.request);return Fi(e)?``:(e.value.hash=``,e.value.href)}get headers(){return wg(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Kh(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return Ni()}get stream(){return this.source.body?QT({evaluate:()=>this.source.body,onError:e=>new uO({reason:new _O({request:this.request,response:this,cause:e})})}):Cse(new uO({reason:new vO({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return B(this.text,e=>dp({try:()=>e===``?null:JSON.parse(e),catch:e=>new uO({reason:new _O({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=V(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return B(this.text,e=>dp({try:()=>zg(new URLSearchParams(e)),catch:e=>new uO({reason:new _O({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=rp({try:()=>this.source.formData(),catch:e=>new uO({reason:new _O({request:this.request,response:this,cause:e})})}).pipe($p,_m)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=rp({try:()=>this.source.arrayBuffer(),catch:e=>new uO({reason:new _O({request:this.request,response:this,cause:e})})}).pipe($p,_m),this.arrayBufferBody}pipe(){return Ot(this,arguments)}};const QO=e=>Tg({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${Li(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),$O=e=>{let t=ok(e);return Ii(t)||(t=ek(e),Ii(t))?t:tk(e)},ek=e=>{if(!(`b3`in e))return Ni();let t=e.b3.split(`-`);return t.length<2||ak(t[0],t[1])===!1?Ni():Pi(Uo({traceId:t[0],spanId:t[1],sampled:!t[2]||t[2]===`1`||t[2]===`d`}))},tk=e=>!e[`x-b3-traceid`]||!e[`x-b3-spanid`]||ak(e[`x-b3-traceid`],e[`x-b3-spanid`])===!1?Ni():Pi(Uo({traceId:e[`x-b3-traceid`],spanId:e[`x-b3-spanid`],sampled:e[`x-b3-flags`]===`1`||!e[`x-b3-sampled`]||e[`x-b3-sampled`]===`1`||e[`x-b3-sampled`]===`true`})),nk=/^[0-9a-f]{32}$/i,rk=/^[0-9a-f]{16}$/i,ik=/^(?:[0-9a-f]{16}|[0-9a-f]{32})$/i,ak=(e,t)=>ik.test(e)&&rk.test(t),ok=e=>{if(!e.traceparent)return Ni();let t=e.traceparent.split(`-`);if(t.length!==4)return Ni();let[n,r,i,a]=t;switch(n){case`00`:return nk.test(r)===!1||rk.test(i)===!1||r===`00000000000000000000000000000000`||i===`0000000000000000`?Ni():Pi(Uo({traceId:r,spanId:i,sampled:(parseInt(a,16)&1)==1}));default:return Ni()}},sk={"http:":80,"https:":443,"ws:":80,"wss:":443},ck=(e,t,n)=>{let r=Xg(t.search,n).slice(1);if(e.attribute(`url.full`,Xg(t.href,n)),e.attribute(`url.path`,t.pathname),r!==``&&e.attribute(`url.query`,r),e.attribute(`url.scheme`,t.protocol.slice(0,-1)),t.hostname!==``){e.attribute(`server.address`,t.hostname.startsWith(`[`)?t.hostname.slice(1,-1):t.hostname);let n=t.port===``?sk[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},lk=(e,t)=>{let n=e.params.filter(([,e])=>typeof e!=`string`).map(([e])=>e);return n.length===0?t:[...t,...new URLSearchParams(n.map(e=>[e,``])).keys()]},uk=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Mg(a,i)?`<redacted>`:n[a])},dk=`~effect/http/HttpClient`,fk=/*#__PURE__*/ P(`effect/HttpClient`),pk=/*#__PURE__*/ j(2,(e,t)=>hk(B(n=>t(e.postprocess(F(n)),n)),e.preprocess)),mk=/*#__PURE__*/ j(2,(e,t)=>hk(n=>t(e.postprocess(n)),e.preprocess)),hk=(e,t)=>{let n=Object.create(gk);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},gk={[dk]:dk,pipe(){return Ot(this,arguments)},...ar,toJSON(){return{_id:`effect/HttpClient`}},.../*#__PURE__*/ Object.fromEntries(/*#__PURE__*/ bO.map(([e,t])=>[t,function(t,n){return this.execute(AO(e)(t,n))}]))},_k=e=>hk(t=>B(t,t=>fp(n=>{let r=Ek.get(t),i=r??new AbortController,a=wO(t.url,t.urlParams,Vi(t.hash));if(Na(a))return z(new uO({reason:new hO({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(Wo)||n.getRef(bk)(t)){let a=e(t,o,i.signal,n);return r?a:im(e=>Fp(e(a),{onSuccess(e){return Tk.register(e,i),F(new Dk(e,i))},onFailure(e){return cd(e)&&i.abort(),cp(e)}}))}return sm(n.getRef(Ck)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Ng);ck(a,o,lk(t.urlParams,n.getRef(i_)));let c=n.getRef(xk);return uk(a,`request`,t.headers,c,s),t=n.getRef(Sk)?IO(t,QO(a)):t,im(l=>l(e(t,o,i.signal,n)).pipe(lm(a,{captureStackTrace:!1}),Fp({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),uk(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),vk(n,a,t,e)),r?F(e):(Tk.register(e,i),F(new Dk(e,i)))),onFailure(e){return!r&&cd(e)&&i.abort(),cp(e)}})))})})),F),vk=(e,t,n,r)=>{let i=sr();cr(0);let a;try{a=Cd(new uO({reason:new gO({request:n,response:r})}))}finally{cr(i)}t.end(e.getRef(qd)?e.getRef(Mf).currentTimeNanosUnsafe():BigInt(0),a)},yk=e=>pk(e,(e,t)=>{let n=new AbortController;return Ek.set(t,n),mp(Jp(()=>I(()=>n.abort())),e)}),bk=/*#__PURE__*/ Ea(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>Nt}),xk=/*#__PURE__*/ Ea(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>Nt}),Sk=/*#__PURE__*/ Ea(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:Mt}),Ck=/*#__PURE__*/ Ea(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),wk=e=>bf(fk)(Rp(t=>V(e,e=>mk(e,Up(e=>Ca(t,e)))))),Tk=/*#__PURE__*/ (()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=/*#__PURE__*/ new FinalizationRegistry(e=>{e.abort()});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=/*#__PURE__*/ new WeakMap;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),Ek=/*#__PURE__*/ new WeakMap;var Dk=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[YO]=YO;[GO]=GO;applyInterrupt(e){return ap(()=>(Tk.unregister(this.original),nm(e,()=>I(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return XT(()=>(Tk.unregister(this.original),Ise(this.original.stream,I(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[rr](){return this.original[rr]()}pipe(){return Ot(this,arguments)}};const Ok=/\+/g,kk=function(){};kk.prototype=/*#__PURE__*/ Object.create(null);function Ak(e){let t=new kk;if(typeof e!=`string`)return t;let n=e.length,r=``,i=``,a=-1,o=-1,s=!1,c=!1,l=!1,u=!1,d=!1,f=0;for(let p=0;p<n+1;p++)if(f=p===n?38:e.charCodeAt(p),f===38){if(d=o>a,d||(o=p),r=e.slice(a+1,o),d||r.length>0){if(l&&(r=r.replace(Ok,` `)),s)try{r=decodeURIComponent(r)||r}catch{}if(d&&(i=e.slice(o+1,p),u&&(i=i.replace(Ok,` `)),c))try{i=decodeURIComponent(i)||i}catch{}let n=t[r];n===void 0?t[r]=i:n.pop?n.push(i):t[r]=[n,i]}i=``,a=p,o=p,s=!1,c=!1,l=!1,u=!1}else f===61?o<=a?o=p:c=!0:f===43?o>a?u=!0:l=!0:f===37&&(o>a?c=!0:s=!0);return t}const jk=/^https?:\/\/.*?\//,Mk=/(\/:[^/()]*?)\?(\/?)/,Nk=[],Pk=/^[^:*(]*\/:[^/:*(.-]+$/,Fk=e=>Pk.test(e),Ik=(e={})=>new Lk(e);var Lk=class{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees=/*#__PURE__*/ Object.create(null);staticRoutes=/*#__PURE__*/ Object.create(null);singleParamRoutes=/*#__PURE__*/ Object.create(null);singleParamDisabled=/*#__PURE__*/ Object.create(null);brothersNodesStack=[];singleParamArray=[``];on(e,t,n){let r=t.match(Mk);if(r&&r.index!==void 0){Wk(t.length===r.index+r[0].length,`Optional Parameter needs to be the last parameter of the path`);let i=t.replace(Mk,`$1$2`),a=t.replace(Mk,`$2`)||`/`;this.on(e,i,n),this.on(e,a,n);return}this.options.ignoreDuplicateSlashes&&(t=Gk(t)),this.options.ignoreTrailingSlash&&(t=Kk(t));let i=typeof e==`string`?[e]:e;for(let e of i)this._on(e,t,n)}all(e,t){this.on(eA,e,t)}_on(e,t,n){this.trees[e]===void 0&&(this.trees[e]=new Vk(`/`));let r=t;if(r===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new Vk(``),this.trees[e].staticChildren[`/`]=t}let i=this.trees[e].prefix.length,a=this.trees[e],o=[];for(let e=0;e<=r.length;e++){if(r.charCodeAt(e)===58&&r.charCodeAt(e+1)===58){e++;continue}let t=r.charCodeAt(e)===58&&r.charCodeAt(e+1)!==58,n=r.charCodeAt(e)===42;if(t||n||e===r.length&&e!==i){let t=r.slice(i,e);this.options.caseSensitive||(t=t.toLowerCase()),t=t.split(`::`).join(`:`),t=t.split(`%`).join(`%25`),a=a.createStaticChild(t)}if(t){let t=!1,n=!0,s=``,c=[],l=``,u=e+1;for(let d=u;;d++){let f=r.charCodeAt(d),p=f===40,m=f===45||f===46,h=f===47||d===r.length;if(p||m||h){let f=r.slice(u,d);if(o.push(f),t=t||p||m,p){let e=Jk(r,d),t=r.slice(d,e+1);c.push(Yk(t)),d=e+1,n=!0}else c.push(n?`(.*?)`:`(${s}|(?:(?!${s}).)*)`),n=!1;let g=d;for(;d<r.length;d++){let e=r.charCodeAt(d);if(e===47)break;if(e===58){if(r.charCodeAt(d+1)===58)d++;else break}}let _=r.slice(g,d);if(_&&(_=_.split(`::`).join(`:`),_=_.split(`%`).join(`%25`),c.push(s=Xk(_))),u=d+1,l+=`()`+_,h||r.charCodeAt(d)===47||d===r.length){let n=t?l:_,o=r.slice(e,d);r=r.slice(0,e+1)+n+r.slice(d),e+=n.length;let s=t?RegExp(`^`+c.join(``)+`$`):void 0;a=a.createParametricChild(s,_,o),i=e+1;break}}}}else if(n&&(o.push(`*`),a=a.createWildcardChild(),i=e+1,e!==r.length-1))throw Error(`Wildcard must be the last character in the route`)}this.options.caseSensitive||(r=r.toLowerCase()),r===`*`&&(r=`/*`);for(let t of this.routes)if(t.method===e&&t.pattern===r)throw Error(`Method '${e}' already declared for route '${r}'`);let s={method:e,path:t,pattern:r,params:o,handler:n};if(this.routes.push(s),a.addRoute(s),o.length===0){let t=r.split(`::`).join(`:`).split(`%`).join(`%25`),n=this.staticRoutes[e]??=/* @__PURE__ */ new Map;n.has(t)||n.set(t,a.handlerStorage.unconstrainedHandler)}else if(Fk(t)){if(this.singleParamDisabled[e]!==!0){let n=t.slice(0,t.indexOf(`:`));this.options.caseSensitive||(n=n.toLowerCase()),n=n.split(`%`).join(`%25`);let r=this.singleParamRoutes[e]??=/* @__PURE__ */ new Map;r.has(n)||r.set(n,a.handlerStorage.unconstrainedHandler)}}else/[(*]|[^/]:|:[^/]*[-.]/.test(t)&&(this.singleParamDisabled[e]=!0,delete this.singleParamRoutes[e])}has(e,t){let n=this.trees[e];if(n===void 0)return!1;let r=n.getStaticChild(t);return r!==void 0&&r.isLeafNode}find(e,t){let n=this.trees[e];if(n===void 0)return;let r=``,i=!1,a=t.charCodeAt(0)===47&&(t.length===1||t.charCodeAt(t.length-1)!==47);if(a)for(let e=1;e<t.length;e++){let n=t.charCodeAt(e);if(n===37||n===63||n===59||n===35||n>=65&&n<=90||n===47&&t.charCodeAt(e-1)===47){a=!1;break}}if(!a){t.charCodeAt(0)!==47&&(t=t.replace(jk,`/`));let e;try{e=Qk(t),t=e.path,r=e.querystring,i=e.shouldDecodeParam}catch{return}this.options.ignoreDuplicateSlashes&&(t=Gk(t)),this.options.ignoreTrailingSlash&&(t=Kk(t))}let o=t;!a&&this.options.caseSensitive===!1&&(t=t.toLowerCase());let s=this.options.maxParamLength,c=this.staticRoutes[e];if(c!==void 0){let e=c.get(t);if(e!==void 0)return{handler:e.handler,params:e.createParams(Nk),searchParams:Ak(r)}}let l=this.singleParamRoutes[e];if(l!==void 0){let e=t.lastIndexOf(`/`)+1,n=l.get(t.slice(0,e));if(n!==void 0&&t.length>e){let t=o.slice(e);if(i&&(t=$k(t)),t.length<=s)return this.singleParamArray[0]=t,{handler:n.handler,params:n.createParams(this.singleParamArray),searchParams:Ak(r)}}}let u=n.prefix.length,d=[],f=t.length,p=this.brothersNodesStack;for(p.length=0;;){if(u===f&&n.isLeafNode){let e=n.handlerStorage?.find();if(e!==void 0)return{handler:e.handler,params:e.createParams(d),searchParams:Ak(r)}}let e=n.getNextNode(t,u,p,d.length);if(e===void 0){if(p.length===0)return;let t=p.pop();u=t.brotherPathIndex,d.splice(t.paramsCount),e=t.brotherNode}for(n=e;;){if(n._tag===`StaticNode`){u+=n.prefix.length;break}if(n._tag===`WildcardNode`){let e=o.slice(u);i&&(e=$k(e)),d.push(e),u=f;break}let e=o.indexOf(`/`,u);e===-1&&(e=f);let t=o.slice(u,e);if(i&&(t=$k(t)),n.regex!==void 0){let e=n.regex.exec(t);if(e===null){if(p.length===0)return;let e=p.pop();u=e.brotherPathIndex,d.splice(e.paramsCount),n=e.brotherNode;continue}let r=!1;for(let t=1;t<e.length;t++)if((e[t]??``).length>s){r=!0;break}if(r){if(p.length===0)return;let e=p.pop();u=e.brotherPathIndex,d.splice(e.paramsCount),n=e.brotherNode;continue}for(let t=1;t<e.length;t++)d.push(e[t]??``)}else{if(t.length>s){if(p.length===0)return;let e=p.pop();u=e.brotherPathIndex,d.splice(e.paramsCount),n=e.brotherNode;continue}d.push(t)}u=e;break}}}},Rk=class{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:qk(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}},zk=class{isLeafNode=!1;routes;handlerStorage;addRoute(e){this.routes===void 0?this.routes=[e]:this.routes.push(e),this.handlerStorage===void 0&&(this.handlerStorage=new Rk),this.isLeafNode=!0,this.handlerStorage.add(e)}},Bk=class extends zk{staticChildren=/*#__PURE__*/ Object.create(null);findStaticMatchingChild(e,t){let n=this.staticChildren[e.charAt(t)];if(n!==void 0&&n.matchPrefix(e,t))return n}getStaticChild(e,t=0){if(e.length===t)return this;let n=this.findStaticMatchingChild(e,t);if(n!==void 0)return n.getStaticChild(e,t+n.prefix.length)}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let n=e.charAt(0);return this.staticChildren[n]=new Vk(e),this.staticChildren[n]}},Vk=class e extends Bk{_tag=`StaticNode`;constructor(e){super(),this.setPrefix(e)}prefix;matchPrefix;parametricChildren=[];wildcardChild;setPrefix(e){if(this.prefix=e,e.length===1)this.matchPrefix=(e,t)=>!0;else{let t=e.slice(1);this.matchPrefix=(e,n)=>e.startsWith(t,n+1)}}getParametricChild(e){if(e===void 0)return this.parametricChildren.find(e=>e.isRegex===!1);let t=e.source;return this.parametricChildren.find(e=>e.regex!==void 0&&e.regex.source===t)}createParametricChild(e,t,n){let r=this.getParametricChild(e);return r===void 0?(r=new Hk(e,t,n),this.parametricChildren.push(r),this.parametricChildren.sort((e,t)=>e.isRegex?t.isRegex?e.staticSuffix===void 0?1:t.staticSuffix===void 0?-1:t.staticSuffix.endsWith(e.staticSuffix)?1:e.staticSuffix.endsWith(t.staticSuffix)?-1:0:-1:1),r):(r.nodePaths.add(n),r)}createWildcardChild(){return this.wildcardChild===void 0&&(this.wildcardChild=new Uk),this.wildcardChild}split(t,n){let r=this.prefix.slice(0,n),i=this.prefix.slice(n);this.setPrefix(i);let a=new e(r);return a.staticChildren[i.charAt(0)]=this,t.staticChildren[r.charAt(0)]=a,a}getNextNode(e,t,n,r){let i=this.findStaticMatchingChild(e,t),a=0;if(i===void 0){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],a=1}this.wildcardChild!==void 0&&n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let e=this.parametricChildren.length-1;e>=a;e--)n.push({paramsCount:r,brotherPathIndex:t,brotherNode:this.parametricChildren[e]});return i}},Hk=class extends Bk{_tag=`ParametricNode`;regex;staticSuffix;constructor(e,t,n){super(),this.regex=e,this.staticSuffix=t,this.isRegex=!!e,this.nodePaths=/* @__PURE__ */ new Set([n])}isRegex;nodePaths;getNextNode(e,t){return this.findStaticMatchingChild(e,t)}},Uk=class extends zk{_tag=`WildcardNode`;getNextNode(e,t,n,r){}};const Wk=(e,t)=>{if(!e)throw Error(t)};function Gk(e){return e.indexOf(`//`)===-1?e:e.replace(/\/\/+/g,`/`)}function Kk(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function qk(e){let t=e.length;return t===0?()=>Object.create(null):function(n){let r=Object.create(null);for(let i=0;i<t;i++)r[e[i]]=n[i];return r}}function Jk(e,t){let n=1;for(;t<e.length;)if(t++,e[t]===`\\`)t++;else if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t;throw TypeError(`Invalid regexp expression in "`+e+`"`)}function Yk(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function Xk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Zk(e,t){if(e===50)return t===53?`%`:t===51?`#`:t===52?`$`:t===54?`&`:t===66||t===98?`+`:t===67||t===99?`,`:t===70||t===102?`/`:void 0;if(e===51)return t===65||t===97?`:`:t===66||t===98?`;`:t===68||t===100?`=`:t===70||t===102?`?`:void 0;if(e===52&&t===48)return`@`}function Qk(e){let t=!1,n=!1,r=``;for(let i=1;i<e.length;i++){let a=e.charCodeAt(i);if(a===37){let r=e.charCodeAt(i+1),a=e.charCodeAt(i+2);Zk(r,a)===void 0?t=!0:(n=!0,r===50&&a===53&&(t=!0,e=e.slice(0,i+1)+`25`+e.slice(i+1),i+=2),i+=2)}else if(a===63||a===59||a===35){r=e.slice(i+1),e=e.slice(0,i);break}}return{path:t?decodeURI(e):e,querystring:r,shouldDecodeParam:n}}function $k(e){let t=e.indexOf(`%`);if(t===-1)return e;let n=``,r=t;for(let i=t;i<e.length;i++)if(e.charCodeAt(i)===37){if(i+2>=e.length)break;let t=Zk(e.charCodeAt(i+1),e.charCodeAt(i+2));n+=e.slice(r,i)+t,r=i+3}return e.slice(0,t)+n+e.slice(r)}const eA=/* @__PURE__ */ `ACL.BIND.CHECKOUT.CONNECT.COPY.DELETE.GET.HEAD.LINK.LOCK.M-SEARCH.MERGE.MKACTIVITY.MKCALENDAR.MKCOL.MOVE.NOTIFY.OPTIONS.PATCH.POST.PROPFIND.PROPPATCH.PURGE.PUT.QUERY.REBIND.REPORT.SEARCH.SOURCE.SUBSCRIBE.TRACE.UNBIND.UNLINK.UNLOCK.UNSUBSCRIBE`.split(`.`),tA=Ik,nA=e=>{switch(e._tag){case`Weak`:return`W/"${e.value}"`;case`Strong`:return`"${e.value}"`}};var rA=class extends (/*#__PURE__*/ P()(`effect/http/Etag/Generator`)){};const iA=e=>{let t=Li(e.mtime,{onNone:()=>`0`,onSome:e=>e.getTime().toString(16)});return`${e.size.toString(16)}-${t}`},aA=e=>`${e.size.toString(16)}-${e.lastModified.toString(16)}`,oA=/*#__PURE__*/ _f(rA)({fromFileInfo(e){return I(()=>({_tag:`Strong`,value:iA(e)}))},fromFileWeb(e){return I(()=>({_tag:`Strong`,value:aA(e)}))}}),sA=/*#__PURE__*/ _f(rA)({fromFileInfo(e){return I(()=>({_tag:`Weak`,value:iA(e)}))},fromFileWeb(e){return I(()=>({_tag:`Weak`,value:aA(e)}))}}),cA=/*#__PURE__*/ Object.getPrototypeOf(Cg),lA=()=>Object.create(cA),uA=`~effect/http/HttpServerResponse`,dA=e=>N(e,uA),fA=e=>PA({status:e?.status??204,statusText:e?.statusText,headers:e?.headers?wg(e.headers):void 0,cookies:e?.cookies}),pA=(e,t)=>{let n=Tg({location:e.toString()});return PA({status:t?.status??302,statusText:t?.statusText,headers:t?.headers?Og(n,wg(t.headers)):n,cookies:t?.cookies??Jh})},mA=(e,t)=>{let n=t?.headers?wg(t.headers):Cg;return PA({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??Jh,body:$D(e,hA(t,n))})},hA=(e,t)=>{if(e?.contentType)return e.contentType;if(e?.headers)return t[`content-type`]},gA=(e,t)=>{let n=t?.headers?wg(t.headers):Cg;return PA({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??Jh,body:rO(e,hA(t,n))})},_A=(e,t)=>{let n=oO(e,t);return(e,t)=>{let r=t?.headers?wg(t.headers):Cg;return V(n(e,hA(t,r)),e=>PA({status:t?.status??200,statusText:t?.statusText,headers:r,cookies:t?.cookies,body:e}))}},vA=(e,t)=>{let n=t?.headers?wg(t.headers):Cg;return PA({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:iO(e,hA(t,n))})},yA=(e,t)=>{let n=t?.headers?wg(t.headers):Cg;return PA({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:rO(Kg(zg(e)),hA(t,n)??`application/x-www-form-urlencoded`)})},bA=(e,t)=>PA({status:t?.status??200,statusText:t?.statusText,headers:t?.headers&&wg(t.headers),cookies:t?.cookies,body:ZD(e,{contentType:t?.contentType,contentLength:t?.contentLength})}),xA=(e,t)=>{let n=t?.headers?wg(t.headers):Cg;return PA({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:cO(e,hA(t,n),t?.contentLength)})},SA=/*#__PURE__*/ j(3,(e,t,n)=>PA(e,Eg(e.headers,t,n))),CA=/*#__PURE__*/ j(2,(e,t)=>PA({...e,headers:kg(e.headers,t)})),wA=/*#__PURE__*/ j(2,(e,t)=>PA(e,Dg(e.headers,t))),TA=/*#__PURE__*/ j(e=>dA(e[0]),(e,t,n,r)=>V(pp(ig(e.cookies,t,n,r)),t=>PA({...e,cookies:t}))),EA=/*#__PURE__*/ j(2,(e,t)=>PA({...e,cookies:rg(e.cookies,t)})),DA=/*#__PURE__*/ j(2,(e,t)=>PA({...e,body:t},xO(e.headers,t))),OA=/*#__PURE__*/ j(e=>dA(e[0]),(e,t,n)=>PA({...e,status:t,statusText:n??e.statusText})),kA=(e,t=!1)=>t||e.status===204||e.status===205||e.status===304,AA=(e,t)=>{for(let[n,r]of t)n===`set-cookie`?e.append(n,r):e.set(n,r);return e},jA=(e,t)=>{let n=new globalThis.Headers(e.headers);if(!Yh(e.cookies)){let t=cg(e.cookies);for(let e of t)n.append(`set-cookie`,e)}let r=e.body,i=kA(e),a=i||t?.withoutBody===!0;if(r._tag===`Raw`&&r.body instanceof Response){let t=r.body;if(!a){if(n.keys().next().done)return t;let e=new Response(t.body,t);return AA(e.headers,n),e}let o=i?e:t;return new Response(void 0,{status:o.status,statusText:o.statusText,headers:AA(new globalThis.Headers(t.headers),n)})}if(a)return r._tag===`Raw`&&MA(r.body)&&r.body.cancel().catch(Ft),new Response(void 0,{status:e.status,statusText:e.statusText,headers:n});switch(r._tag){case`Empty`:return new Response(void 0,{status:e.status,statusText:e.statusText,headers:n});case`Uint8Array`:return new Response(r.text??r.body,{status:e.status,statusText:e.statusText,headers:n});case`Raw`:return new Response(r.body,{status:e.status,statusText:e.statusText,headers:n});case`FormData`:return new Response(r.formData,{status:e.status,statusText:e.statusText,headers:n});case`Stream`:return new Response(sE(r.stream,t?.context??la(),{signal:t?.signal}),{status:e.status,statusText:e.statusText,headers:n})}},MA=e=>typeof ReadableStream<`u`&&e instanceof ReadableStream,NA={...Sr,[uA]:uA,[NE]:!0,toJSON(){return{_id:`HttpServerResponse`,status:this.status,statusText:this.statusText,headers:Hn(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}},PA=(e,t)=>{let n=Object.create(NA);if(n.status=e.status,n.statusText=e.statusText,n.cookies=e.cookies??Jh,n.body=e.body??YD,n.body._tag!==`Empty`&&(n.body.contentType||n.body.contentLength!==void 0)){let r=t!==void 0,i=r?t:e.headers===void 0||e.headers===Cg?lA():Tg({...e.headers});n.body.contentType&&(!r||i[`content-type`]===void 0)&&(i[`content-type`]=n.body.contentType),n.body.contentLength!==void 0&&(!r||i[`content-length`]===void 0)&&(i[`content-length`]=n.body.contentLength.toString()),n.headers=i}else n.headers=t??e.headers??Cg;return n},FA=e=>{let t=new globalThis.Headers(e.headers),n=t.getSetCookie();t.delete(`set-cookie`);let r=fA({status:e.status,statusText:e.statusText,headers:t,cookies:Kh(n)});if(e.body){let t=e.headers.get(`content-type`);r=DA(r,cO(QT({evaluate:()=>e.body,onError:e=>e}),t??void 0,SO(e.headers.get(`content-length`))))}return r},IA=(e,t)=>{let n=e.vary;if(n===void 0)return t;let r=n.split(`,`).map(e=>e.trim().toLowerCase());return r.includes(`*`)||r.includes(t.toLowerCase())?n:`${n}, ${t}`},LA=e=>({algorithms:e.algorithms,compressResponse(t,n,r){return V(e.compressResponse(t,n,r),e=>{if(e===t)return t;let r={"content-encoding":n,vary:IA(e.headers,`Accept-Encoding`)},i=e.headers.etag;return i!==void 0&&!i.startsWith(`W/`)&&(r.etag=`W/${i}`),wA(e,r)})}}),RA={"application/andrew-inset":[`ez`],"application/appinstaller":[`appinstaller`],"application/applixware":[`aw`],"application/appx":[`appx`],"application/appxbundle":[`appxbundle`],"application/atom+xml":[`atom`],"application/atomcat+xml":[`atomcat`],"application/atomdeleted+xml":[`atomdeleted`],"application/atomsvc+xml":[`atomsvc`],"application/atsc-dwd+xml":[`dwd`],"application/atsc-held+xml":[`held`],"application/atsc-rsat+xml":[`rsat`],"application/automationml-aml+xml":[`aml`],"application/automationml-amlx+zip":[`amlx`],"application/bdoc":[`bdoc`],"application/calendar+xml":[`xcs`],"application/ccxml+xml":[`ccxml`],"application/cdfx+xml":[`cdfx`],"application/cdmi-capability":[`cdmia`],"application/cdmi-container":[`cdmic`],"application/cdmi-domain":[`cdmid`],"application/cdmi-object":[`cdmio`],"application/cdmi-queue":[`cdmiq`],"application/cpl+xml":[`cpl`],"application/cu-seeme":[`cu`],"application/cwl":[`cwl`],"application/dash+xml":[`mpd`],"application/dash-patch+xml":[`mpp`],"application/davmount+xml":[`davmount`],"application/dicom":[`dcm`],"application/docbook+xml":[`dbk`],"application/dssc+der":[`dssc`],"application/dssc+xml":[`xdssc`],"application/ecmascript":[`ecma`],"application/emma+xml":[`emma`],"application/emotionml+xml":[`emotionml`],"application/epub+zip":[`epub`],"application/exi":[`exi`],"application/express":[`exp`],"application/fdf":[`fdf`],"application/fdt+xml":[`fdt`],"application/font-tdpfr":[`pfr`],"application/geo+json":[`geojson`],"application/gml+xml":[`gml`],"application/gpx+xml":[`gpx`],"application/gxf":[`gxf`],"application/gzip":[`gz`],"application/hjson":[`hjson`],"application/hyperstudio":[`stk`],"application/inkml+xml":[`ink`,`inkml`],"application/ipfix":[`ipfix`],"application/its+xml":[`its`],"application/java-archive":[`jar`,`war`,`ear`],"application/java-serialized-object":[`ser`],"application/java-vm":[`class`],"application/javascript":[`*js`],"application/json":[`json`,`map`],"application/json5":[`json5`],"application/jsonml+json":[`jsonml`],"application/ld+json":[`jsonld`],"application/lgr+xml":[`lgr`],"application/lost+xml":[`lostxml`],"application/mac-binhex40":[`hqx`],"application/mac-compactpro":[`cpt`],"application/mads+xml":[`mads`],"application/manifest+json":[`webmanifest`],"application/marc":[`mrc`],"application/marcxml+xml":[`mrcx`],"application/mathematica":[`ma`,`nb`,`mb`],"application/mathml+xml":[`mathml`],"application/mbox":[`mbox`],"application/media-policy-dataset+xml":[`mpf`],"application/mediaservercontrol+xml":[`mscml`],"application/metalink+xml":[`metalink`],"application/metalink4+xml":[`meta4`],"application/mets+xml":[`mets`],"application/mmt-aei+xml":[`maei`],"application/mmt-usd+xml":[`musd`],"application/mods+xml":[`mods`],"application/mp21":[`m21`,`mp21`],"application/mp4":[`*mp4`,`*mpg4`,`mp4s`,`m4p`],"application/msix":[`msix`],"application/msixbundle":[`msixbundle`],"application/msword":[`doc`,`dot`],"application/mxf":[`mxf`],"application/n-quads":[`nq`],"application/n-triples":[`nt`],"application/node":[`cjs`],"application/octet-stream":[`bin`,`dms`,`lrf`,`mar`,`so`,`dist`,`distz`,`pkg`,`bpk`,`dump`,`elc`,`deploy`,`exe`,`dll`,`deb`,`dmg`,`iso`,`img`,`msi`,`msp`,`msm`,`buffer`],"application/oda":[`oda`],"application/oebps-package+xml":[`opf`],"application/ogg":[`ogx`],"application/omdoc+xml":[`omdoc`],"application/onenote":[`onetoc`,`onetoc2`,`onetmp`,`onepkg`,`one`,`onea`],"application/oxps":[`oxps`],"application/p2p-overlay+xml":[`relo`],"application/patch-ops-error+xml":[`xer`],"application/pdf":[`pdf`],"application/pgp-encrypted":[`pgp`],"application/pgp-keys":[`asc`],"application/pgp-signature":[`sig`,`*asc`],"application/pics-rules":[`prf`],"application/pkcs10":[`p10`],"application/pkcs7-mime":[`p7m`,`p7c`],"application/pkcs7-signature":[`p7s`],"application/pkcs8":[`p8`],"application/pkix-attr-cert":[`ac`],"application/pkix-cert":[`cer`],"application/pkix-crl":[`crl`],"application/pkix-pkipath":[`pkipath`],"application/pkixcmp":[`pki`],"application/pls+xml":[`pls`],"application/postscript":[`ai`,`eps`,`ps`],"application/provenance+xml":[`provx`],"application/pskc+xml":[`pskcxml`],"application/raml+yaml":[`raml`],"application/rdf+xml":[`rdf`,`owl`],"application/reginfo+xml":[`rif`],"application/relax-ng-compact-syntax":[`rnc`],"application/resource-lists+xml":[`rl`],"application/resource-lists-diff+xml":[`rld`],"application/rls-services+xml":[`rs`],"application/route-apd+xml":[`rapd`],"application/route-s-tsid+xml":[`sls`],"application/route-usd+xml":[`rusd`],"application/rpki-ghostbusters":[`gbr`],"application/rpki-manifest":[`mft`],"application/rpki-roa":[`roa`],"application/rsd+xml":[`rsd`],"application/rss+xml":[`rss`],"application/rtf":[`rtf`],"application/sbml+xml":[`sbml`],"application/scvp-cv-request":[`scq`],"application/scvp-cv-response":[`scs`],"application/scvp-vp-request":[`spq`],"application/scvp-vp-response":[`spp`],"application/sdp":[`sdp`],"application/senml+xml":[`senmlx`],"application/sensml+xml":[`sensmlx`],"application/set-payment-initiation":[`setpay`],"application/set-registration-initiation":[`setreg`],"application/shf+xml":[`shf`],"application/sieve":[`siv`,`sieve`],"application/smil+xml":[`smi`,`smil`],"application/sparql-query":[`rq`],"application/sparql-results+xml":[`srx`],"application/sql":[`sql`],"application/srgs":[`gram`],"application/srgs+xml":[`grxml`],"application/sru+xml":[`sru`],"application/ssdl+xml":[`ssdl`],"application/ssml+xml":[`ssml`],"application/swid+xml":[`swidtag`],"application/tei+xml":[`tei`,`teicorpus`],"application/thraud+xml":[`tfi`],"application/timestamped-data":[`tsd`],"application/toml":[`toml`],"application/trig":[`trig`],"application/ttml+xml":[`ttml`],"application/ubjson":[`ubj`],"application/urc-ressheet+xml":[`rsheet`],"application/urc-targetdesc+xml":[`td`],"application/voicexml+xml":[`vxml`],"application/wasm":[`wasm`],"application/watcherinfo+xml":[`wif`],"application/widget":[`wgt`],"application/winhlp":[`hlp`],"application/wsdl+xml":[`wsdl`],"application/wspolicy+xml":[`wspolicy`],"application/xaml+xml":[`xaml`],"application/xcap-att+xml":[`xav`],"application/xcap-caps+xml":[`xca`],"application/xcap-diff+xml":[`xdf`],"application/xcap-el+xml":[`xel`],"application/xcap-ns+xml":[`xns`],"application/xenc+xml":[`xenc`],"application/xfdf":[`xfdf`],"application/xhtml+xml":[`xhtml`,`xht`],"application/xliff+xml":[`xlf`],"application/xml":[`xml`,`xsl`,`xsd`,`rng`],"application/xml-dtd":[`dtd`],"application/xop+xml":[`xop`],"application/xproc+xml":[`xpl`],"application/xslt+xml":[`*xsl`,`xslt`],"application/xspf+xml":[`xspf`],"application/xv+xml":[`mxml`,`xhvml`,`xvml`,`xvm`],"application/yang":[`yang`],"application/yin+xml":[`yin`],"application/zip":[`zip`],"application/zip+dotlottie":[`lottie`],"audio/3gpp":[`*3gpp`],"audio/aac":[`adts`,`aac`],"audio/adpcm":[`adp`],"audio/amr":[`amr`],"audio/basic":[`au`,`snd`],"audio/midi":[`mid`,`midi`,`kar`,`rmi`],"audio/mobile-xmf":[`mxmf`],"audio/mp3":[`*mp3`],"audio/mp4":[`m4a`,`mp4a`,`m4b`],"audio/mpeg":[`mpga`,`mp2`,`mp2a`,`mp3`,`m2a`,`m3a`],"audio/ogg":[`oga`,`ogg`,`spx`,`opus`],"audio/s3m":[`s3m`],"audio/silk":[`sil`],"audio/wav":[`wav`],"audio/wave":[`*wav`],"audio/webm":[`weba`],"audio/xm":[`xm`],"font/collection":[`ttc`],"font/otf":[`otf`],"font/ttf":[`ttf`],"font/woff":[`woff`],"font/woff2":[`woff2`],"image/aces":[`exr`],"image/apng":[`apng`],"image/avci":[`avci`],"image/avcs":[`avcs`],"image/avif":[`avif`],"image/bmp":[`bmp`,`dib`],"image/cgm":[`cgm`],"image/dicom-rle":[`drle`],"image/dpx":[`dpx`],"image/emf":[`emf`],"image/fits":[`fits`],"image/g3fax":[`g3`],"image/gif":[`gif`],"image/heic":[`heic`],"image/heic-sequence":[`heics`],"image/heif":[`heif`],"image/heif-sequence":[`heifs`],"image/hej2k":[`hej2`],"image/ief":[`ief`],"image/jaii":[`jaii`],"image/jais":[`jais`],"image/jls":[`jls`],"image/jp2":[`jp2`,`jpg2`],"image/jpeg":[`jpg`,`jpeg`,`jpe`],"image/jph":[`jph`],"image/jphc":[`jhc`],"image/jpm":[`jpm`,`jpgm`],"image/jpx":[`jpx`,`jpf`],"image/jxl":[`jxl`],"image/jxr":[`jxr`],"image/jxra":[`jxra`],"image/jxrs":[`jxrs`],"image/jxs":[`jxs`],"image/jxsc":[`jxsc`],"image/jxsi":[`jxsi`],"image/jxss":[`jxss`],"image/ktx":[`ktx`],"image/ktx2":[`ktx2`],"image/pjpeg":[`jfif`],"image/png":[`png`],"image/sgi":[`sgi`],"image/svg+xml":[`svg`,`svgz`],"image/t38":[`t38`],"image/tiff":[`tif`,`tiff`],"image/tiff-fx":[`tfx`],"image/webp":[`webp`],"image/wmf":[`wmf`],"message/disposition-notification":[`disposition-notification`],"message/global":[`u8msg`],"message/global-delivery-status":[`u8dsn`],"message/global-disposition-notification":[`u8mdn`],"message/global-headers":[`u8hdr`],"message/rfc822":[`eml`,`mime`,`mht`,`mhtml`],"model/3mf":[`3mf`],"model/gltf+json":[`gltf`],"model/gltf-binary":[`glb`],"model/iges":[`igs`,`iges`],"model/jt":[`jt`],"model/mesh":[`msh`,`mesh`,`silo`],"model/mtl":[`mtl`],"model/obj":[`obj`],"model/prc":[`prc`],"model/step":[`step`,`stp`,`stpnc`,`p21`,`210`],"model/step+xml":[`stpx`],"model/step+zip":[`stpz`],"model/step-xml+zip":[`stpxz`],"model/stl":[`stl`],"model/u3d":[`u3d`],"model/vrml":[`wrl`,`vrml`],"model/x3d+binary":[`*x3db`,`x3dbz`],"model/x3d+fastinfoset":[`x3db`],"model/x3d+vrml":[`*x3dv`,`x3dvz`],"model/x3d+xml":[`x3d`,`x3dz`],"model/x3d-vrml":[`x3dv`],"text/cache-manifest":[`appcache`,`manifest`],"text/calendar":[`ics`,`ifb`],"text/coffeescript":[`coffee`,`litcoffee`],"text/css":[`css`],"text/csv":[`csv`],"text/html":[`html`,`htm`,`shtml`],"text/jade":[`jade`],"text/javascript":[`js`,`mjs`],"text/jsx":[`jsx`],"text/less":[`less`],"text/markdown":[`md`,`markdown`],"text/mathml":[`mml`],"text/mdx":[`mdx`],"text/n3":[`n3`],"text/plain":[`txt`,`text`,`conf`,`def`,`list`,`log`,`in`,`ini`],"text/richtext":[`rtx`],"text/rtf":[`*rtf`],"text/sgml":[`sgml`,`sgm`],"text/shex":[`shex`],"text/slim":[`slim`,`slm`],"text/spdx":[`spdx`],"text/stylus":[`stylus`,`styl`],"text/tab-separated-values":[`tsv`],"text/troff":[`t`,`tr`,`roff`,`man`,`me`,`ms`],"text/turtle":[`ttl`],"text/uri-list":[`uri`,`uris`,`urls`],"text/vcard":[`vcard`],"text/vtt":[`vtt`],"text/wgsl":[`wgsl`],"text/xml":[`*xml`],"text/yaml":[`yaml`,`yml`],"video/3gpp":[`3gp`,`3gpp`],"video/3gpp2":[`3g2`],"video/h261":[`h261`],"video/h263":[`h263`],"video/h264":[`h264`],"video/iso.segment":[`m4s`],"video/jpeg":[`jpgv`],"video/jpm":[`*jpm`,`*jpgm`],"video/mj2":[`mj2`,`mjp2`],"video/mp2t":[`ts`,`m2t`,`m2ts`,`mts`],"video/mp4":[`mp4`,`mp4v`,`mpg4`],"video/mpeg":[`mpeg`,`mpg`,`mpe`,`m1v`,`m2v`],"video/ogg":[`ogv`],"video/quicktime":[`qt`,`mov`],"video/webm":[`webm`]};Object.freeze(RA);let zA;const BA=()=>{if(zA!==void 0)return zA;let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(RA)){let a=/* @__PURE__ */ new Set;n.set(r,a);for(let n=0;n<i.length;n++){let o=i[n],s=o.startsWith(`*`);s&&(o=o.slice(1)),a.add(o),n===0&&t.set(r,o),s||e.set(o,r)}}return zA={extensionToType:e,typeToExtension:t,typeToExtensions:n},zA},VA=e=>{if(typeof e!=`string`)return Ni();let t=e.replace(/^.*[/\\]/s,``).toLowerCase(),n=t.replace(/^.*\./s,``).toLowerCase(),r=t.length<e.length;return!(n.length<t.length-1)&&r?Ni():Bi(BA().extensionToType.get(n))};var HA=class extends (/*#__PURE__*/ P()(`effect/http/HttpPlatform`)){};const UA=/*#__PURE__*/ H(function*(e){let t=yield*lE,n=yield*rA;return HA.of({platform:e.platform,compression:LA(e.compression),fileResponse:H(function*(r,i){let a=yield*t.stat(r),o=yield*n.fromFileInfo(a),s=i?.offset===void 0?uh:yield*GA(i.offset,`offset`),c=s>a.size?a.size:s,l=a.size-c,u=i?.bytesToRead===void 0?void 0:yield*GA(i.bytesToRead,`bytesToRead`),d=u===void 0||u>l?l:u,f=u===void 0?void 0:c+d,p=yield*KA(c,`offset`),m=f===void 0?void 0:yield*KA(f,`end`),h=Eg(WA(i),`etag`,nA(o));return Ii(a.mtime)&&(h[`last-modified`]=a.mtime.value.toUTCString()),e.fileResponse(r,i?.status??200,i?.statusText,h,p,m,d)}),fileWebResponse(t,r){return V(n.fromFileWeb(t),n=>{let i=Og(WA(r),Tg({etag:nA(n),"last-modified":new Date(t.lastModified).toUTCString()}));return e.fileWebResponse(t,r?.status??200,r?.statusText,i,r)})}})}),WA=e=>{let t=e?.headers?wg(e.headers):Cg;return e?.contentType?Eg(t,`content-type`,e.contentType):t},GA=(e,t)=>{let n=gh(e);return Ii(n)?F(n.value):z(TT({module:`HttpPlatform`,method:`fileResponse`,description:`Invalid ${t}: ${e}`}))},KA=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)?F(n):z(TT({module:`HttpPlatform`,method:`fileResponse`,description:`${t} exceeds the safe integer range: ${e}`}))},qA=`~effect/http/HttpServerRespondable`,JA=e=>N(e,qA),YA=/*#__PURE__*/ fA({status:400}),XA=/*#__PURE__*/ fA({status:404}),ZA=(e,t)=>dA(e)?F(e):JA(e)?Sp(e[qA](),()=>F(t)):Tx(e)?F(YA):dd(e)?F(XA):F(t),QA=(e,t)=>dA(e)?F(e):JA(e)?Sp(e[qA](),()=>F(t)):F(t),$A=`~effect/http/HttpServerError`;var ej=class extends (/*#__PURE__*/ jo(`HttpServerError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[$A]=$A;stack=`${this.name}: ${this.message}`;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}[qA](){return this.reason[qA]()}get[NE](){return this.reason[`~effect/ErrorReporter/ignore`]??!1}get message(){return this.reason.message}},tj=class extends (/*#__PURE__*/ jo(`RequestParseError`)){[qA](){return F(fA({status:400}))}get methodAndUrl(){return oj(this.request)}get message(){return sj(this._tag,this.description,this.methodAndUrl)}},nj=class extends (/*#__PURE__*/ jo(`RouteNotFound`)){[qA](){return F(fA({status:404}))}[NE]=!0;get methodAndUrl(){return oj(this.request)}get message(){return sj(this._tag,this.description,this.methodAndUrl)}};const rj=e=>N(e,$A);var ij=class extends (/*#__PURE__*/ jo(`ResponseError`)){[qA](){return F(fA({status:500}))}get methodAndUrl(){return oj(this.request)}get message(){let e=`${this._tag} (${this.response.status} ${this.methodAndUrl})`;return this.description?`${e}: ${this.description}`:e}},aj=class extends (/*#__PURE__*/ P()(`effect/http/HttpServerError/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ fa(yd,{name:`ClientAbort`,stack:Pt,parent:void 0}))};const oj=e=>`${e.method} ${Xg(e.url)}`,sj=(e,t,n)=>{let r=`${e} (${n})`;return t?`${r}: ${t}`:r},cj=e=>{let t,n=dj,r=[],i=[],a=!1;for(let o=0;o<e.reasons.length;o++){let s=e.reasons[o];switch(s._tag){case`Fail`:n=ZA(s.error,uj),r.push(s);break;case`Die`:dA(s.defect)?t=s.defect:(n=QA(s.defect,uj),r.push(s));break;case`Interrupt`:if(a=s.annotations.has(aj.key),r.length>0)break;i.push(s)}}return t?F([t,Xu(r)]):(i.length>0&&r.length===0&&(r.push(...i),n=a?fj:pj),Om(n,e=>(r.push(ed(e)),[e,Xu(r)])))},lj=e=>{let t,n=e.reasons.filter(e=>e._tag===`Die`&&dA(e.defect)?(t=e.defect,!1):!0);return[t??uj,n.length>0?Pi(Xu(n)):Ni()]},uj=/*#__PURE__*/ fA({status:500}),dj=/*#__PURE__*/ F(uj),fj=/*#__PURE__*/ F(/*#__PURE__*/ fA({status:499})),pj=/*#__PURE__*/ F(/*#__PURE__*/ fA({status:503})),mj=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,hj=/\\([\v\u0020-\u{10ffff}])/gu,gj=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,_j=/^[!#$%&'*+.^\w|~-]+$/u,vj={value:``,parameters:/*#__PURE__*/ Object.create(null)};function yj(e,t=!1){if(typeof e!=`string`)return vj;let n=e.indexOf(`;`),r=n===-1?e.trim():e.slice(0,n).trim();if((t?_j:gj).test(r)===!1)return vj;let i={value:r.toLowerCase(),parameters:Object.create(null)};if(n===-1)return i;let a,o,s;for(mj.lastIndex=n;o=mj.exec(e);){if(o.index!==n)return vj;n+=o[0].length,a=o[1].toLowerCase(),s=o[2],s[0]===`"`&&(s=s.slice(1,s.length-1),!t&&hj.test(s)&&(s=s.replace(hj,`$1`))),i.parameters[a]=s}return n===e.length?i:vj}const bj=16384,xj={key:0,whitespace:1,value:2},Sj={_tag:`Continue`},Cj=/*#__PURE__*/ new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")Cj[/*#__PURE__*/ e.charCodeAt(0)]=1;const wj=/*#__PURE__*/ new Uint8Array(256);wj[9]=1;for(let e=32;e<=126;e++)wj[e]=1;for(let e=128;e<=255;e++)wj[e]=1;function Tj(){let e=new TextDecoder,t={state:xj.key,headers:Object.create(null),key:``,value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function n(e){return t.state=xj.key,t.headers=Object.create(null),t.key=``,t.value=void 0,t.crlf=0,t.previousChunk=void 0,t.pairs=0,t.size=0,e}function r(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function i(e){return n({_tag:`Failure`,reason:e,headers:t.headers})}return function(a,o){let s=0,c;if(t.previousChunk!==void 0){s=t.previousChunk.length,c=s;let e=new Uint8Array(a.length+s);e.set(t.previousChunk),e.set(a,s),t.previousChunk=void 0,a=e}let l=a.length;outer:for(;o<l;){if(t.state===xj.key){let n=o;for(;n<l;n++){if(t.size++>bj)return i(`HeaderTooLarge`);if(a[n]===58){if(t.key+=e.decode(a.subarray(o,n)).toLowerCase(),t.key.length===0)return i(`InvalidHeaderName`);a[n+1]===32&&a[n+2]!==32&&a[n+2]!==9?(o=n+2,t.state=xj.value,t.size++):a[n+1]!==32&&a[n+1]!==9?(o=n+1,t.state=xj.value):(o=n+1,t.state=xj.whitespace);break}if(Cj[a[n]]!==1)return i(`InvalidHeaderName`)}if(n===l)return t.key+=e.decode(a.subarray(o,l)).toLowerCase(),Sj}if(t.state===xj.whitespace){for(;o<l;o++){if(t.size++>bj)return i(`HeaderTooLarge`);if(a[o]!==32&&a[o]!==9){t.state=xj.value;break}}if(o===l)return Sj}if(t.state===xj.value){let u=o;for(c!==void 0&&(u=c,c=void 0);u<l;u++){if(t.size++>bj)return i(`HeaderTooLarge`);if(a[u]===13||t.crlf>0){let c=a[u];if(c===13&&t.crlf===0&&(t.crlf=1,u++,t.size++,c=a[u]),c===10&&t.crlf===1&&(t.crlf=2,u++,t.size++,c=a[u]),c===13&&t.crlf===2&&(t.crlf=3,u++,t.size++,c=a[u]),c===10&&t.crlf===3&&(t.crlf=4,u++,t.size++),t.crlf<4&&u>=l)return t.previousChunk=a.subarray(o),Sj;if(t.crlf>=2){t.value=t.value===void 0?a.subarray(o,u-t.crlf):r(t.value,a.subarray(o,u-t.crlf));let c=e.decode(t.value);if(t.headers[t.key]===void 0?t.headers[t.key]=c:typeof t.headers[t.key]==`string`?t.headers[t.key]=[t.headers[t.key],c]:t.headers[t.key].push(c),o=u,t.size--,t.crlf!==4&&t.pairs===100)return i(`TooManyHeaders`);if(t.crlf===3)return i(`InvalidHeaderValue`);if(t.crlf===4)return n({_tag:`Headers`,headers:t.headers,endPosition:o-s});t.pairs++,t.key=``,t.value=void 0,t.crlf=0,t.state=xj.key;continue outer}}else if(wj[a[u]]!==1)return i(`InvalidHeaderValue`)}if(u===l)return t.value=t.value===void 0?a.subarray(o,l):r(t.value,a.subarray(o,l)),Sj}}return o>l&&(t.size+=l-o),Sj}}function Ej(e){let t=new TextEncoder().encode(e),n=t.length,r={};for(let e=0;e<n;e++){let n=t[e];r[n]===void 0&&(r[n]=[]),r[n].push(e)}return{needle:t,needleLength:n,indexes:r,firstByte:t[0],previousChunk:void 0,previousChunkLength:0,matchIndex:0}}function Dj(e,t,n,r){let i=Ej(e),a=r??i.needleLength;n!==void 0&&(i.previousChunk=n,i.previousChunkLength=n.length);function o(){if(`Buffer`in globalThis&&!(`Bun`in globalThis||`Deno`in globalThis))return function(e,t,n){return Buffer.prototype.indexOf.call(e,t,n)};let e=(/* @__PURE__ */ new Uint8Array(256)).fill(i.needle.length);for(let t=0,n=i.needle.length-1;t<n;++t)e[i.needle[t]]=n-t;return function(t,n,r){let a=t.length,o=r+i.needleLength-1;for(;o<a;){for(let e=i.needleLength-1,r=o;e>=0&&t[r]===n[e];e--,r--)if(e===0)return r;o+=e[t[o]]}return-1}}let s=o();function c(e){let n=e.length;if(i.previousChunk!==void 0){let t=new Uint8Array(i.previousChunkLength+n);t.set(i.previousChunk),t.set(e,i.previousChunkLength),e=t,n=i.previousChunkLength+n,i.previousChunk=void 0}let r=0;for(;r<n;){let o=n-r;if(o<a){i.previousChunk=e.subarray(r),i.previousChunkLength=o;return}let c=s(e,i.needle,r);if(c>-1)c>r&&t(i.matchIndex,e.subarray(r,c)),i.matchIndex+=1,r=c+i.needleLength;else{if(e[n-1]in i.indexes){let a=i.indexes[e[n-1]],o=-1;for(let t=0,r=a.length;t<r;t++){let r=a[t];e[n-1-r]===i.firstByte&&t>o&&(o=r)}o===-1?r===0?t(i.matchIndex,e):t(i.matchIndex,e.subarray(r)):(n-1-o>r&&t(i.matchIndex,e.subarray(r,n-1-o)),i.previousChunk=e.subarray(n-1-o),i.previousChunkLength=o+1)}else r===0?t(i.matchIndex,e):t(i.matchIndex,e.subarray(r));break}}}function l(){i.previousChunk!==void 0&&i.previousChunk!==n&&t(i.matchIndex,i.previousChunk),i.previousChunk=n,i.previousChunkLength=n?.length??0,i.matchIndex=0}return{write:c,end:l}}const Oj={headers:0,body:1},kj={_tag:`InvalidDisposition`},Aj={_tag:`EndNotReached`},jj={_tag:`ReachedLimit`,limit:`MaxParts`},Mj={_tag:`ReachedLimit`,limit:`MaxTotalSize`},Nj={_tag:`ReachedLimit`,limit:`MaxPartSize`},Pj={_tag:`ReachedLimit`,limit:`MaxFieldSize`},Fj=/*#__PURE__*/ new TextEncoder().encode(`\r
23
+ `);function Ij(e){return e.filename!==void 0||e.contentType===`application/octet-stream`}function Lj(e){return yj(e[`content-type`]).parameters.boundary}function Rj(e){}const zj=e=>e===1/0?1/0:Number(hh(e));function Bj({headers:e,onFile:t,onField:n,onError:r,onDone:i,isFile:a=Ij,maxParts:o=1/0,maxTotalSize:s=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=zj(s),d=zj(c),f=zj(l),p=Lj(e);if(p===void 0)return r({_tag:`InvalidBoundary`}),{write:Rj,end(){}};let m={state:Oj.headers,index:0,parts:0,onChunk:Rj,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0,done:!1,stopped:!1};function h(){m.state=Oj.body,m.isFile=!0,m.onChunk=Rj}function g(e){m.stopped=!0,m.state===Oj.body&&m.isFile&&m.onChunk(null),r(e)}let _=Tj(),v=Dj(`\r\n--${p}`,function(e,s){if(!m.stopped){if(e===0)h();else{if(e!==m.index){if(m.index>0){if(m.isFile)m.onChunk(null);else{if(m.fieldChunks.length===1)n(m.info,m.fieldChunks[0]);else{let e=new Uint8Array(m.fieldSize),t=0;for(let n=0;n<m.fieldChunks.length;n++){let r=m.fieldChunks[n];e.set(r,t),t+=r.length}n(m.info,e)}m.fieldSize=0,m.fieldChunks=[]}}if(m.partSize=0,m.state=Oj.headers,m.index=e,m.headerSkip=2,s[0]===45&&s[1]===45)return m.done=!0,i();if(m.parts++,m.parts>o)return g(jj)}if((m.partSize+=s.length)>d)return g(Nj);if(m.state===Oj.headers){let e=_(s,m.headerSkip);if(m.headerSkip=0,e._tag===`Continue`)return;if(e._tag===`Failure`)return h(),r({_tag:`BadHeaders`,error:e});let n=yj(e.headers[`content-type`]),i=yj(e.headers[`content-disposition`],!0);if(i.value===`form-data`&&!(`name`in i.parameters))return h(),r(kj);let o;if(`filename*`in i.parameters){let e=i.parameters[`filename*`].split(`''`);if(e.length===2)try{o=decodeURIComponent(e[1])}catch{o=e[1]}}if(m.info={name:i.parameters.name??``,filename:o??i.parameters.filename,contentType:n.value===``?i.parameters.filename===void 0?`text/plain`:`application/octet-stream`:n.value,contentTypeParameters:n.parameters,contentDisposition:i.value,contentDispositionParameters:i.parameters,headers:e.headers},m.state=Oj.body,m.isFile=a(m.info),m.isFile&&(m.onChunk=t(m.info)),e.endPosition<s.length){if(m.isFile)m.onChunk(s.subarray(e.endPosition));else{let t=s.subarray(e.endPosition);if((m.fieldSize+=t.length)>f)return g(Pj);m.fieldChunks.push(t)}}}else if(m.isFile)m.onChunk(s);else{if((m.fieldSize+=s.length)>f)return g(Pj);m.fieldChunks.push(s)}}}},Fj,2);return{write(e){if(!m.stopped)return(m.totalSize+=e.length)>u?g(Mj):v.write(e)},end(){v.end(),!m.done&&!m.stopped&&g(Aj),m.state=Oj.headers,m.index=0,m.parts=0,m.onChunk=Rj,m.info=void 0,m.totalSize=0,m.partSize=0,m.fieldChunks=[],m.fieldSize=0,m.done=!1,m.stopped=!1}}}const Vj=/*#__PURE__*/ new TextDecoder(`utf-8`);function Hj(e){if(e===`utf-8`||e===`utf8`||e===``)return Vj;try{return new TextDecoder(e)}catch{return Vj}}function Uj(e,t){return Hj(e.contentTypeParameters.charset??`utf-8`).decode(t)}const Wj=Bj,Gj=Ij,Kj=Uj,qj=`~effect/http/Multipart`,Jj=`~effect/http/Multipart/MultipartError`,Yj=e=>$j(e)?e:Qj.fromReason(`InternalError`,e);var Xj=class extends Ao{};const Zj={FileTooLarge:413,FieldTooLarge:413,BodyTooLarge:413,TooManyParts:413,InternalError:500,Parse:400};var Qj=class e extends (/*#__PURE__*/ jo(`MultipartError`)){static fromReason(t,n){return new e({reason:new Xj({_tag:t,cause:n})})}[Jj]=Jj;[NE]=!0;[qA](){return F(fA({status:Zj[this.reason._tag]}))}get message(){return this.reason._tag}};const $j=e=>N(e,Jj),eM=e=>fp(t=>{let n=va(t.context,dM);return F({headers:e,maxParts:t.getRef(cM),maxFieldSize:t.getRef(lM),maxPartSize:t.getRef(uM),maxTotalSize:t.getRef(qO),isFile:n.length===0?void 0:e=>!n.some(t=>e.contentType.includes(t))&&Gj(e)})});var tM=class extends or{[qj];constructor(){super(),this[qj]=qj}};const nM=(e,t)=>B(lE,n=>Tp(aE(t.content,n.sink(e)),Yj)),rM=/*#__PURE__*/ new TextEncoder,iM=e=>{let t=Array.from(e),n=``,r=0;for(let e=t.length-1;e>=0&&(r+=rM.encode(t[e]).length,!(r>128));e--)n=t[e]+n;return n===``||n===`.`||n===`..`?`file`:n},aM=(e,t=nM)=>R(function*(){let n=yield*lE,r=yield*pE,i=yield*n.makeTempDirectoryScoped(),a=Object.create(null),o=/* @__PURE__ */ new Set,s=0;return yield*Rse(e,e=>{if(e._tag===`Field`)return e.key in a?typeof a[e.key]==`string`?a[e.key]=[a[e.key],e.value]:a[e.key].push(e.value):a[e.key]=e.value,L;if(e.name===``)return L;let n=e,c=iM(r.basename(n.name)),l=r.join(i,c);for(;o.has(l);)l=r.join(i,`${s++}-${c}`);o.add(l);let u=new oM(n.key,n.name,n.contentType,l);return Array.isArray(a[e.key])?a[e.key].push(u):a[e.key]=[u],t(l,n)}),a}).pipe(xp(`PlatformError`,e=>z(Qj.fromReason(`InternalError`,e))));var oM=class extends tM{_tag=`PersistedFile`;key;name;contentType;path;constructor(e,t,n,r){super(),this.key=e,this.name=t,this.contentType=n,this.path=r}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`PersistedFile`,key:this.key,name:this.name,contentType:this.contentType,path:this.path}}};const sM=e=>{let t=/* @__PURE__ */ new Map;return e.maxParts!==void 0&&t.set(cM.key,e.maxParts),e.maxFieldSize!==void 0&&t.set(lM.key,hh(e.maxFieldSize)),e.maxFileSize!==void 0&&t.set(uM.key,hh(e.maxFileSize)),e.maxTotalSize!==void 0&&t.set(qO.key,hh(e.maxTotalSize)),e.fieldMimeTypes!==void 0&&t.set(dM.key,e.fieldMimeTypes),ra(t)},cM=/*#__PURE__*/ Ea(`effect/http/Multipart/MaxParts`,{defaultValue:()=>void 0}),lM=/*#__PURE__*/ Ea(`effect/http/Multipart/MaxFieldSize`,{defaultValue:/*#__PURE__*/ jt(/*#__PURE__*/ vh(10))}),uM=/*#__PURE__*/ Ea(`effect/http/Multipart/MaxFileSize`,{defaultValue:()=>void 0}),dM=/*#__PURE__*/ Ea(`effect/http/Multipart/FieldMimeTypes`,{defaultValue:/*#__PURE__*/ jt([`application/json`])}),fM=`~effect/http/HttpServerRequest`,pM=/*#__PURE__*/ P(`effect/http/HttpServerRequest`);var mM=class extends (/*#__PURE__*/ P()(`effect/http/ParsedSearchParams`)){};const Gce=(e,t)=>{let n=Nx(e);return B(pM,e=>n(e.cookies,t))},Kce=(e,t)=>{let n=Nx(e);return B(pM,e=>n(e.headers,t))},qce=(e,t)=>{let n=Nx(e);return B(mM,e=>n(e,t))},Jce=e=>{let t=e.headers.host??`localhost`,n=e.headers[`x-forwarded-proto`]===`https`?`https`:`http`;try{return Pi(new URL(e.url,`${n}://${t}`))}catch{return Ni()}},hM=/*#__PURE__*/ new WeakMap,Yce=(e,t)=>{let n=hM.get(e.source),r=n?(e,r)=>B(n(e,r),n=>t(e,n)):t;hM.set(e.source,r)},Xce=e=>e,Zce=/*#__PURE__*/ new WeakSet,Qce=e=>fp(t=>{let n=_a(t.context,pM);return Zce.add(n.source),e}),$ce=/*#__PURE__*/ Ea(`effect/http/HttpMiddleware/TracerDisabledWhen`,{defaultValue:()=>Nt}),ele=/*#__PURE__*/ Ea(`@effect/platform/HttpMiddleware/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),tle=/*#__PURE__*/ Ea(`effect/http/HttpMiddleware/TracerHeaderFilter`,{defaultValue:()=>Nt}),gM=(e,t)=>!e.cache.tracerEnabled||e.getRef($ce)(t),_M=(e,t)=>{if(!(t.status>=500&&t.status<600))return xd(t);let n=sr();cr(0);try{return Cd(new ej({reason:new ij({request:e,response:t})}))}finally{cr(n)}},vM=/*#__PURE__*/ Xce(e=>fp(t=>{let n=_a(t.context,pM);if(gM(t,n))return e;let r=t.getRef(ele),i=bu(t,r(n),{parent:Vi($O(n.headers)),kind:`server`}),a=t.context;return t.setContext(fa(t.context,Vo,i)),Nl(t,e=>{t.setContext(a);let r=t.getRef(Mf).currentTimeNanosUnsafe();if(Dd(e)&&(!i.sampled||t.getRef(Jo)===Yo)){i.end(r,_M(n,e.value));return}let o=t.getRef(Ng),s=t.getRef(tle),c,l;if(Od(e)){let[t,r]=lj(e.cause);c=t,l=Ii(r)&&(c.status>=500||cd(r.value))?Sd(r.value):_M(n,c)}else c=e.value,l=_M(n,c);if(i.sampled){i.attribute(`http.request.method`,n.method);let e=Jce(n);Ii(e)&&ck(i,e.value,t.getRef(i_)),n.headers[`user-agent`]!==void 0&&i.attribute(`user_agent.original`,n.headers[`user-agent`]),uk(i,`request`,n.headers,s,o),Ii(n.remoteAddress)&&i.attribute(`client.address`,n.remoteAddress.value),i.attribute(`http.response.status_code`,c.status),uk(i,`response`,c.headers,s,o)}i.end(r,l)}),e})),nle=(e,t,n)=>{let r=(e,n)=>{e.cause=n;let r=e.request;return jm(cj(n),([e,n])=>{let i=xC();Ju(i,n);let a=hM.get(r.source),o=n.reasons.length===0?F(e):cp(n);return a===void 0?(r[yM]=!0,jm(t(r,e),()=>o)):jm(jm(a(r,e),e=>(r[yM]=!0,t(r,e))),()=>o)})},i=(e,n)=>{let r=hM.get(e.source);return r===void 0?(e[yM]=!0,Om(t(e,n),e=>dA(e)?e:n)):jm(r(e,n),r=>(e[yM]=!0,Om(t(e,r),e=>dA(e)?e:n)))},a=a=>{let o=a.request,s=Fp(e,{onSuccess:e=>i(o,e),onFailure:e=>r(a,e)});return n===void 0?s:Fp(vM(n(s)),{onFailure(e){return Ju(xC(),e),yM in o?L:tie(cj(e),{onFailure(e){return t(o,fA({status:500}))},onSuccess([e]){return t(o,e)}})},onSuccess(e){return yM in o?L:t(o,e)}})},o=e=>vM(a(e)),s=(e,t,n)=>Zp(n,n=>{if(t.setContext(e.prev),!(bM in e.scope))return rf(e.scope,e.cause===void 0?n:Sd(e.cause))},!0);class c{scope;prev;request;cause;constructor(e,t,n){this.scope=e,this.prev=t,this.request=n}[vr](e,t){let n=i(this.request,e);if(zc(n)&&n._tag===`Success`){if(t.setContext(this.prev),bM in this.scope)return n;let e=rf(this.scope,n);return e===void 0?n:B(e,()=>n)}return s(this,t,n)}[yr](e,t){return s(this,t,r(this,e))}}return fp(t=>{Kl(t);let r=Xd(),i=new c(r,t.context,_a(t.context,pM));t.setContext(fa(i.prev,Jd,r));let l=t.cache.tracer;return n===void 0&&(l===void 0||l===Yo||gM(t,i.request))?(t._stack.push(i),e):s(i,t,n===void 0?o(i):a(i))})},yM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/handled`),bM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/scopeEjected`),rle=e=>pM.use(t=>(xM(t,e),L)),xM=Yce,ile=/*#__PURE__*/ j(2,(e,t)=>pM.use(n=>(xM(n,t),e))),SM=`~effect/http/HttpRouter`,CM=/*#__PURE__*/ P(`effect/http/HttpRouter`),ale=/*#__PURE__*/ R(function*(){let e=yield*cle,t=e.ignoreDuplicateSlashes??!0,n=tA(e),r=/* @__PURE__ */ new Set,i=e=>Rp(r=>{let i=IM(r),a=e=>{for(let t=0;t<i.length;t++)e=i[t](e);return e};for(let r=0;r<e.length;r++){let o=i.length===0?e[r]:OM({...e[r],handler:a(e[r].handler)}),s={route:o,prefixSegments:Ii(o.prefix)?sle(o.prefix.value,t):void 0};o.method===`*`?o.path.endsWith(`/*`)?(n.all(o.path,s),n.all(o.path.slice(0,-2),s)):n.all(o.path,s):o.path.endsWith(`/*`)?(n.on(o.method,o.path,s),n.on(o.method,o.path.slice(0,-2),s)):n.on(o.method,o.path,s)}return L});return CM.of({[SM]:SM,prefixed(e){return e=AM(e),CM.of({...this,prefixed:t=>this.prefixed(jM(t,e)),addAll:t=>i(t.map(dle(e))),add:(t,n,r,a)=>i([OM({method:t,path:jM(n,e),handler:dA(r)?F(r):Qf(r)?r:B(pM,r),uninterruptible:a?.uninterruptible??!1,prefix:e})])})},addAll:i,add:(e,t,n,r)=>i([kM(e,t,n,r)]),addGlobalMiddleware:e=>I(()=>{r.add(e)}),asHttpEffect(){let e=fp(e=>{let r=e.context,i=_a(r,pM),a=n.find(i.method,i.url);if(a===void 0&&i.method===`HEAD`&&(a=n.find(`GET`,i.url)),a===void 0)return z(new ej({reason:new nj({request:i})}));let{route:o,prefixSegments:s}=a.handler;if(s!==void 0&&(r=fa(r,pM,ole(i,s,t))),r=fa(r,mM,a.searchParams),r=fa(r,wM,{route:o,params:a.params}),e.getRef(Jo)!==Yo){let e=ha(r,Vo);e!==void 0&&e._tag===`Span`&&e.sampled&&e.attribute(`http.route`,o.path)}if(e.setContext(r),!o.uninterruptible){let t=ql(e);if(t!==void 0)return t}return o.handler});if(r.size===0)return e;for(let t of cte(r))e=t(e);return e}})});function ole(e,t,n){let r=e.url,i=0;for(let e=t;e>0;e--){if(n)for(;r[i]===`/`;)i++;else r[i]===`/`&&i++;for(;i<r.length&&!`/?;#`.includes(r[i]);)i++}return e.modify({url:i<r.length?r.slice(i):`/`})}function sle(e,t){let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`/`?((!t||e[i-1]!==`/`)&&n++,r=!1):a===`:`?e[i+1]===`:`?i++:r=!0:a===`-`||a===`.`?r=!1:a===`(`&&r&&(i=Jk(e,i),r=!1)}return n}const cle=/*#__PURE__*/ Ea(`effect/http/HttpRouter/RouterConfig`,{defaultValue:()=>({})});var wM=class extends (/*#__PURE__*/ P()(`effect/http/HttpRouter/RouteContext`)){};const TM=e=>Cf(B(CM,e)),EM=(e,t,n,r)=>TM(i=>i.add(e,t,n,r)),lle=/*#__PURE__*/ bf(CM)(ale),ule=e=>Rp(t=>{let n=va(t,Jd),r=hf.forkOrCreate(t);return V(gf(jf(e,lle),r,n),e=>va(e,CM).asHttpEffect())}),DM=`~effect/http/HttpRouter/Route`,OM=e=>({...e,uninterruptible:e.uninterruptible??!1,prefix:typeof e.prefix==`string`?Pi(e.prefix):e.prefix??Ni(),[DM]:DM}),kM=(e,t,n,r)=>OM({...r,method:e,path:t,handler:dA(n)?F(n):Qf(n)?n:B(pM,n),uninterruptible:r?.uninterruptible??!1}),AM=e=>e.endsWith(`/`)?e.slice(0,-1):e,jM=/*#__PURE__*/ j(2,(e,t)=>(t=AM(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),dle=/*#__PURE__*/ j(2,(e,t)=>OM({...e,path:jM(e.path,t),prefix:Li(e.prefix,{onNone:()=>AM(t),onSome:e=>jM(e,t)})})),MM=function(){return arguments.length===0?NM:NM(arguments[0],arguments[1])},NM=(e,t)=>t?.global?Cf(R(function*(){let t=yield*CM,n=Qf(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new ple(Qf(e)?Sf(V(e,e=>ra(/* @__PURE__ */ new Map([[PM,e]])))):vf(ra(/* @__PURE__ */ new Map([[PM,e]]))));let fle=0;const PM=`effect/http/HttpRouter/MiddlewareFn`;var ple=class e{"~effect/http/HttpRouter/Middleware"={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++fle}`;this.layer=Sf(R({self:this},function*(){let e=yield*Lp(),t=[ga(e,PM)];if(this.dependencies){let n=yield*hf,r=va(e,Jd),i=yield*gf(this.dependencies,n,r);t.push(...IM(i))}return ra(/* @__PURE__ */ new Map([[n,t]]))})).pipe(Af(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?jf(this.dependencies,t.layer):t.layer)}};const FM=/*#__PURE__*/ new WeakMap,IM=e=>{let t=FM.get(e);if(t)return t;let n=Ga(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=/* @__PURE__ */ new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=Ba(e).reverse()}return FM.set(e,t),t};(/*#__PURE__*/ MM(Qce)).layer;var LM=class extends (/*#__PURE__*/ P()(`effect/workers/Transferable/Collector`)){};const RM=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return LM.of({addAllUnsafe:t,addAll:e=>I(()=>t(e)),readUnsafe:n,read:I(n),clearUnsafe:r,clear:I(r)})},zM=(e,t)=>e===void 0?t:`${e}.${t}`,BM=(e,t)=>({"rpc.system.name":`effect_rpc`,"rpc.method":e,...t}),VM=`~effect/rpc/RpcSchema/StreamSchema`;function HM(e){return N(e,VM)}function UM(e){return HM(e)?Pi({success:e.success,error:e.error}):Ni()}const mle=/*#__PURE__*/ Ox(WT);function hle(e,t){return Bx(mle.ast,{[VM]:VM,success:e,error:t})}var gle=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSchema/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ fa(yd,{name:`ClientAbort`,stack:Pt,parent:void 0}))};const WM=`~effect/rpc/Rpc`;var GM=class{id;annotations;constructor(e){this.id=e,this.annotations=la()}annotate(e,t){return this.annotations=fa(this.annotations,e,t),this}};const _le={[WM]:WM,pipe(){return Ot(this,arguments)},setSuccess(e){return KM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return KM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return KM({_tag:this._tag,payloadSchema:Vx(e)?e:W(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return KM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},prefix(e){return KM({_tag:`${e}${this._tag}`,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},annotate(e,t){return KM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:fa(this.annotations,e,t)})},annotateMerge(e){return KM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:Ca(this.annotations,e)})}},KM=e=>{function t(){}return Object.setPrototypeOf(t,_le),Object.assign(t,e),t.key=`effect/rpc/Rpc/${e._tag}`,t},J=(e,t)=>{let n=t?.success??Qx,r=t?.error??qx,i=t?.defect??zS(),a;return a=t?.primaryKey?class extends uC(`effect/rpc/Rpc/${e}`)(t.payload){"~effect/PrimaryKey"(){return t.primaryKey(this)}}:Vx(t?.payload)?t?.payload:t?.payload?W(t?.payload):Qx,KM({_tag:e,payloadSchema:a,successSchema:t?.stream?hle(n,r):n,errorSchema:t?.stream?qx:r,defectSchema:i,annotations:la(),middlewares:/* @__PURE__ */ new Set})},qM=/*#__PURE__*/ new WeakMap,JM=e=>{if(qM.has(e))return qM.get(e);let t=e,n=/* @__PURE__ */ new Set([t.errorSchema]),r=UM(t.successSchema);Ii(r)&&n.add(r.value.error);for(let e of t.middlewares)n.add(e.error);let i=tC(Ii(r)?Qx:t.successSchema,K([...n]),t.defectSchema);return qM.set(e,i),i},YM=e=>`~effect/rpc/Rpc/Wrapper`in e,XM=e=>e,vle={_tag:`Eof`},ZM=e=>({_tag:`Defect`,defect:e}),yle={_tag:`Pong`},QM=mC;let ble;const $M=e=>(ble??=new TextDecoder).decode(e);var eN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSerialization`)){};const xle=/*#__PURE__*/ eN.of({contentType:`application/json`,includesFraming:!1,codecFor:QM,makeUnsafe:()=>({decode:e=>{let t=JSON.parse(typeof e==`string`?e:$M(e));return Array.isArray(t)?t:[t]},encode:e=>JSON.stringify(e)})}),tN=e=>eN.of({contentType:e?.contentType??`application/json`,includesFraming:!1,codecFor:QM,makeUnsafe:()=>{let e=/* @__PURE__ */ new Map;return{decode:t=>Sle(JSON.parse(typeof t==`string`?t:$M(t)),e),encode:t=>{let n=Cle(t,e);return n&&JSON.stringify(n)}}}});function Sle(e,t){if(Array.isArray(e)){let n={size:0,responses:/* @__PURE__ */ new Map},r=[];for(let i=0;i<e.length;i++){let a=e[i];if(!nn(a))continue;let o=nN(a);r.push(o),o._tag===`Request`&&!o.isNotification&&(n.size++,t.set(o.id,n))}return r}return nn(e)?[nN(e)]:[]}function nN(e){if(Object.hasOwn(e,`method`)){let t=e;if(Qt(t.id)&&Ut(t.method)&&t.method.startsWith(`@effect/rpc/`)){let e=t.method.slice(12),n=t.params?.requestId;return n===void 0?{_tag:e}:{_tag:e,requestId:n}}return{_tag:`Request`,id:t.id??``,tag:t.method,payload:t.params??null,headers:t.headers??[],...N(t,`id`)?{}:{isNotification:!0},...t.spanId?{traceId:t.traceId,spanId:t.spanId,sampled:t.sampled}:{}}}let t=e,n=Object.hasOwn(t,`error`);return n&&t.error&&t.error._tag===`Defect`?{_tag:`Defect`,defect:t.error.data}:Object.hasOwn(t,`chunk`)&&t.chunk===!0?{_tag:`Chunk`,requestId:t.id??``,values:t.result}:{_tag:`Exit`,requestId:t.id??``,exit:n&&t.error!=null?{_tag:`Failure`,cause:t.error._tag===`Cause`?t.error.data:[{_tag:`Fail`,error:t.error}]}:{_tag:`Success`,value:t.result}}}function rN(e,t){if(!(`requestId`in e))return iN(e);let n=t.get(e.requestId);return n?(t.delete(e.requestId),n.responses.set(e.requestId,e),n.size===n.responses.size?Array.from(n.responses.values(),iN):void 0):iN(e)}function Cle(e,t){if(Array.isArray(e)===!1)return rN(e,t);if(e.length===0)return;let n=[];for(let r=0;r<e.length;r++){let i=rN(e[r],t);i!==void 0&&n.push(i)}if(n.length===0)return;if(n.length===1)return n[0];let r=[];for(let e=0;e<n.length;e++){let t=n[e];Array.isArray(t)?r.push(...t):r.push(t)}return r}function iN(e){switch(e._tag){case`Request`:return{jsonrpc:`2.0`,method:e.tag,params:e.payload,...e.isNotification?{}:{id:e.id},...e.headers?.length>0?{headers:e.headers}:{},traceId:e.traceId,spanId:e.spanId,sampled:e.sampled};case`Ping`:case`Pong`:case`Interrupt`:case`Ack`:case`Eof`:return{jsonrpc:`2.0`,method:`@effect/rpc/${e._tag}`,params:`requestId`in e?{requestId:e.requestId}:void 0};case`Chunk`:return{jsonrpc:`2.0`,chunk:!0,id:e.requestId,result:e.values};case`Exit`:{if(e.exit._tag===`Success`)return{jsonrpc:`2.0`,id:e.requestId??void 0,result:e.exit.value};let t=e.exit.cause.find(e=>e._tag===`Fail`),n=t?._tag===`Fail`?t.error:void 0;return{jsonrpc:`2.0`,id:e.requestId??void 0,error:e.exit._tag===`Failure`?{_tag:`Cause`,code:n&&N(n,`code`)?Number(n.code):0,message:n&&N(n,`message`)?n.message:JSON.stringify(e.exit.cause),data:e.exit.cause}:void 0}}case`Defect`:return{jsonrpc:`2.0`,id:wle,error:{_tag:`Defect`,code:1,message:`A defect occurred`,data:e.defect}};case`ClientProtocolError`:return{}}}const wle=-32603,Tle=e=>_f(eN)(tN(e)),Ele=()=>e=>ap(()=>{let t=yw(1),n=[],r=(...e)=>Rp(t=>(n.push([e,t]),L));return V(e((...e)=>r(...e)),e=>({...e,run(e){return t.withPermits(1)(R(function*(){let t=r;for(let[t,r]of n)yield*Bp(ap(()=>e(...t)),r);return n=[],r=e,yield*Qp(sp,()=>(r=t,L))}))}}))}),Dle=e=>ap(()=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=(e,t)=>Rp(r=>{let i=n.get(e);return i||(i=[],n.set(e,i)),i.push([t,r]),L});return V(e((e,t)=>{let n=r.get(e);return n?n(t):i(e,t)},t),e=>({...e,run(e,i){return R(function*(){t.add(e),r.set(e,i);let a=n.get(e);if(a){n.delete(e);for(let[e,t]of a)yield*Bp(ap(()=>i(e)),t)}return yield*Qp(sp,()=>(t.delete(e),r.delete(e),L))})}}))});let Ole=0;const aN=/*#__PURE__*/ H(function*(e,t){let n=t.spanPrefix,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Ole++),o=yield*Lp(),s=va(o,Jd),c=/* @__PURE__ */ new Map,l=!1;yield*$d(s,fp(e=>(l=!0,u(Td(e.id)))));let u=H(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?KC(n.queue):WC(n.queue,e.cause):n.resume(e)}),d=e=>{let r=HM(e.successSchema),a=m(e);return(o,s)=>{let c=s?.headers?wg(s.headers):Cg,l=s?.context??la();if(!r){let r=t=>f(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):sm(zM(n,e._tag),{kind:`client`,attributes:BM(e._tag,t.spanAttributes)},r)}let u=p(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:$T(V(u,ZT))}},f=(e,n,r,i,o,s,u)=>fp(d=>{if(l)return em;let f=a(),p=n(e=>t.onFromClient({message:e,context:s,discard:u}),{_tag:`Request`,id:f,tag:e._tag,payload:i,...r?{traceId:r.traceId,spanId:r.spanId,sampled:r.sampled}:{},headers:Og(d.getRef(oN),o)});if(u)return p;let m;return nm(op(t=>{let n={_tag:`Effect`,rpc:e,context:s,resume(e){t(e),m&&!m.pollUnsafe()&&d.currentDispatcher.scheduleTask(()=>{m.interruptUnsafe(d.id)},0)}};c.set(f,n),m=p.pipe(r?lm(r,{captureStackTrace:!1}):M,mm(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),mp(bC(m),h(f,Array.from(e),s))))}),p=H(function*(e,r,o,s,u,d){if(l)return yield*em;let f=i?void 0:yield*om(zM(n,e._tag),{kind:`client`,attributes:BM(e._tag,t.spanAttributes)}),p=xC(),m=a(),g=_a(p.context,Jd),_=yield*RC(u);return yield*Qd(g,e=>(YC(_),c.has(m)?(c.delete(m),h(m,Od(e)?Array.from(ld(e.cause)):[],d)):L)),c.set(m,{_tag:`Queue`,rpc:e,queue:_,scope:g,context:d}),yield*r(e=>t.onFromClient({message:e,context:d,discard:!1}),{_tag:`Request`,id:m,tag:e._tag,payload:o,...f?{traceId:f.traceId,spanId:f.spanId,sampled:f.sampled}:{},headers:Og(p.getRef(oN),s)}).pipe(f?lm(f,{captureStackTrace:!1}):M,Xp(e=>WC(_,e)),tm,dm(g,{startImmediately:!0})),_}),m=e=>{let t=[];for(let n of e.middlewares.values()){let e=ga(o,`${n.key}/Client`);e&&t.push(e)}return t.length===0?(e,t)=>e(t):function n(r,i,a=t.length-1){return a===-1?r(i):t[a]({rpc:e,request:i,next(e){return n(r,e,a-1)}})}},h=(e,n,r)=>op(i=>{let a=xC();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(Xre(1e3),mm(a.context)).addObserver(()=>{i(L)})}),g=e=>{switch(e._tag){case`Chunk`:{let n=e.requestId,i=c.get(n);return!i||i._tag!==`Queue`?L:HC(i.queue,e.values).pipe(r?B(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):M,Sp(e=>WC(i.queue,e)))}case`Exit`:{let t=e.requestId,n=c.get(t);return n?(c.delete(t),n._tag===`Effect`?(n.resume(e.exit),L):e.exit._tag===`Success`?KC(n.queue):WC(n.queue,e.exit.cause)):L}case`Defect`:return u(wd(e.defect));case`ClientEnd`:return L}},_;if(t.flatten){let t=/* @__PURE__ */ new Map;_=function(n,r,i){let a=t.get(n);return a||(a=d(e.requests.get(n)),t.set(n,a)),a(r,i)}}else _={},e.requests.forEach(e=>{dr(_,e._tag,d(e))});return{client:_,write:g}});let kle=0;const Ale=/*#__PURE__*/ H(function*(e,t){let n=kle++,{codecFor:r,run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*sN,c=jle(r),l=_oe(r(zS())),u=/* @__PURE__ */ new Map,d=e=>u.has(e)?(u.delete(e),a(n,{_tag:`Interrupt`,requestId:e})):L,{client:f,write:p}=yield*aN(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),i=s?RM():void 0,o=xC(),l={rpc:r,context:i?fa(o.context,LM,i):o.context,schemas:c(r)};return u.set(t.id,l),l.schemas.encodePayload(t.payload).pipe(Bp(l.context),Ep,B(e=>a(n,{...t,id:t.id,payload:e,headers:Object.entries(t.headers)},i&&i.readUnsafe())))}case`Ack`:return u.get(t.requestId)?a(n,{_tag:`Ack`,requestId:t.requestId}):L;case`Interrupt`:return d(t.requestId);case`Eof`:return L}}});return yield*i(n,e=>{switch(e._tag){case`Chunk`:{let t=XM(e.requestId),n=u.get(t);if(!n||Fi(n.schemas.decodeChunk))return L;let r=n.schemas.decodeChunk.value;return im(i=>i(r(e.values).pipe(Bp(n.context),Ep,B(e=>p({_tag:`Chunk`,clientId:0,requestId:t,values:e})))).pipe(Xp(e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Sd(e)}).pipe(mp(cd(e)?L:kp(d(t))))),Jre(e=>!cd(e),()=>L)))}case`Exit`:{let t=XM(e.requestId),n=u.get(t);return n?(u.delete(t),n.schemas.decodeExit(e.exit).pipe(Bp(n.context),Ep,Fp({onSuccess:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Sd(e)})}))):L}case`Defect`:return p({_tag:`Defect`,clientId:0,defect:l(e.defect)});case`ClientProtocolError`:{let t=Cd(e.error);return ep(Array.from(u.keys()),e=>p({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return L}}).pipe(Sp(Cm),tm,fm),f}),jle=e=>{let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=UM(n.successSchema);return r={decodeChunk:Ui(i,t=>Nx(e(iS(t.success)))),encodePayload:Lx(e(n.payloadSchema)),decodeExit:Nx(e(JM(n)))},t.set(n,r),r}},oN=/*#__PURE__*/ Ea(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>Cg});var sN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcClient/Protocol`)){static make=Dle};const Mle=/*#__PURE__*/ H(function*(e,t){let n=t.disableTracing!==!0,r=t.disableSpanPropagation!==!0,i=t.disableClientAcks!==!0,a=t.spanPrefix,o=t.concurrency??`unbounded`,s=t.disableFatalDefects??!1,c=yield*Lp(),l=va(c,Jd),u=SC(tf(l,`parallel`)),d=o===`unbounded`?void 0:yield*Sw(o),f=/* @__PURE__ */ new Map,p=!1,m=CC(!1);yield*$d(l,fp(e=>{p=!0;for(let t of f.values())if(t.ended=!0,t.fibers.size===0)u(mm(c)(_(t)));else for(let n of t.fibers.values())n.interruptUnsafe(e.id);return f.size===0?L:m.await}));let h=e=>fp(t=>{let n=f.get(e);if(!n)return L;for(let e of n.fibers.values())e.interruptUnsafe(t.id);return f.delete(e),L}),g=(e,n,r)=>Cp(fp(i=>{if(p)return em;let a=f.get(e);if(!a)a={id:e,latches:void 0,fibers:/* @__PURE__ */ new Map,ended:!1,serverClient:new GM(e)},f.set(e,a);else if(a.ended&&(n._tag!==`Interrupt`&&n._tag!==`Ack`||!a.fibers.has(n.requestId)))return em;switch(n._tag){case`Request`:return v(i,a,n,r);case`Ack`:{let e=a.latches?.get(n.requestId);return e?yp(e.open):L}case`Interrupt`:{let r=a.fibers.get(n.requestId);return r?(r.interruptUnsafe(i.id,gle.annotation),L):t.onFromServer({_tag:`Exit`,clientId:e,requestId:n.requestId,exit:Td()})}case`Eof`:return a.ended=!0,a.fibers.size>0?L:_(a);default:return b(a,`Unknown request tag: ${n._tag}`)}}),t=>b(f.get(e),t)),_=e=>{f.delete(e.id);let n=t.onFromServer({_tag:`ClientEnd`,clientId:e.id});return p&&f.size===0?mp(n,m.open):n},v=(i,o,l,f)=>{if(o.fibers.has(l.id))return em;let p=e.requests.get(l.tag),m=ga(c,p?.key);if(!p||!m){let e=Cp(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:wd(`Unknown request tag: ${l.tag}`)}),e=>b(o,e));return!o.ended||o.fibers.size>0?e:Yp(e,_(o))}let h=HM(p.successSchema),g={rpc:p,client:o.serverClient,requestId:l.id,headers:l.headers,payload:l.payload},v=m.handler(l.payload,g),x=YM(v),S=x&&v.fork,ee=x&&v.uninterruptible,C=x?v.value:v,te,ne=h?y(o,l,C,e=>{te=e}):C,w=p.middlewares.size===0?ne:h?B(_p(pN(c,ne,g)),e=>te?cp(te):e):pN(c,ne,g),T=!1,re=Xd(),ie,ae=Qp(w,e=>{T=!0;let n;if(e._tag===`Success`)Md(e.value)?(ie=e.value,n=L):n=t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});else if(te)return rf(re,e)??L;else n=!s&&sd(e.cause)&&!cd(e.cause)?b(o,ad(e.cause)):t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});let r=rf(re,e);return e._tag===`Failure`&&Ju(xC(),e.cause),r?Yp(n,r):n});if(f?.onRequest&&(ae=f.onRequest(ae)),n){let e=ha(i.context,Vo);ae=cm(ae,zM(a,l.tag),{captureStackTrace:!1,kind:`server`,attributes:BM(l.tag,t.spanAttributes),parent:r&&l.spanId?Uo({traceId:l.traceId,spanId:l.spanId,sampled:l.sampled}):void 0,links:r&&e?[{span:e,attributes:{}}]:void 0})}!S&&d&&(ae=d.withPermit(ae));let oe=mm(fa(Fle(m,i.context),Jd,re));return u(oe(fp(e=>(o.fibers.set(l.id,e),ae)),ee?{uninterruptible:!0}:void 0)).addObserver(function e(n){if(ie){let n=u(oe(Qp(Ld(ie),e=>t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e}))));o.fibers.set(l.id,n),ie=void 0,n.addObserver(e)}else!T&&n._tag===`Failure`&&u(oe(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Td()}))),o.fibers.delete(l.id),o.latches?.delete(l.id),o.ended&&o.fibers.size===0&&u(oe(_(o)))}),L},y=(e,n,r,a)=>{let o=r=>Xp(t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r}),e=>(nd(e)||a(e),L)),s;return i&&(e.latches??=/* @__PURE__ */ new Map,s=e.latches.get(n.id),s||(s=CC(!1),e.latches.set(n.id,s))),Qf(r)?r.pipe(B(e=>tp({while:Mt,body:jt(B(XC(e),e=>{let t=o(e);return s?(s.closeUnsafe(),B(t,()=>s.await)):t})),step:Ft})),Uf(()=>L),Kp):oE(r,e=>{let t=o(e);return s?(s.closeUnsafe(),mp(t,s.await)):t})},b=(e,n)=>ap(()=>{let r=e.ended&&e.fibers.size===0,i=t.onFromServer({_tag:`Defect`,clientId:e.id,defect:n});return r?mp(i,_(e)):i});return M({write:g,disconnect:h})}),cN=e=>e===xle.codecFor,lN=/*#__PURE__*/ new WeakMap,Nle=(e,t)=>{let n=cN(e),r=n?lN.get(t):void 0;if(r===void 0){let i=UM(t.successSchema);r={decode:Nx(e(t.payloadSchema)),encodeChunk:Ix(e(iS(Ii(i)?i.value.success:Jx))),encodeExit:Ix(e(JM(t)))},n&&lN.set(t,r)}return r};let Ple;const uN=e=>({encodeDefectUnsafe:zx(e(zS())),encodeUnknownRequestExit:Ix(e(tC(qx,qx,zS())))}),dN=e=>cN(e)?Ple??=uN(e):uN(e),fN=/*#__PURE__*/ new WeakMap,Fle=(e,t)=>{let n=fN.get(e);n===void 0&&(n=/* @__PURE__ */ new WeakMap,fN.set(e,n));let r=n.get(t);return r===void 0&&(r=Ca(e.context,t),n.set(t,r)),r},pN=(e,t,n)=>{for(let r of n.rpc.middlewares)t=_a(e,r)(t,n);return t},Ile=/*#__PURE__*/ H(function*(e,t){let{codecFor:n,disconnects:r,end:i,run:a,send:o,supportsAck:s,supportsSpanPropagation:c,supportsTransferables:l}=yield*mN,{encodeDefectUnsafe:u,encodeUnknownRequestExit:d}=dN(n),f=yield*Lp(),p=yield*Yd(),m=yield*Mle(e,{...t,disableClientAcks:!s,disableSpanPropagation:!c,onFromServer(e){let t=_.get(e.clientId);if(!t)return L;switch(e._tag){case`Chunk`:{let n=t.schemas.get(e.requestId);return n?y(t,e.requestId,n,n.encodeChunk(e.values),`Chunk`):L}case`Exit`:{let n=t.schemas.get(e.requestId);return n?(t.schemas.delete(e.requestId),y(t,e.requestId,n,n.encodeExit(e.exit),`Exit`)):L}case`Defect`:return x(t,e.defect);case`ClientEnd`:return _.delete(e.clientId),i(e.clientId)}}}).pipe(Zd(p));yield*um(tp({while:Mt,body:jt(B($C(r),e=>(_.delete(e),m.disconnect(e)))),step:Ft}));let h=/* @__PURE__ */ new WeakMap,g=e=>{let t=h.get(e);if(!t){let r=ga(f,e.key);t={tag:e._tag,...Nle(n,e),context:r.context},h.set(e,t)}return t},_=/* @__PURE__ */ new Map,v=(e,t,n)=>t===`Chunk`?{_tag:`Chunk`,requestId:e,values:n}:{_tag:`Exit`,requestId:e,exit:n},y=(e,t,n,r,i)=>{let a=n.collector,s=!1,c=bd(r)&&Dd(r)?o(e.id,v(t,i,r.value),a&&a.clearUnsafe()):B(bp(Bp(a?Wp(r,LM,a):r,n.context),e=>fp(t=>{let r=Qu(`Failed to encode response for RPC "${n.tag}": ${Z_(e.issue)}`);return Ju(t,r),s=!0,cp(r)})),n=>o(e.id,v(t,i,n),a&&a.clearUnsafe()));return Sp(c,r=>(e.schemas.delete(t),mp(b(e,t,n.encodeExit,ad(r)),s?cp(r):m.write(e.id,{_tag:`Interrupt`,requestId:t,interruptors:[]}))))},b=(e,t,n,r)=>Sp(B(n(wd(r)),n=>o(e.id,v(t,`Exit`,n))),t=>x(e,ad(t))),x=(e,t)=>Sp(o(e.id,ZM(u(t))),e=>Em(Tm(e),{module:`RpcServer`,method:`sendDefect`})),S=(e,t,n,r,i)=>{e.schemas.set(t,l?{...n,collector:RM()}:n);let a=r;return a.id=t,a.payload=i,a.headers=wg(r.headers),m.write(e.id,a)};return yield*a((t,n)=>{let r=_.get(t);switch(r||(r={id:t,schemas:/* @__PURE__ */ new Map},_.set(t,r)),n._tag){case`Request`:{let t=Object.hasOwn(n,`tag`)?n.tag:``,i;switch(typeof n.id){case`number`:case`string`:i=XM(n.id);break;default:return x(r,`Invalid request id: ${n.id}`)}let a=e.requests.get(t);if(!a)return b(r,i,d,`Unknown request tag: ${t}`);let o=g(a),s=o.decode(n.payload);return bd(s)&&Dd(s)?S(r,i,o,n,s.value):Ip(Bp(s,o.context),{onFailure:e=>b(r,i,o.encodeExit,Z_(e.issue)),onSuccess:e=>S(r,i,o,n,e)})}case`Ping`:return Sp(o(r.id,yle),e=>x(r,ad(e)));case`Eof`:return m.write(t,n);case`Ack`:return m.write(t,n);case`Interrupt`:return m.write(t,{...n,requestId:XM(n.requestId),interruptors:[]});default:return x(r,`Unknown request tag: ${n._tag}`)}}).pipe(Op(e=>xm(`BUG: RpcServer protocol crashed`,e)),Qp(e=>nf(p,e)))});var mN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcServer/Protocol`)){static make=/*#__PURE__*/ Ele()};const hN=/*#__PURE__*/ H(function*(e={}){let t=yield*eN,{encodeDefectUnsafe:n}=dN(t.codecFor),r=t.includesFraming,i=!t.contentType.includes(`json`),a=yield*LC(),o,s=0,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=new TextEncoder,d=R(function*(){let d=xC(),f=_a(d.context,pM),p=_a(d.context,Jd),m=Object.entries(f.headers),h=yield*Ep(i?V(f.arrayBuffer,e=>new Uint8Array(e)):f.text),g=s++,_=yield*LC({capacity:r&&e.streamBufferSize!==`unbounded`?e.streamBufferSize??16:void 0}),v=t.makeUnsafe(),y=[],b=e=>typeof e==`string`?BC(_,u.encode(e)):BC(_,e),x={write:r?e=>{try{let t=v.encode(e);return t===void 0?L:b(t)}catch(e){return b(v.encode(ZM(n(e))))}}:e=>e._tag===`Request`&&e.isNotification===!0?L:BC(_,e),end:KC(_)};yield*Qd(p,()=>(c.delete(g),l.delete(g),VC(a,g),_.state._tag===`Done`?L:mp(JC(_),ep(y,e=>o(g,{_tag:`Interrupt`,requestId:e}),{discard:!0})))),c.set(g,x),l.add(g);try{let e=v.decode(h);for(let t=0;t<e.length;t++){let n=e[t];n._tag===`Request`&&(y.push(XM(n.id)),n.headers=m.concat(n.headers)),yield*o(g,n)}}catch(e){yield*x.write(ZM(n(e)))}if(yield*o(g,vle),!r){let e=yield*ZC(_),n=v.encode(e);return gA(n===void 0?``:n,{contentType:t.contentType})}let S=yield*Uf(XC(_),()=>F([]));return _.state._tag===`Done`?mA(Lle(S),{contentType:t.contentType}):xA(wse(S).pipe(Ese(ZT(_))),{contentType:t.contentType})});return{protocol:yield*mN.make(e=>(o=e,F({disconnects:a,send(e,t){let n=c.get(e);return n?n.write(t):L},end(e){let t=c.get(e);return t?t.end:L},clientIds:I(()=>l),initialMessage:ip,supportsAck:!1,supportsTransferables:!1,supportsSpanPropagation:!1,supportsNotifications:r,codecFor:t.codecFor}))),httpEffect:d}}),Lle=e=>{if(e.length===0)return/* @__PURE__ */ new Uint8Array;if(e.length===1)return e[0];let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n},Rle={add(...e){let t=new Map(this.requests);for(let n of e)t.set(n._tag,n);return gN({requests:t,annotations:this.annotations})},merge(...e){let t=new Map(this.requests),n=new Map(this.annotations.mapUnsafe);for(let r of e){for(let[e,n]of r.requests)t.set(e,n);for(let[e,t]of r.annotations.mapUnsafe)n.set(e,t)}return gN({requests:t,annotations:ra(n)})},omit(...e){let t=new Map(this.requests);for(let n of e)t.delete(n);return gN({requests:t,annotations:this.annotations})},middleware(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.middleware(e));return gN({requests:t,annotations:this.annotations})},toHandlers(e){let t=this;return R(function*(){let n=yield*Lp(),r=Qf(e)?yield*e:e,i=/* @__PURE__ */ new Map;return t.requests.forEach((e,t)=>{i.set(e.key,{tag:e._tag,handler:r[t],context:n})}),ra(i)})},prefix(e){let t=/* @__PURE__ */ new Map;for(let n of this.requests.values()){let r=n.prefix(e);t.set(r._tag,r)}return gN({requests:t,annotations:this.annotations})},toLayer(e){return Sf(this.toHandlers(e))},of:M,toLayerHandler(e,t){let n=this;return Sf(R(function*(){let r=yield*Lp(),i=Qf(t)?yield*t:t,a=/* @__PURE__ */ new Map,o=n.requests.get(e);return a.set(o.key,{handler:i,context:r}),ra(a)}))},accessHandler(e){return Rp(t=>{let n=this.requests.get(e),{handler:r,context:i}=ga(t,n.key);return F((e,t)=>{t.rpc=n;let a=r(e,t),o=YM(a)?a.value:a;return Qf(o)?zp(o,i):iE(o,i)})})},annotate(e,t){return gN({requests:this.requests,annotations:fa(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsMerge(da(e,t))},annotateMerge(e){return gN({requests:this.requests,annotations:Ca(this.annotations,e)})},annotateRpcsMerge(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.annotateMerge(Ca(e,r.annotations)));return gN({requests:t,annotations:this.annotations})}},gN=e=>Object.assign(function(){},Rle,{requests:e.requests,annotations:e.annotations}),_N=(...e)=>gN({requests:new Map(e.map(e=>[e._tag,e])),annotations:la()}),zle=e=>{switch(e){case`SHA-1`:return`sha1`;case`SHA-256`:return`sha256`;case`SHA-384`:return`sha384`;case`SHA-512`:return`sha512`}},Ble=/* @__PURE__ */ _f(ME,/* @__PURE__ */ bce({randomBytes:et.randomBytes,digest:(e,t)=>dp({try:()=>Uint8Array.from(et.createHash(zle(e)).update(t).digest()),catch:e=>wT({module:`Crypto`,method:`digest`,_tag:`Unknown`,description:`Could not compute digest`,cause:e})})})),vN=e=>t=>TT({module:`FileSystem`,method:e,description:t.message??String(t)}),yN=(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n))throw RangeError(`${t} exceeds the safe integer range: ${e}`);return n},bN=e=>Wi(zi(e),$m),xN=e=>BigInt.asUintN(64,e),SN=e=>Ui(zi(e),xN),CN=(e,t)=>dp({try:()=>yN(e,`position`),catch:vN(t)}),Vle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.access,/*#__PURE__*/ wD(`FileSystem`,`access`),/*#__PURE__*/ vN(`access`));return(t,n)=>{let r=vt.constants.F_OK;return n?.readable&&(r|=vt.constants.R_OK),n?.writable&&(r|=vt.constants.W_OK),e(t,r)}})(),Hle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.cp,/*#__PURE__*/ wD(`FileSystem`,`copy`),/*#__PURE__*/ vN(`copy`));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),Ule=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.copyFile,/*#__PURE__*/ wD(`FileSystem`,`copyFile`),/*#__PURE__*/ vN(`copyFile`));return(t,n)=>e(t,n)})(),Wle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.chmod,/*#__PURE__*/ wD(`FileSystem`,`chmod`),/*#__PURE__*/ vN(`chmod`));return(t,n)=>e(t,n)})(),Gle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.chown,/*#__PURE__*/ wD(`FileSystem`,`chown`),/*#__PURE__*/ vN(`chown`));return(t,n,r)=>e(t,n,r)})(),Kle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.glob,/*#__PURE__*/ wD(`FileSystem`,`glob`),/*#__PURE__*/ vN(`glob`));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),qle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.link,/*#__PURE__*/ wD(`FileSystem`,`link`),/*#__PURE__*/ vN(`link`));return(t,n)=>e(t,n)})(),Jle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.mkdir,/*#__PURE__*/ wD(`FileSystem`,`makeDirectory`),/*#__PURE__*/ vN(`makeDirectory`));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),wN=e=>{let t=Dm(vt.mkdtemp,wD(`FileSystem`,e),vN(e));return e=>ap(()=>{let n=e?.prefix??``,r=typeof e?.directory==`string`?rt.join(e.directory,`.`):dt.tmpdir();return t(n?rt.join(r,n):r+`/`)})},Yle=/*#__PURE__*/ wN(`makeTempDirectory`),TN=e=>{let t=Dm(vt.rm,wD(`FileSystem`,e),vN(e));return(e,n)=>t(e,{recursive:n?.recursive??!1,force:n?.force??!1})},Xle=/*#__PURE__*/ TN(`remove`),Zle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ wN(`makeTempDirectoryScoped`),t=/*#__PURE__*/ TN(`makeTempDirectoryScoped`);return n=>qp(e(n),e=>Ep(t(e,{recursive:!0})))})(),Qle=e=>{let{O_APPEND:t,O_CREAT:n,O_EXCL:r,O_RDONLY:i,O_RDWR:a,O_TRUNC:o,O_WRONLY:s}=vt.constants;switch(e){case`r`:return i;case`r+`:return a;case`w`:return o|n|s;case`wx`:return o|n|s|r;case`w+`:return o|n|a;case`wx+`:return o|n|a|r;case`a`:return t|n|s;case`ax`:return t|n|s|r;case`a+`:return t|n|a;case`ax+`:return t|n|a|r}},$le=(e,t)=>ap(()=>{let{O_NOFOLLOW:n}=vt.constants;return process.platform===`win32`||typeof n!=`number`||n===0?z(TT({module:`FileSystem`,method:e,description:`noFollow is not supported on this platform`})):F(Qle(t)|n)}),eue=/*#__PURE__*/ (e=>{let t=Dm(vt.open,wD(`FileSystem`,e),vN(e)),n=Dm(vt.close,wD(`FileSystem`,e),vN(e));return(r,i)=>It(qp(i?.noFollow===!0?B($le(e,i.flag??`r`),e=>t(r,e,i.mode)):t(r,i?.flag??`r`,i?.mode),e=>Ep(n(e))),V(e=>tue(e,i?.flag?.startsWith(`a`)??!1)))})(`open`),EN=e=>TT({module:`FileSystem`,method:e,description:`Cannot read before the start of the file`}),tue=/*#__PURE__*/ (()=>{let e=e=>Dm(vt.read,wD(`FileSystem`,e),vN(e)),t=/*#__PURE__*/ e(`read`),n=/*#__PURE__*/ e(`readAlloc`),r=/*#__PURE__*/ Dm(vt.fstat,/*#__PURE__*/ wD(`FileSystem`,`stat`),/*#__PURE__*/ vN(`stat`)),i=/*#__PURE__*/ Dm(vt.ftruncate,/*#__PURE__*/ wD(`FileSystem`,`truncate`),/*#__PURE__*/ vN(`truncate`)),a=/*#__PURE__*/ Dm(vt.fsync,/*#__PURE__*/ wD(`FileSystem`,`sync`),/*#__PURE__*/ vN(`sync`)),o=e=>Dm(vt.write,wD(`FileSystem`,e),vN(e)),s=/*#__PURE__*/ o(`write`),c=/*#__PURE__*/ o(`writeAll`);class l{[uE];fd;append;position=/*#__PURE__*/ BigInt(0);constructor(e,t){this[uE]=uE,this.fd=e,this.append=t}get stat(){return B(r(this.fd,{bigint:!0}),ON)}get sync(){return a(this.fd)}seek(e,t){return ap(()=>{let n=t===`start`?e:this.position+e;return n<BigInt(0)?z(TT({module:`FileSystem`,method:`seek`,description:`Cannot seek before the start of the file`})):(this.position=n,F(n))})}read(e,n){return ap(()=>{let r=n?.position;if(r!==void 0)return r<BigInt(0)?z(EN(`read`)):t(this.fd,{buffer:e,position:r});let i=this.position;return V(t(this.fd,{buffer:e,position:i}),e=>(this.position=i+BigInt(e),e))})}readAlloc(e,t){return ap(()=>{try{if(!Number.isInteger(e)||e<0)throw RangeError(`size must be a non-negative integer`);let r=t?.position;if(r!==void 0&&r<BigInt(0))return z(EN(`readAlloc`));let i=Buffer.allocUnsafeSlow(e),a=r??this.position;return V(n(this.fd,{buffer:i,position:a}),t=>{if(t===0)return Ni();if(r===void 0&&(this.position=a+BigInt(t)),t===e)return Pi(i);let n=Buffer.allocUnsafeSlow(t);return i.copy(n,0,0,t),Pi(n)})}catch(e){return z(vN(`readAlloc`)(e))}})}truncate(e){return V(i(this.fd,e||void 0),()=>{if(!this.append){let t=BigInt(e??0);this.position>t&&(this.position=t)}})}write(e){return ap(()=>{let t=this.position;return B(this.append?F(void 0):CN(t,`write`),n=>V(s(this.fd,e,void 0,void 0,n),e=>(this.append||(this.position=t+BigInt(e)),e)))})}writeAllChunk(e){return ap(()=>{let t=this.position;return B(this.append?F(void 0):CN(t,`writeAll`),n=>B(c(this.fd,e,void 0,void 0,n),n=>n===0?z(wT({module:`FileSystem`,method:`writeAll`,_tag:`WriteZero`,pathOrDescriptor:this.fd,description:`write returned 0 bytes written`})):(this.append||(this.position=t+BigInt(n)),n<e.length?this.writeAllChunk(e.subarray(n)):L)))})}writeAll(e){return e.length===0?L:this.writeAllChunk(e)}}return(e,t)=>new l(e,t)})(),DN=e=>{let t=wN(e);return H(function*(e){let n=yield*t(e),r=et.randomBytes(6).toString(`hex`),i=rt.join(n,e?.suffix?`${r}${e.suffix}`:r);return yield*AN(i,/* @__PURE__ */ new Uint8Array),i})},nue=/*#__PURE__*/ DN(`makeTempFile`),rue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ DN(`makeTempFileScoped`),t=/*#__PURE__*/ TN(`makeTempFileScoped`);return n=>qp(e(n),e=>Ep(t(rt.dirname(e),{recursive:!0})))})(),iue=(e,t)=>rp({try:()=>vt.promises.readdir(e,t),catch:t=>wD(`FileSystem`,`readDirectory`)(t,[e])}),aue=e=>op((t,n)=>{try{vt.readFile(e,{signal:n},(n,r)=>{t(n?z(wD(`FileSystem`,`readFile`)(n,[e])):F(r))})}catch(e){t(z(vN(`readFile`)(e)))}}),oue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.readlink,/*#__PURE__*/ wD(`FileSystem`,`readLink`),/*#__PURE__*/ vN(`readLink`));return t=>e(t)})(),sue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.realpath,/*#__PURE__*/ wD(`FileSystem`,`realPath`),/*#__PURE__*/ vN(`realPath`));return t=>e(t)})(),cue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.rename,/*#__PURE__*/ wD(`FileSystem`,`rename`),/*#__PURE__*/ vN(`rename`));return(t,n)=>e(t,n)})(),ON=e=>dp({try:()=>({type:e.isFile()?`File`:e.isDirectory()?`Directory`:e.isSymbolicLink()?`SymbolicLink`:e.isBlockDevice()?`BlockDevice`:e.isCharacterDevice()?`CharacterDevice`:e.isFIFO()?`FIFO`:e.isSocket()?`Socket`:`Unknown`,mtime:zi(e.mtime),atime:zi(e.atime),birthtime:zi(e.birthtime),dev:xN(e.dev),rdev:SN(e.rdev),ino:SN(e.ino),mode:yN(e.mode,`mode`),nlink:SN(e.nlink),uid:bN(e.uid),gid:bN(e.gid),size:_h(e.size),blksize:e.blksize===void 0?Ni():Pi(_h(e.blksize)),blocks:zi(e.blocks)}),catch:vN(`stat`)}),kN=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.stat,/*#__PURE__*/ wD(`FileSystem`,`stat`),/*#__PURE__*/ vN(`stat`));return t=>B(e(t,{bigint:!0}),ON)})(),lue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.symlink,/*#__PURE__*/ wD(`FileSystem`,`symlink`),/*#__PURE__*/ vN(`symlink`));return(t,n)=>e(t,n)})(),uue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.truncate,/*#__PURE__*/ wD(`FileSystem`,`truncate`),/*#__PURE__*/ vN(`truncate`));return(t,n)=>e(t,n)})(),due=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ Dm(vt.utimes,/*#__PURE__*/ wD(`FileSystem`,`utime`),/*#__PURE__*/ vN(`utime`));return(t,n,r)=>e(t,n,r)})(),fue=(e,t,n)=>Sse(r=>qp(I(()=>{let i=t.type===`Directory`?e:rt.dirname(e),a=vt.watch(e,{recursive:n?.recursive??!1},(e,t)=>{if(t)switch(e){case`rename`:pm(Ip(kN(rt.resolve(i,t)),{onSuccess:e=>BC(r,{_tag:`Create`,path:t}),onFailure:e=>BC(r,{_tag:`Remove`,path:t})}));return;case`change`:VC(r,{_tag:`Update`,path:t});return}});return a.on(`error`,t=>{GC(r,Zu(wT({module:`FileSystem`,_tag:`Unknown`,method:`watch`,pathOrDescriptor:e,cause:t})))}),a.on(`close`,()=>{qC(r)}),a}),e=>I(()=>e.close())).pipe(hp(()=>I(()=>n?.onReady?.())))),pue=(e,t,n)=>$f([kN(t),Hp(dE)]).pipe(V(([r,i])=>qee(i,()=>e).pipe(Wi(e=>e.register(t,r,n)),Ri(()=>fue(t,r,n)))),$T),AN=(e,t,n)=>op((r,i)=>{try{vt.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},t=>{r(t?z(wD(`FileSystem`,`writeFile`)(t,[e])):L)})}catch(e){r(z(vN(`writeFile`)(e)))}}),mue=/*#__PURE__*/ V(/*#__PURE__*/ Hp(dE),e=>Vse({access:Vle,chmod:Wle,chown:Gle,copy:Hle,copyFile:Ule,glob:Kle,link:qle,makeDirectory:Jle,makeTempDirectory:Yle,makeTempDirectoryScoped:Zle,makeTempFile:nue,makeTempFileScoped:rue,open:eue,readDirectory:iue,readFile:aue,readLink:oue,realPath:sue,remove:Xle,rename:cue,stat:kN,symlink:lue,truncate:uue,utimes:due,watch(t,n){return pue(e,t,n)},writeFile:AN})),jN=/* @__PURE__ */ bf(lE)(mue),MN=/*#__PURE__*/ new TextDecoder;var hue=class extends or{[GO];source;onError;remoteAddressOverride;constructor(e,t,n){super(),this[GO]=GO,this.source=e,this.onError=t,this.remoteAddressOverride=n}get headers(){return wg(this.source.headers)}get remoteAddress(){return this.remoteAddressOverride??zi(this.source.socket?.remoteAddress)}textEffect;get text(){return this.textEffect||=V(this.arrayBuffer,e=>MN.decode(e)),this.textEffect}get textUnsafe(){return _m(this.text)}get json(){return B(this.text,e=>dp({try:()=>e===``?null:JSON.parse(e),catch:this.onError}))}get jsonUnsafe(){return _m(this.json)}get urlParamsBody(){return B(this.text,e=>dp({try:()=>zg(new URLSearchParams(e)),catch:this.onError}))}get stream(){return OD({evaluate:()=>this.source,onError:this.onError})}arrayBufferEffect;get arrayBuffer(){return this.arrayBufferEffect||(this.arrayBufferEffect=fp(e=>MD(()=>this.source,{onError:this.onError,maxBytes:e.getRef(qO)})).pipe($p,_m),this.textEffect=V(this.arrayBufferEffect,e=>MN.decode(e))),this.arrayBufferEffect}};const NN=/*#__PURE__*/ Ea(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch});var PN=class extends (/*#__PURE__*/ P()(`effect/http/FetchHttpClient/RequestInit`)){};const FN=/*#__PURE__*/ wk(/*#__PURE__*/ F(/* @__PURE__ */ _k((e,t,n,r)=>{let i=r.getRef(NN),a=ha(r.context,PN)??{},o=a.headers?Og(wg(a.headers),e.headers):e.headers;o[`content-length`]&&(o=kg(o,`content-length`));let s=r=>V(rp({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:typeof ReadableStream<`u`&&r instanceof ReadableStream?`half`:void 0,signal:n}),catch:t=>new uO({reason:new mO({request:e,cause:t})})}),t=>XO(e,t));switch(e.body._tag){case`Raw`:case`Uint8Array`:return s(e.body.body);case`FormData`:return s(e.body.formData);case`Stream`:return B(Bse(e.body.stream),s)}return s(void 0)}))),gue=/*#__PURE__*/ new Set(typeof wt.zstdCompress==`function`?[`gzip`,`deflate`,`br`,`zstd`]:[`gzip`,`deflate`,`br`]),IN=(e,t)=>{let n={};return e!==void 0&&(n[wt.constants.BROTLI_PARAM_QUALITY]=e),t!==void 0&&(n[wt.constants.BROTLI_PARAM_SIZE_HINT]=t),{params:n}},LN=e=>e===void 0||e===3?void 0:{params:{[wt.constants.ZSTD_c_compressionLevel]:e}},_ue=(e,t,n)=>op(r=>{let i=(e,t)=>r(e===null?F(t):up(e));switch(t){case`gzip`:wt.gzip(e,{level:n?.level},i);break;case`deflate`:wt.deflate(e,{level:n?.level},i);break;case`br`:wt.brotliCompress(e,IN(n?.level,e.byteLength),i);break;case`zstd`:{let t=LN(n?.level);t===void 0?wt.zstdCompress(e,i):wt.zstdCompress(e,t,i);break}}}),vue=e=>({algorithms:e.algorithms,compressResponse(t,n,r){let i=t.body;return i._tag===`Uint8Array`?V(_ue(i.body,n,r),e=>SA(DA(t,$D(e,t.headers[`content-type`]??i.contentType)),`content-length`,e.byteLength.toString())):e.compressResponse(t,n,r)}}),RN=(e,t)=>{switch(e){case`gzip`:return wt.createGzip({level:t?.level,flush:wt.constants.Z_SYNC_FLUSH});case`deflate`:return wt.createDeflate({level:t?.level,flush:wt.constants.Z_SYNC_FLUSH});case`br`:return wt.createBrotliCompress({...IN(t?.level),flush:wt.constants.BROTLI_OPERATION_FLUSH});case`zstd`:return wt.createZstdCompress({...LN(t?.level),flush:wt.constants.ZSTD_e_flush})}},zN=(e,t)=>{let n;return new mt({read(){if(n===void 0){try{n=e()}catch(e){this.destroy(e instanceof Error?e:Error(String(e)));return}n.on(`data`,e=>{this.push(e)||n.pause()}),n.once(`end`,()=>this.push(null)),n.once(`error`,e=>this.destroy(e)),n.once(`close`,()=>{n.readableEnded||this.destroy(/* @__PURE__ */ Error(`Response stream closed prematurely`))})}n.resume()},destroy(e,r){n?.destroy(e??void 0),t?.(),r(e)}})},BN=(e,t)=>CA(DA(e,t),`content-length`),yue=/*#__PURE__*/ UA({platform:`node`,compression:/* @__PURE__ */ vue({algorithms:gue,compressResponse(e,t,n){let r=e.body;switch(r._tag){case`Stream`:return F(BN(e,cO(jD(r.stream,{evaluate:()=>RN(t,n)}),e.headers[`content-type`]??r.contentType)));case`Raw`:{let i=r.body instanceof mt?r.body:void 0,a=zN(()=>{let e=RN(t,n);return i??=mt.fromWeb(new Response(r.body).body),gee(i,e,e=>{e&&a.destroy(e)})},()=>i?.destroy());return F(BN(e,ZD(a,{contentType:e.headers[`content-type`]??r.contentType})))}default:return F(e)}}}),fileResponse(e,t,n,r,i,a,o){let s=zN(()=>o===BigInt(0)?mt.from([]):vt.createReadStream(e,{start:i,end:a===void 0?void 0:a-1}));return bA(s,{headers:{...r,"content-type":r[`content-type`]??Ri(VA(e),()=>`application/octet-stream`),"content-length":o.toString()},status:t,statusText:n})},fileWebResponse(e,t,n,r,i){return bA(zN(()=>mt.fromWeb(e.stream())),{headers:Og(r,Tg({"content-type":r[`content-type`]??(e.type===``?Ri(VA(e.name),()=>`application/octet-stream`):e.type),"content-length":e.size.toString()})),status:t,statusText:n})}}),bue=/*#__PURE__*/ It(/*#__PURE__*/ bf(HA)(yue),/*#__PURE__*/ Af(jN),/*#__PURE__*/ Af(oA));var xue=class extends hee{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,n;this._parser=Wj({...e,onField:(e,n)=>{if(t!==void 0)return;let r={_tag:`Field`,info:e,value:n};this.push(r),this.emit(`field`,r)},onFile:e=>{if(t!==void 0)return e=>{};let r=new Cue(e,this);return n=r,this.push(r),this.emit(`file`,r),e=>{t===void 0&&(this._canWrite=r.push(e),e===null&&!this._canWrite&&(n=void 0,this._resume()))}},onError:e=>{this.emit(`error`,e),n?.emit(`error`,e),t=e},onDone:()=>{this.push(null)}})}_resume(){if(this._canWrite=!0,this._writeCallback!==void 0){let e=this._writeCallback;this._writeCallback=void 0,e()}}_read(e){}_write(e,t,n){this._parser.write(e instanceof Uint8Array?e:Buffer.from(e,t)),this._canWrite?n():this._writeCallback=n}_final(e){this._parser.end(),e()}};const Sue=e=>new xue(e);var Cue=class extends mt{_tag=`File`;filename;info;_parent;constructor(e,t){super(),this.info=e,this._parent=t,this.filename=e.filename}_read(e){this._parent._canWrite===!1&&this._parent._resume()}};const VN=(e,t)=>eM(t).pipe(V(t=>OD({evaluate(){let n=Sue(t);return e.pipe(n),n},onError:e=>Oue(e)})),$T,eE(Tue)),wue=(e,t)=>aM(VN(e,t),(e,t)=>rp({try:n=>St.pipeline(t.file,vt.createWriteStream(e),{signal:n}),catch:e=>Qj.fromReason(`InternalError`,e)})),Tue=e=>e._tag===`Field`?new Eue(e.info,e.value):new Due(e);var HN=class extends or{[qj];constructor(){super(),this[qj]=qj}},Eue=class extends HN{_tag=`Field`;key;contentType;value;constructor(e,t){super(),this.key=e.name,this.contentType=e.contentType,this.value=Kj(e,t)}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`Field`,key:this.key,value:this.value,contentType:this.contentType}}},Due=class extends HN{_tag=`File`;key;name;contentType;content;contentEffect;file;constructor(e){super(),this.file=e,this.key=e.info.name,this.name=e.filename??e.info.name,this.contentType=e.info.contentType,this.content=OD({evaluate:()=>e,onError:e=>Qj.fromReason(`InternalError`,e)}),this.contentEffect=ND(()=>e,{onError:e=>Qj.fromReason(`InternalError`,e)})}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`File`,key:this.key,name:this.name,contentType:this.contentType}}};function Oue(e){switch(e._tag){case`ReachedLimit`:switch(e.limit){case`MaxParts`:return Qj.fromReason(`TooManyParts`,e);case`MaxFieldSize`:return Qj.fromReason(`FieldTooLarge`,e);case`MaxPartSize`:return Qj.fromReason(`FileTooLarge`,e);case`MaxTotalSize`:return Qj.fromReason(`BodyTooLarge`,e)}default:return Qj.fromReason(`Parse`,e)}}const UN=e=>({fromFileUrl:t=>dp({try:()=>ct.fileURLToPath(t,{windows:e}),catch:e=>new xT({module:`Path`,method:`fromFileUrl`,cause:e})}),toFileUrl:t=>dp({try:()=>ct.pathToFileURL(t,{windows:e}),catch:e=>new xT({module:`Path`,method:`toFileUrl`,cause:e})})});({...rt.posix,.../*#__PURE__*/ UN(!1)}),{...rt.win32,.../*#__PURE__*/ UN(!0)};const kue=/* @__PURE__ */ _f(pE)(/*#__PURE__*/ Hse({...rt,.../*#__PURE__*/ UN(void 0)})),Aue=/* @__PURE__ */ _f(Uce,/*#__PURE__*/ Wce({args:/*#__PURE__*/ I(()=>process.argv.slice(2)),stdinIsTerminal:/*#__PURE__*/ I(()=>process.stdin.isTTY===!0),stdoutIsTerminal:/*#__PURE__*/ I(()=>process.stdout.isTTY===!0),stderrIsTerminal:/*#__PURE__*/ I(()=>process.stderr.isTTY===!0),stdout:e=>TD({evaluate:()=>process.stdout,onError:e=>wT({module:`Stdio`,method:`stdout`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stderr:e=>TD({evaluate:()=>process.stderr,onError:e=>wT({module:`Stdio`,method:`stderr`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stdin:/*#__PURE__*/ OD({evaluate:()=>process.stdin,onError:e=>wT({module:`Stdio`,method:`stdin`,_tag:`Unknown`,cause:e}),closeOnDone:!1})})),jue=/*#__PURE__*/ bf(eD,/*#__PURE__*/ (/* @__PURE__ */ H(function*(e=WN){let t=process.stdin,n=process.stdout,r=yield*LC(),i=t.readableEnded,a=!1,o=()=>{i=!0,a||qC(r)};t.once(`end`,o),yield*Jp(()=>I(()=>t.off(`end`,o)));let s=yield*yse({acquire:qp(I(()=>{let e=Tt.createInterface({input:t,escapeCodeTimeout:50}),n=e=>VC(r,e),i=()=>{a=!1,qC(r)};return a=!0,Tt.emitKeypressEvents(t,e),e.on(`line`,n),e.once(`close`,i),t.isTTY&&t.setRawMode(!0),{rl:e,onClose:i,onLine:n}}),({rl:e,onClose:n,onLine:o})=>I(()=>{a=!1,e.off(`line`,o),e.off(`close`,n),t.isTTY&&t.setRawMode(!1),e.close(),i&&qC(r)})),idleTimeToLive:`10 millis`}),c=I(()=>n.columns??0),l=I(()=>n.rows??0),u=R(function*(){let n=yield*LC(),r=(t,r)=>{let i={input:Bi(t),key:{name:r.name??``,ctrl:!!r.ctrl,meta:!!r.meta,shift:!!r.shift}};VC(n,i),e(i)&&qC(n)},a=setInterval(()=>{},2147483647),o=()=>{clearInterval(a),qC(n)};return yield*Jp(()=>I(()=>{clearInterval(a),t.off(`keypress`,r),t.off(`end`,o)})),t.on(`keypress`,r),i?o():(yield*UT(s),t.once(`end`,o)),n}),d=ap(()=>ew(r).pipe(B(Li({onNone:()=>Kp(mp(UT(s),$C(r))),onSome:F})),Tp(()=>new $E({}))));return tD({columns:c,rows:l,readInput:u,readLine:d,display:e=>rm(op(t=>{n.write(e,e=>Qt(e)?t(L):t(z(TT({module:`Terminal`,method:`display`,description:`Failed to write prompt to stdout`,cause:e}))))}))})}))(WN));function WN(e){let t=e.key;return t.name===`escape`||t.ctrl&&(t.name===`c`||t.name===`d`)}const Mue=/*#__PURE__*/ jf(UD,/*#__PURE__*/ Df(jN,Ble,kue,Aue,jue)),Nue=(e,t)=>{let n=nle(e,Lue,t.middleware);return fp(e=>{let r=e.context;return F(function(i,a){let o=fa(r,pM,new Pue(i,a)),s=SC(mm(o)(n),t.scope);s.pollUnsafe()===void 0&&a.on(`close`,()=>{a.writableEnded||s.interruptUnsafe(e.id,aj.annotation)})})})};var Pue=class e extends hue{[fM];response;upgradeEffect;upgraded=!1;url;headersOverride;constructor(e,t,n,r=e.url,i,a){super(e,e=>new ej({reason:new tj({request:this,cause:e})}),a),this[fM]=fM,this.response=t,this.upgradeEffect=n,this.url=r,this.headersOverride=i}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=lg(this.headers.cookie??``)}get resolvedResponse(){return typeof this.response==`function`?this.response():this.response}modify(t){return new e(this.source,this.response,this.upgradeEffect,t.url??this.url,t.headers??this.headersOverride,`remoteAddress`in t?t.remoteAddress:this.remoteAddressOverride)}get originalUrl(){return this.source.url}cachedMethod;get method(){return this.cachedMethod??=this.source.method.toUpperCase()}get headers(){return this.headersOverride??=this.source.headers,this.headersOverride}multipartEffect;get multipart(){return this.multipartEffect||=_m($p(wue(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return VN(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??z(new ej({reason:new tj({request:this,description:`not an upgradeable ServerRequest`})}))}toString(){return`ServerRequest(${this.method} ${Xg(this.url)})`}toJSON(){return JO(this,{_id:`HttpServerRequest`,method:this.method,url:Xg(this.originalUrl)})}};const Fue=/*#__PURE__*/ Df(bue,sA,Mue),Iue=/*#__PURE__*/ fA({status:101}),Lue=(e,t)=>{if(e.upgraded)return F(Iue);let n=e.resolvedResponse;if(n.writableEnded)return L;let r=t.headers;if(!Yh(t.cookies)){r={...r};let e=cg(t.cookies);r[`set-cookie`]!==void 0&&e.push(r[`set-cookie`]),r[`set-cookie`]=e}if(e.method===`HEAD`)return n.writeHead(t.status,t.statusText,r),mp(Rue(t.body),op(e=>{let t=!1,r=()=>{t||(t=!0,n.off(`close`,r),e(L))};n.once(`close`,r),n.end(r)}));let i=t.body;switch(i._tag){case`Empty`:return n.writeHead(t.status,t.statusText,r),n.end(),L;case`Raw`:return n.writeHead(t.status,t.statusText,r),typeof i.body==`object`&&i.body!==null&&`pipe`in i.body&&typeof i.body.pipe==`function`?rp({try:e=>Ct(i.body,n,{signal:e,end:!0}),catch:n=>new ej({reason:new ij({request:e,response:t,description:`Error writing raw response`,cause:n})})}).pipe(tm,Op(GN(n,t))):op(e=>{n.end(i.body,()=>e(L))});case`Uint8Array`:return n.writeHead(t.status,t.statusText,r),i.contentLength<1048576?(n.end(i.text??i.body),L):op(e=>{n.end(i.text??i.body,()=>e(L))});case`FormData`:return ap(()=>{let a=new globalThis.Response(i.formData);return n.writeHead(t.status,t.statusText,{...r,...Object.fromEntries(a.headers)}),op((r,i)=>{mt.fromWeb(a.body,{signal:i}).pipe(n).on(`error`,n=>{r(z(new ej({reason:new ij({request:e,response:t,description:`Error writing FormData response`,cause:n})})))}).once(`finish`,()=>{r(L)})}).pipe(tm,Op(GN(n,t)))});case`Stream`:{n.writeHead(t.status,t.statusText,r);let e=CC();return n.on(`drain`,()=>e.openUnsafe()),i.stream.pipe(Ase,oE(t=>{let r=t.length>1?Buffer.concat(t):t[0];return n.write(r)?L:(e.closeUnsafe(),e.await)}),tm,Fp({onSuccess:()=>I(()=>n.end()),onFailure:GN(n,t)}))}}},Rue=e=>{let t=e._tag===`Raw`?e.body:void 0;return t instanceof mt?I(()=>t.destroy()):L},GN=(e,t)=>n=>B(cj(n),([r,i])=>{let a=e.headersSent;return a||e.writeHead(r.status,r.statusText),e.writableEnded||e.end(),cp(a?id(n,Qu(t)):i)}),zue={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},Bue=e=>zue[e],KN=new TextEncoder,qN=new TextDecoder,JN=new TextDecoder(`utf-8`,{fatal:!0}),YN=2**32;function XN(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function ZN(e,t,n){if(t<0||t>=YN)throw RangeError(`value must be >= 0 and <= ${YN-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function QN(e){let t=Math.floor(e/YN),n=e%YN,r=/* @__PURE__ */ new Uint8Array(8);return ZN(r,t,0),ZN(r,n,4),r}function $N(e){let t=/* @__PURE__ */ new Uint8Array(4);return ZN(t,e),t}const Vue=/[^\x00-\x7f]/;function eP(e){if(typeof e==`string`&&e.length>=128){if(Vue.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return KN.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Hue(e,t=!1){if(Uint8Array.prototype.toBase64)return e.toBase64({alphabet:t?`base64url`:`base64`,omitPadding:t});let n=32768,r=[];for(let t=0;t<e.length;t+=n)r.push(String.fromCharCode.apply(null,e.subarray(t,t+n)));let i=btoa(r.join(``));return t?i.replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`):i}function Uue(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}async function tP(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var nP=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},rP=class extends nP{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},iP=class extends nP{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},aP=class extends nP{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},oP=class extends nP{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},sP=class extends nP{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},cP=class extends nP{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},lP=class extends nP{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},uP=class extends nP{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},dP=class extends nP{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},fP=class extends nP{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},pP=class extends nP{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},mP=class extends nP{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},hP=class extends nP{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Wue=class extends nP{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function gP(e){try{return Uue(typeof e==`string`?e:qN.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function _P(e){return Hue(typeof e==`string`?KN.encode(e):e,!0)}function vP(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function yP(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function bP(e){return yP(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(yP)}function xP(...e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function SP(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function CP(e,t,n){try{return gP(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function wP(e,t,n){try{return eP(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function TP(e,t,n){let r;try{r=JSON.parse(JN.decode(gP(e)))}catch{throw new t(n)}if(!yP(r))throw new t(n);return r}const EP={__proto__:null,b64:!0},DP={__proto__:null};function OP(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function kP(e,t){let{crit:n}=t??{};if(Array.isArray(n)&&new Set(n).size!==n.length)throw new e(`"crit" (Critical) Header Parameter MUST NOT contain duplicate values`)}function AP(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new oP(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function jP(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new lP(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function MP(e,t){let n,r;try{n=JSON.stringify(t),r=JSON.parse(n)}catch(t){throw new e(`JOSE Header is not valid JSON`,{cause:t})}if(!yP(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}const Gue=e=>e[Symbol.toStringTag],Kue=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function NP(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(yP(t)){if(o=qP(t),typeof o.kty!=`string`)throw VP(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(Kue(e,o,n),o.kty===`oct`)return gP(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!RP(t))throw VP(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Gue(t)} instances must be of type "${e}" for the ${r} algorithm`);if(IP(t))return t;if(s=t,s.type===`secret`)return s.export()}PP||=/* @__PURE__ */ new WeakMap;let c=t,l=PP.get(c);if(l?.[r])return l[r];if(l||PP.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=que[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await YP(e,o)}let PP;const que={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function FP(e){if(!IP(e))throw Error(`CryptoKey instance expected`)}const IP=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},LP=e=>e?.[Symbol.toStringTag]===`KeyObject`,RP=e=>IP(e)||LP(e);function zP(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const BP=(e,...t)=>zP(`Key must be `,e,...t);function VP(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(zP(`Key for the ${e} algorithm must be `,t,...r))}const HP=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function UP(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function WP(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function GP(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw HP(t.name);if(t.hash&&r.hash?.name!==t.hash)throw HP(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw HP(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw HP(t.length,`algorithm.length`);UP(e,n)}function KP(e){return{__proto__:null,...e}}function qP(e){let t=KP(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}function JP(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function YP(e,t,n){if(!e.kty.includes(t.kty))throw new oP(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function XP(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),GP(e,t,n),e}const ZP=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function QP(e,t){let n=e.byteLength<<3;if(n!==t)throw new cP(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}const Jue=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function $P(e,t){if(t.length<<3!==e.ivBits)throw new cP(`Invalid Initialization Vector length`)}async function eF(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(BP(t,`Uint8Array`));let r=e.cekBits>>1;return[await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),r]}async function tF(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function Yue(e,t,n,r,i){let[a,o,s]=await eF(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await tF(o,XN(i,r,c,QN(i.length*8)),s),iv:r}}async function Xue(e,t){let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`,`verify`]),i=await crypto.subtle.sign(n,r,e);return crypto.subtle.verify(n,r,i,t)}async function Zue(e,t,n,r,i,a){let[o,s,c]=await eF(e,t,`decrypt`),l=await tF(s,XN(a,r,n,QN(a.length*8)),c);try{if(await Xue(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new sP}async function nF(e,t,n,r,i){if(!IP(n)&&!(n instanceof Uint8Array))throw TypeError(BP(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?$P(e,r):r=Jue(e),n instanceof Uint8Array&&QP(n,e.cekBits),e.cbc)return Yue(e,t,n,r,i);let a=await XP(n,e.subtle,`encrypt`),o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t));return{ciphertext:o.subarray(0,-16),tag:o.subarray(-16),iv:r}}async function rF(e,t,n,r,i,a){if(!IP(t)&&!(t instanceof Uint8Array))throw TypeError(BP(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new cP(`JWE Initialization Vector missing`);if(!i)throw new cP(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new cP(`Invalid Authentication Tag length`);if($P(e,r),t instanceof Uint8Array&&QP(t,e.cekBits),e.cbc)return Zue(e,t,n,r,i,a);let o=await XP(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,XN(n,i)))}catch{throw new sP}}function iF(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const Que=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],$ue=[[],[`deriveBits`]],aF=[[],[]];function oF(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:Que,ops:[`wrapKey`,`unwrapKey`]}}function sF(e){return{kty:[`EC`,`OKP`],mode:e,subtle:{name:`ECDH`},resolve:({kty:e,crv:t,asymmetricKeyType:n})=>{if(t===`X25519`||n===`x25519`)return{name:`X25519`};if(e===`OKP`)throw new oP(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:$ue,ops:[void 0,`deriveBits`]}}function cF(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:aF,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function lF(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:aF,ops:[`deriveBits`,`deriveBits`]}}const uF=iF({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:aF,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":oF(1),"RSA-OAEP-256":oF(256),"RSA-OAEP-384":oF(384),"RSA-OAEP-512":oF(512),"ECDH-ES":sF(`direct-key-agreement`),"ECDH-ES+A128KW":sF(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":sF(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":sF(`key-agreement-with-key-wrapping`),A128KW:cF(128),A192KW:cF(192),A256KW:cF(256),A128GCMKW:cF(128,!0),A192GCMKW:cF(192,!0),A256GCMKW:cF(256,!0),"PBES2-HS256+A128KW":lF(),"PBES2-HS384+A192KW":lF(),"PBES2-HS512+A256KW":lF()}),ede=[`encrypt`,`decrypt`];function dF(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:aF,ops:ede,cekBits:e,ivBits:t?128:96,cbc:t}}const tde=iF({A128GCM:dF(128),A192GCM:dF(192),A256GCM:dF(256),"A128CBC-HS256":dF(256,!0),"A192CBC-HS384":dF(384,!0),"A256CBC-HS512":dF(512,!0)});function fF(e,t){throw new oP(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function pF(e){return(typeof e==`string`?uF[e]:void 0)??fF(`alg`,`Algorithm`)}function mF(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function hF(e){return(typeof e==`string`?tde[e]:void 0)??fF(`enc`,`Encryption Algorithm`)}function gF(e,t){if(e.algorithm.name!==`ECDH`&&e.algorithm.name!==`X25519`)throw TypeError(`CryptoKey does not support this operation, its algorithm.name must be ECDH or X25519`);UP(e,t)}async function nde(e,t,n){let r=await XP(t,pF(e).subtle,`wrapKey`,!0),i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function rde(e,t,n){let r=await XP(t,pF(e).subtle,`unwrapKey`,!0),i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function _F(e,t,n){GP(t,pF(e).subtle,n),WP(e,t)}async function vF(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new cP(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new cP(`PBES2 Count Input must be a positive integer`);let i=XN(eP(t),Uint8Array.of(0),e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await XP(r,pF(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function yF(e){return XN($N(e.length),e)}async function ide(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=await tP(`sha256`,XN($N(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function bF(e,t,n,r,i=/* @__PURE__ */ new Uint8Array,a=/* @__PURE__ */ new Uint8Array){gF(e),gF(t,`deriveBits`);let o=XN(yF(eP(n)),yF(i),yF(a),$N(r));return ide(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3)),r,o)}function xF(e){FP(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new oP(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function SF(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new cP(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return CP(n,t,cP)}}function CF(e,t){if(e!==void 0&&t!==void 0&&e.byteLength===t.byteLength){for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return;throw new cP(`JOSE Header "apu" and "apv" values must be distinct`)}}function ade(e){if(e===void 0)throw new cP(`JWE Encrypted Key missing`)}function wF(e){if(e!==void 0)throw new cP(`Encountered unexpected JWE Encrypted Key`)}function ode(e){if(e!==void 0&&e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxPBES2Count must be a positive safe integer or Infinity`)}async function sde(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return wF(r),n;let c=s===`direct-key-agreement`;switch(c?wF(r):ade(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!yP(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new cP(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);xF(n);let a=await YP(e,r),s=SF(i,`apu`),l=SF(i,`apv`);CF(s,l);let u=await bF(a,n,c?t.alg:o,c?t.cekBits:parseInt(o.slice(-5,-2),10),s,l);if(c)return u;n=u;break}case`RSA-OAEP`:return FP(n),_F(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new cP(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);ode(a);let e=a??1e4;if(i.p2c>e)throw new cP(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new cP(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await vF(CP(i.p2s,`p2s`,cP),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new cP(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new cP(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=CP(i.iv,`iv`,cP),t=CP(i.tag,`tag`,cP);if(e.byteLength!==12)throw new cP(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new cP(`Invalid Authentication Tag length`);return rF(hF(o.slice(0,-2)),n,r,e,t,/* @__PURE__ */ new Uint8Array)}}return rde(o.slice(-6),n,r)}async function cde(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=mF(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await NP(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??ZP(t):void 0;u&&QP(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{xF(l);let{apu:n,apv:i}=a;n!==void 0&&vP(n,`"apu"`),i!==void 0&&vP(i,`"apv"`);let c=n??SF(r,`apu`),u=i??SF(r,`apv`);CF(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await NP(e,a.epk,`decrypt`);let p=crypto.subtle,m=d;if(!m.extractable){if(typeof p.getPublicKey!=`function`)throw TypeError(`CryptoKey for "epk" must be extractable`);m=await p.getPublicKey(d,[])}let{x:h,y:g,crv:_,kty:v}=await p.exportKey(`jwk`,m),y=s===`direct-key-agreement`,b=await bF(l,d,y?t.alg:o,y?t.cekBits:parseInt(o.slice(-5,-2),10),c,u),x={x:h,crv:_,kty:v};if(v===`EC`&&(x.y=g),f={epk:x},n!==void 0&&(f.apu=_P(n)),i!==void 0&&(f.apv=_P(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:FP(l),_F(o,l,`encrypt`),d=new Uint8Array(await crypto.subtle.encrypt(`RSA-OAEP`,l,u));break;case`PBKDF2`:{let{p2c:e=2048,p2s:t=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))}=a;l=await vF(t,o,e,l),f={p2c:e,p2s:_P(t)};break}case`AES-GCM`:{let e=a.iv===void 0?crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)):a.iv;if(!(e instanceof Uint8Array))throw TypeError(`"iv" must be an instance of Uint8Array`);let t=await nF(hF(o.slice(0,-2)),u,l,e,/* @__PURE__ */ new Uint8Array);d=t.ciphertext,f={iv:_P(t.iv),tag:_P(t.tag)}}}if(d??=await nde(o.slice(-6),l,u),!(d instanceof Uint8Array)||!d.byteLength)throw TypeError(`JWE key management algorithm did not produce an Encrypted Key`);return[u,d,f]}function TF(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new oP(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new cP(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function EF(e){if(typeof globalThis[e]>`u`)throw new oP(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function DF(e,t,n=1/0){let r=e.writable.getWriter();r.write(t).catch(()=>{}),r.close().catch(()=>{});let i=[],a=0,o=e.readable.getReader();for(;;){let{value:e,done:t}=await o.read();if(t)break;if(i.push(e),a+=e.byteLength,n!==1/0&&a>n)throw new cP(`Decompressed plaintext exceeded the configured limit`)}return XN(...i)}async function lde(e){return EF(`CompressionStream`),DF(new CompressionStream(`deflate-raw`),e)}async function ude(e,t){return EF(`DecompressionStream`),DF(new DecompressionStream(`deflate-raw`),e,t)}function dde(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=TP(t,cP,`JWE Protected Header is invalid`)),[o,CP(n,`ciphertext`,cP),r===void 0?void 0:CP(r,`iv`,cP),i===void 0?void 0:CP(i,`tag`,cP),wP((t??``)+(a===void 0?``:`.${a}`),`aad`,cP)]}function fde(e){return[e&&OP(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&OP(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function pde(e,t,n,r=dde(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!xP(i,l,u))throw new cP(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);f={...i,...l,...u}}else f=i??{};let[p,m,h,g,_]=t,{encrypted_key:v}=e;AP(cP,DP,h,i,f),TF(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new cP(`missing JWE Algorithm (alg) in JWE Header`);let x=uF[y];if(v===``&&(!x||!mF(x)))throw new cP(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new cP(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new aP(`"alg" (Algorithm) Header Parameter value not allowed`);let ee;if(S){if(b!==void 0)throw new cP(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new cP(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new cP(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new aP(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);ee=hF(b)}let C;if(v!==void 0)try{C=CP(v,`encrypted_key`,cP)}catch(e){if(!x||!mF(x))throw e;C=/* @__PURE__ */ new Uint8Array}let te=!1;typeof n==`function`&&(n=await n(i,e),te=!0);let ne=x??pF(y);mF(ne)&&C===void 0&&(C=/* @__PURE__ */ new Uint8Array);let w=await NP(ne.mode===`direct-encryption`?ee:ne,n,`decrypt`),T;if(ne.mode===`integrated-encryption`)T=await ne.decrypt(w,C,a,c,i,f);else{let e=ee,t;try{t=await sde(ne,e,w,C,f,g),mF(ne)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=ZP(e))}catch(n){if(n instanceof TypeError||n instanceof cP||n instanceof oP)throw n;t=ZP(e)}T=await rF(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new oP(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);T=await ude(T,e).catch(e=>{throw e instanceof cP?e:new cP(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:T,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:CP(d,`aad`,cP)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...te&&{key:w}}}async function mde(e,t,n){if(e instanceof Uint8Array&&(e=qN.decode(e)),typeof e!=`string`)throw new cP(`Compact JWE must be a string or Uint8Array`);let{0:r,1:i,2:a,3:o,4:s,length:c}=e.split(`.`);if(c!==5)throw new cP(`Invalid Compact JWE`);return pde({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function OF(e,t,n){if(!xP(e,t,n))throw new cP(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function hde(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new cP(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);t!==void 0&&(e[8]=t?.crit);let[,r,i,a,o,s,c,l,u]=e;if(o!==void 0&&vP(o,`JWE Additional Authenticated Data`),s!==void 0&&vP(s,`JWE Content Encryption Key`),c!==void 0&&vP(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=MP(cP,r)[0],e[1]=r),i!==void 0&&(i=MP(cP,i)[0],e[2]=i),!n&&a!==void 0&&(a=MP(cP,a)[0],e[3]=a),l!==void 0&&!yP(l))throw TypeError(`JWE Key Management Parameters must be an object`);OF(r,i,a);let d={...r,...i,...a};kP(cP,r),AP(cP,DP,u,r,d),TF(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new cP(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=uF[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new cP(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(s!==void 0)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${f}`);if(c!==void 0)throw TypeError(`setInitializationVector cannot be called with JWE "alg" (Algorithm) Header ${f}`);return[d,void 0,m]}if(typeof p!=`string`||!p)throw new cP(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,hF(p),m]}async function gde(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??pF(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await NP(_,n,`encrypt`):[b,v,y]=await cde(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,OF(h,g,l));let x=h?_P(JSON.stringify(h)):``,S=u?.byteLength?_P(u):void 0,ee=eP(S?`${x}.${S}`:x),C=o;r.zip===`DEF`&&(C=await lde(C).catch(e=>{throw new cP(`Failed to compress plaintext`,{cause:e})}));let te,ne,w;_.mode===`integrated-encryption`?[v,te]=await _.encrypt(b,C,ee,h,r,p):{ciphertext:te,tag:ne,iv:w}=await nF(i,C,b,f,ee);let T={ciphertext:_P(te)};return w&&(T.iv=_P(w)),ne&&(T.tag=_P(ne)),v?.byteLength&&(T.encrypted_key=_P(v)),S&&(T.aad=S),h&&(T.protected=x),l&&(T.unprotected=l),g&&(T.header=g),T}async function _de(e,t,n){return gde(e,hde(e,n),t)}function vde(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}const kF=[[`verify`],[`sign`]];function AF(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:kF}}function jF(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:kF,minRsaBits:2048}}function MF(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:kF}}function NF(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:kF}}function PF(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:kF}}const FF=iF({HS256:AF(256),HS384:AF(384),HS512:AF(512),RS256:jF(256),RS384:jF(384),RS512:jF(512),PS256:jF(256,32),PS384:jF(384,48),PS512:jF(512,64),ES256:MF(`P-256`,256),ES384:MF(`P-384`,384),ES512:MF(`P-521`,512),EdDSA:NF(),Ed25519:NF(),"ML-DSA-44":PF(44),"ML-DSA-65":PF(65),"ML-DSA-87":PF(87)});function IF(e){let t=typeof e==`string`?FF[e]:void 0;if(!t)throw new oP(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function LF(e){return[e&&OP(`algorithms`,e.algorithms),e?.crit]}function yde(e){return e===void 0?{}:TP(e,lP,`JWS Protected Header is invalid`)}function bde(e){try{return eP(e)}catch{throw new lP(`JWS Compact Serialization payload must use only ASCII characters`)}}async function xde(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??yde(a);if(!xP(c,o))throw new lP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=jP(c,AP(lP,EP,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new lP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new aP(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new lP(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new lP(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=IF(d),h=XN(a===void 0?/* @__PURE__ */ new Uint8Array:eP(a),eP(`.`),typeof f==`string`?t[2]??=wP(f,`payload`,lP):f),g=CP(e.signature,`signature`,lP),_=await NP(m,n,`verify`),v=await XP(_,m.subtle,`verify`);m.minRsaBits&&WP(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!y)throw new Wue;let b={payload:typeof f==`string`?CP(f,`payload`,lP):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function RF(e,t,n){if(e instanceof Uint8Array&&(e=qN.decode(e)),typeof e!=`string`)throw new lP(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new lP(`Invalid Compact JWS`);return xde({payload:i,protected:r,signature:a},t,n,bde)}async function zF(e,t,n){let[r]=await RF(e,LF(n),t);return r}const BF=e=>Math.floor(e.getTime()/1e3),Sde={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Cde=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,VF=`check_failed`;function HF(){throw TypeError(`Invalid time period format`)}function UF(e){typeof e!=`string`&&HF();let t=Cde.exec(e);(!t||t[4]&&t[1])&&HF();let n=parseFloat(t[2]),r=Math.round(n*Sde[t[3][0].toLowerCase()]);return Number.isFinite(r)||HF(),t[1]===`-`||t[4]===`ago`?-r:r}function WF(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function GF(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function wde(e){if(typeof e!=`string`&&(!Array.isArray(e)||Array.from(e).some(e=>typeof e!=`string`)))throw TypeError(`"aud" claim must be a string or an array of strings`)}function KF(e,t){return typeof e==`number`?WF(t,e):e instanceof Date?WF(t,BF(e)):BF(/* @__PURE__ */ new Date)+UF(e)}const qF=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Tde=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function JF(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new rP(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function YF(e,t){throw new rP(`unexpected "${t}" claim value`,e,t,VF)}function XF(e,t,n={}){let r;try{r=JSON.parse(JN.decode(t))}catch{}if(!yP(r))throw new uP(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||qF(e.typ)!==qF(i)))throw new rP(`unexpected "typ" JWT header value`,r,`typ`,VF);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new rP(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&YF(r,`iss`),s!==void 0&&r.sub!==s&&YF(r,`sub`),c!==void 0&&!Tde(r.aud,typeof c==`string`?[c]:c)&&YF(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=UF(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}WF(`clockTolerance option`,f);let{currentDate:p}=n,m=WF(`currentDate option`,BF(p===void 0?/* @__PURE__ */ new Date:p)),h=JF(r,`iat`,l!==void 0),g=JF(r,`nbf`);if(g!==void 0&&g>m+f)throw new rP(`"nbf" claim timestamp check failed`,r,`nbf`,VF);let _=JF(r,`exp`);if(_!==void 0&&_<=m-f)throw new iP(`"exp" claim timestamp check failed`,r,`exp`,VF);if(l!==void 0){let e=m-h,t=WF(`maxTokenAge option`,typeof l==`number`?l:UF(l));if(e-f>t)throw new iP(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,VF);if(e<-f)throw new rP(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,VF)}return r}let ZF;function QF(e){return ZF.get(e)}function $F(e){let t=QF(e);for(let e of[`iat`,`nbf`,`exp`]){let n=t[e];if(typeof n==`number`&&!Number.isFinite(n))throw TypeError(`"${e}" claim must be a finite number`)}return KN.encode(JSON.stringify(t))}function eI(e,t){return QF(e)[t]}var tI=class{constructor(e={}){if(!yP(e))throw TypeError(`JWT Claims Set MUST be an object`);(ZF||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return GF(`iss`,e),QF(this).iss=e,this}setSubject(e){return GF(`sub`,e),QF(this).sub=e,this}setAudience(e){return wde(e),QF(this).aud=e,this}setJti(e){return GF(`jti`,e),QF(this).jti=e,this}setNotBefore(e){return QF(this).nbf=KF(e,`setNotBefore`),this}setExpirationTime(e){return QF(this).exp=KF(e,`setExpirationTime`),this}setIssuedAt(e){let t=QF(this);return t.iat=e===void 0?BF(/* @__PURE__ */ new Date):typeof e==`string`?WF(`setIssuedAt`,BF(/* @__PURE__ */ new Date)+UF(e)):KF(e,`setIssuedAt`),this}};async function nI(e,t,n){let[r,i]=await RF(e,LF(n),t);if(!i)throw new uP(`JWTs MUST NOT use unencoded payload`);let a=XF(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function rI(e,t,n){let{plaintext:r,...i}=await mde(e,fde(n),t),{protectedHeader:a}=i,o=XF(a,r,n);for(let e of[`iss`,`sub`,`aud`])if(a[e]!==void 0&&(e===`aud`?JSON.stringify(a.aud)!==JSON.stringify(o.aud):a[e]!==o[e]))throw new rP(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function Ede(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=MP(lP,i);i=e[0],s=_P(e[1])}if(a!==void 0&&(a=MP(lP,a)[0]),!i&&!a)throw new lP(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!xP(i,a))throw new lP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};kP(lP,i);let l=jP(i,AP(lP,EP,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new lP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=IF(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=_P(r),p=t[1]??=eP(f)):(f=_P(r),m=KN.encode(`${s}.${f}`))}m??=XN(eP(s),eP(`.`),p);let h=await XP(await NP(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&WP(d.alg,h);let g={signature:_P(new Uint8Array(await crypto.subtle.sign(d.signing,h,m))),payload:f};return i&&(g.protected=s),a&&(g.header=a),[g,l]}async function Dde(e,t,n,r,i){let[a]=await Ede([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const Ode=tI;var iI=class extends Ode{#e;setProtectedHeader(e){return SP(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return Dde($F(this),this.#e,t?.crit,e,()=>{throw new uP(`JWTs MUST NOT use unencoded payload`)})}};const kde=tI;var Ade=class extends kde{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return SP(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return SP(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return SP(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return SP(this.#e[6],`setInitializationVector`),this.#e[6]=e,this}replicateIssuerAsHeader(){return this.#t=!0,this}replicateSubjectAsHeader(){return this.#n=!0,this}replicateAudienceAsHeader(){return this.#r=!0,this}async encrypt(e,t){let n=$F(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?eI(this,`iss`):void 0,sub:this.#n?eI(this,`sub`):void 0,aud:this.#r?eI(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,vde(await _de(r,e,t))}};function aI(e=`JWK "alg" (Algorithm) Parameter`){throw new oP(`Invalid or unsupported ${e} value`)}function oI(e,t){return(typeof e==`string`?FF[e]??uF[e]:void 0)??aI(t)}async function sI(e){if(LP(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:_P(e)};if(!IP(e))throw TypeError(BP(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let t=await crypto.subtle.exportKey(`jwk`,e);delete t.ext,delete t.key_ops,delete t.use,t.kty!==`AKP`&&delete t.alg;for(let e of Object.keys(t))t[e]===void 0&&delete t[e];return t}const cI=(e,t)=>{if(typeof e!=`string`||!e)throw new dP(`${t} missing or invalid`)};async function lI(e,t){let n;if(yP(e)){if(n=KP(e),typeof n.kty!=`string`)throw TypeError(BP(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(RP(e))n=KP(await sI(e));else throw TypeError(BP(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:cI(n.alg,`"alg" (Algorithm) Parameter`),cI(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:cI(n.crv,`"crv" (Curve) Parameter`),cI(n.x,`"x" (X Coordinate) Parameter`),cI(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:cI(n.crv,`"crv" (Subtype of Key Pair) Parameter`),cI(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:cI(n.e,`"e" (Exponent) Parameter`),cI(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:if(typeof n.k!=`string`)throw new dP(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new oP(`"kty" (Key Type) Parameter missing or unsupported`)}let i=eP(JSON.stringify(r));return _P(await tP(t,i))}function jde(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function uI(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=YP(n,t,!0).then(e=>{if(e.type!==`public`)throw new fP(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function dI(e){let t;try{t=structuredClone(e)}catch{}if(!bP(t))throw new fP(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=KP(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=/* @__PURE__ */ new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?FF[a]:void 0;if(!s||s.secret)throw new oP(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>jde(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new pP;if(u!==1){let e=new mP;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await uI(r,e,s)}catch{}},e}return uI(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Mde(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let fI;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(fI=`jose/v6.2.12`);const Nde=/* @__PURE__ */ Symbol();async function Pde(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new hP:e});if(i.status!==200)throw new nP(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new nP(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Fde=/* @__PURE__ */ Symbol();function pI(e,t){return Number.isFinite(e)&&Date.now()<e+t}function mI(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function Ide(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=mI(r.cooldownDuration,3e4,`cooldownDuration`),s=mI(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);fI&&!c.has(`User-Agent`)&&c.set(`User-Agent`,fI),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[Nde],u=r[Fde],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;pI(e,s)&&bP(t)&&(d=e,h=dI(t))}let g=async()=>{if(f&&Mde()&&(f=void 0),!f){let e=++p,t=f=Pde(n,c,AbortSignal.timeout(a),l).then(t=>{let n=dI(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!pI(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof pP&&!pI(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>pI(d,o),enumerable:!0},fresh:{get:()=>pI(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}async function hI(e,t,n){if(!yP(e))throw TypeError(`JWK must be an object`);let r=qP(e),i=JP(n?.extractable),{alg:a}=r;if(t??=a,r.kty!==`oct`&&!t)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);switch(r.kty){case`oct`:if(typeof r.k!=`string`)throw TypeError(`missing "k" (Key Value) Parameter value`);return gP(r.k);case`AKP`:if(typeof a!=`string`||!a)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==a)throw TypeError(`JWK alg and alg option value mismatch`);return YP(oI(t),r,i);case`RSA`:case`EC`:case`OKP`:return YP(oI(t),r,i);default:throw new oP(`Unsupported "kty" (Key Type) Parameter value`)}}function gI(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e){if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`)}let n=`Invalid Token or Protected Header formatting`;if(typeof t!=`string`||!t)throw TypeError(n);return TP(t,TypeError,n)}function _I(e){if(typeof e!=`string`)throw new uP(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new uP(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new uP(`Invalid JWT`);if(!t)throw new uP(`JWTs must contain a payload`);let r;try{r=gP(t)}catch{throw new uP(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(JN.decode(r))}catch{throw new uP(`Failed to parse the decoded payload as JSON`)}if(!yP(i))throw new uP(`Invalid JWT Claims Set`);return i}function Lde(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new oP(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Rde(e,t){let n=JP(t?.extractable),r=oI(e,`"alg" (Algorithm)`);r.secret&&aI(`"alg" (Algorithm)`);let i;if(r.resolve){let e=t?.crv??`P-256`;if(![`P-256`,`P-384`,`P-521`,`X25519`].includes(e))throw new oP(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`);i=r.resolve({crv:e})}else{if(r.crv!==void 0&&t?.crv!==void 0&&t.crv!==r.crv)throw new oP(`Invalid or unsupported crv option provided, the only supported value for ${e} is ${r.crv}`);i=r.kty[0]===`RSA`?{...r.subtle,publicExponent:Uint8Array.of(1,0,1),modulusLength:Lde(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}const vI=`key-list+jwt`,zde=W({keys:G(W({id:U,sealed:U}))}),yI=VS(W({keyId:IS,ownerId:IS,scopes:G(IS),expiresAt:sS(CS)})),bI=new TextEncoder,Bde=async e=>new Uint8Array(await crypto.subtle.digest(`SHA-256`,bI.encode(e))),xI=async(e,t)=>{let n=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveBits`]),r=new Uint8Array(await crypto.subtle.deriveBits({name:`HKDF`,hash:`SHA-256`,salt:/* @__PURE__ */ new Uint8Array,info:bI.encode(`clankerauth key list\0${t}`)},n,512));return{id:_P(r.subarray(0,32)),key:await crypto.subtle.importKey(`raw`,r.subarray(32),`AES-GCM`,!1,[`encrypt`,`decrypt`])}},Vde=async(e,t,n)=>{let{id:r,key:i}=await xI(e,t),a=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a},i,bI.encode(zx(yI)(n))),s=new Uint8Array(a.length+o.byteLength);return s.set(a),s.set(new Uint8Array(o),a.length),{id:r,sealed:_P(s)}},Hde=async(e,t,n)=>{let r=await xI(await Bde(e),t),i=n.get(r.id);if(i===void 0)return;let a=new Uint8Array(gP(i)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.subarray(0,12)},r.key,a.subarray(12));return Fx(yI)(new TextDecoder().decode(o))},SI=Symbol.for(`@gjermundgaraba/effect-actions/Anyone`),CI=(e,t)=>{for(let n of e)if(n.caller!==SI&&(t===void 0||n.caller.key!==t.identity.key))throw Error(`Protected action '${n.name}' requires its matching authentication descriptor`)},wI=e=>U.pipe(pS(F(e))),Ude=W({path:G(K([U,CS])),message:U}),Wde=W_();var TI=class e extends fC()(`InvalidInput`,{message:wI(`The input does not match the action's input.`),issues:G(Ude).pipe(pS(F([])))},{httpApiStatus:400}){static fromSchemaError=({issue:t,message:n})=>new e({message:n,issues:Wde(t).issues.map(e=>({path:(e.path??[]).map(e=>{let t=qt(e)?e:e.key;return Kt(t)?String(t):t}),message:e.message}))})},EI=class extends fC()(`Unauthenticated`,{message:wI(`Authentication is required.`)},{httpApiStatus:401}){};const DI=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Gde=U.check(SS(DI));var OI=class extends fC()(`Forbidden`,{message:wI(`Not allowed.`),scopes:Hx(iS(Gde))},{httpApiStatus:403}){};const kI=[EI,OI],Kde=K(kI),AI=[TI,...kI];K(AI);const qde=/^[A-Za-z0-9_-]{1,128}$/,Jde=(e,t)=>{if(!qde.test(t)||t===`then`)throw Error(`Invalid ${e}: ${t}`)},jI=(e,t,n,r=n)=>{let i=/* @__PURE__ */ new Map;for(let a of t){let t=n(a),o=r(a),s=i.get(t);if(s!==void 0){let n=s===o?``:`, claimed by ${s} and ${o}`;throw Error(`Duplicate ${e}: ${t}${n}`)}i.set(t,o)}},MI=(e,t)=>jI(e,t,e=>e.name),Yde=(e,t,n)=>{let r=t.filter(e=>!n.includes(e));if(r.length>0)throw Error(`Unknown ${e}: ${r.join(`, `)}`)},NI=e=>Iv(e)?NI(e.thunk()):e,PI=e=>{let t=NI(e);return Fv(t)?t.types.flatMap(PI):[t]},Xde=e=>jv(e)?[e.literal]:wie(e)?e.enums.map(([,e])=>e):[void 0],FI=e=>e===void 0?[]:Vx(e)?[e]:e,II=(e,t=[])=>[.../* @__PURE__ */ new Set([...AI,...e.error,...t])],Zde=(e,t)=>II(e,e.caller===SI||t.authentication===void 0?t.error:[...t.error,...t.authentication.error]),LI=e=>PI(ib(e)).flatMap(e=>{let t=Pv(e)?e.propertySignatures.find(e=>e.name===`_tag`)?.type:void 0;return t===void 0?[]:PI(t).flatMap(Xde).filter(Ut)}),Qde=new Set(AI.flatMap(e=>LI(e.ast))),RI=(e,t)=>{let n=t.flatMap(e=>LI(e.ast)).find(e=>Qde.has(e));if(n!==void 0)throw Error(`${e}: error _tag "${n}" is built in, and declared on every surface`)},$de=(e,t,n)=>{MI(`action`,t);let r=FI(n.error);return RI(e,r),CI(t,n.authentication),{error:r,authentication:n.authentication}},efe=()=>Math.random().toString(36).slice(2),zI=e=>{let t=P(`effect-actions/Implementation/${efe()}`);return{key:t,layer:bf(t,e)}};var BI=class e{actions;#e;#t;constructor(e,t,n){this.actions=e,this.#e=t,this.#t=n}static share(t,n){let r=e.own(n);return new e(t,r.#e,r.#t)}static runKey(t){return e.own(t).#e.key.key}static layerOf(t){let n=e.own(t);return t.actions.some(e=>e.caller!==SI)?Of(n.#e.layer,n.#t.layer):n.#e.layer}static boundOf(t){let{actions:n}=t,r=e.own(t);return R(function*(){let e=yield*r.#e.key,t=n.some(e=>e.caller!==SI)?yield*r.#t.key:()=>L;return n.flatMap(n=>e.flatMap(([e,r])=>e===n?[[n,rfe(n,r,t)]]:[]))})}static own(e){if(!(#e in e))throw Error(`Not an implementation made by this Action.implement: is effect-actions installed twice?`);return e}};const VI=e=>Va(e),HI=(e,t,n)=>{let r=t.filter(e=>!n.includes(e));if(r.length>0){let t=new Set(n.map(({name:e})=>e));throw Error(`Listed in actions, but ${e}: ${r.map(({name:e})=>t.has(e)?`${e} (another contract)`:e).join(`, `)}`)}},UI=(e,t)=>t===void 0?e:(HI(`no implementation holds it`,t,e.flatMap(e=>e.actions)),e.flatMap(e=>{let n=e.actions.filter(e=>t.includes(e));return n.length===0?[]:n.length===e.actions.length?[e]:[BI.share(n,e)]})),tfe=(e,t,n,r)=>{r!==void 0&&HI(`the binding does not hold it`,r,t);let i=n.flatMap(e=>e.actions),a=UI(n,r??t.filter(e=>i.includes(e))),o=a.flatMap(e=>e.actions);if(o.length===0&&r===void 0&&n.length>0){let n=new Set(t.map(({name:e})=>e));throw Error(`No action of these implementations is in this ${e}: ${i.map(({name:e})=>n.has(e)?`${e} (another contract)`:e).join(`, `)||`none`}`)}return MI(`served action`,o),a},nfe=(e,t,n,r)=>{let i=tfe(e,t.actions,VI(n),r.actions),a=i.flatMap(e=>e.actions);return CI(a,t.authentication),jI(`middleware`,r.middleware??[],e=>e.key),{apps:i,actions:a,authentication:a.some(e=>e.caller!==SI)?t.authentication:void 0}},WI=e=>t=>{let[n,...r]=e.map(e=>BI.layerOf(e));return n===void 0?t:Af(t,Df(n,...r))},GI=e=>V(ep(e,e=>BI.boundOf(e)),e=>e.flat()),rfe=(e,t,n)=>{let r={"action.name":e.name,"action.read_only":e.readOnly},i=e.caller===SI?L:B(Hp(e.caller),e=>Ii(e)?L:z(new EI)),a=e.caller===SI?L:ap(()=>n(e)),o=Nx(Wx(K(II(e)))),s=(e,t)=>{let n=ra(e.annotations);return[ed(e.error).annotate(n),ed(ad(t)).annotate(n)]},c=H(function*(e){let t=[];for(let n of e.reasons)if(Yu(n)){let e=yield*_p(o(n.error));t.push(...Dd(e)?[n]:s(n,e.cause))}else t.push(n);return yield*cp(Xu(t))});return n=>Kp(i.pipe(mp(a),mp(ap(()=>t(n))),Sp(c))).pipe(Em(r),cm(e.name,{attributes:r},{captureStackTrace:!1}))},KI={errors:`all`,onExcessProperty:`error`},qI=`effect-actions/media`,JI=W({data:KS,mimeType:U});JI.annotate({[qI]:`image`});const YI=e=>e.annotations?.[qI]===`image`,XI=e=>YI(e)&&e.encoding===void 0?`image`:void 0,ife=tS(U,qx),ZI=e=>Vx(e)?e:Reflect.ownKeys(e).length===0?ife:W(e);function QI(e,t){Jde(`action name`,e);let{caller:n,readOnly:r}=t;if(n!==SI&&!sa(n))throw Error(`Missing caller: declare Action.Anyone or an identity service key`);if(n!==SI&&ca(n))throw Error(`Invalid caller: an identity is a Context.Service, not a Context.Reference`);if(r!==!0&&r!==!1)throw Error(`Invalid readOnly: ${String(r)}`);let i={caller:n,name:e,description:t.description,input:ZI(t.input??{}),success:t.success===void 0?Qx:ZI(t.success),error:FI(t.error),readOnly:r,mcp:{...t.mcp}};return RI(`Action "${i.name}"`,i.error),i}const afe=()=>L,$I=e=>{if(!Jt(e))throw Error(`Missing authorize: pass an authorization function, or Action.allowAll`);return e},ofe=e=>{if(e===void 0)throw Error(`Protected actions require authorize, or Action.allowAll`);return e},sfe=e=>{if(e!==void 0)throw Error(`A public-only target takes no authorize`);return afe},cfe=e=>zI(Qf(e)?V(e,$I):F($I(e)));function eL(e,t,n){let r=Va(e),i=r.map(e=>e.name);MI(`action`,r);let a=cfe(r.some(e=>e.caller!==SI)?ofe(n?.authorize):sfe(n?.authorize)),o=t=>{let n=Jt(t)?Object.fromEntries(Array.isArray(e)?[]:r.map(({name:e})=>[e,t])):t;Yde(`handlers`,Object.keys(n),i);let a=r.flatMap(e=>{let t=Object.hasOwn(n,e.name)?n[e.name]:void 0;return Jt(t)?[[e,t]]:[]}),o=i.filter(e=>!a.some(([t])=>t.name===e));if(o.length>0)throw Error(`Missing handlers: ${o.join(`, `)}`);return a},s=Qf(t)?V(t,o):F(o(t));return new BI(r,zI(s),a)}const tL=e=>B(Vp(e[`~provider`]),t=>t.descriptor===e?F(t):up(/* @__PURE__ */ Error(`Authentication "${e.name}": the binding's descriptor is not its provider's; build both from one descriptor`))),lfe=(e,t)=>B(Hp(e[`~verified`]),n=>Ii(n)?Wp(t,e.identity,n.value):z(new EI)),nL=gb(`httpApiStatus`),rL=e=>nL(e)??(Iv(e)?rL(e.thunk()):void 0),iL=e=>{let t=rL(e.ast);if(t!==void 0)return[nL(e.ast)===void 0?e.annotate({httpApiStatus:t}):e];let n=NI(e.ast);return Fv(n)&&n.checks===void 0&&n.encoding===void 0?n.types.flatMap(e=>iL(Bx(e))):[e.annotate({httpApiStatus:422})]},ufe={write(e){switch(e._tag){case`Event`:{let t=``;return e.id!==void 0&&(t+=`id: ${e.id}\n`),e.event!==`message`&&(t+=`event: ${e.event}\n`),t+=`data: ${e.data.replace(/\r\n|\r|\n/g,`
24
+ data: `)}\n`,t+`
25
+ `}case`Retry`:return`retry: ${yo(e.duration)}\n\n`}}};function aL(e){let t=typeof e==`string`?Bue(e):e;return e=>e.annotate({httpApiStatus:t})}const dfe=/*#__PURE__*/ (e=>Qx.pipe(aL(e)))(204),oL=e=>Vx(e)&&N(e,`~effect/http-api/HttpApiSchema/Stream`),sL=e=>oL(e)&&e._tag===`StreamSse`,ffe=e=>oL(e)&&e._tag===`StreamUint8Array`,cL=`~effect/http-api/HttpApiSchema/WithHeaders`,pfe=e=>N(e,`~effect/http-api/HttpApiSchema/WithHeadersValue`),lL=e=>Vx(e)&&N(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function uL(e,t,n){return Bx(e.ast,{[cL]:cL,schema:t,headers:n})}function dL(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??fL(t._tag)}})}function fL(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function pL(e){return t=>dL(t,{_tag:`Json`,...e})}function mL(e){return t=>dL(t,{_tag:`FormUrlEncoded`,...e})}const hL=e=>{if(Av(e))return!0;let t=ib(e);if(Av(t))return!0;let n=e.encoding?.[0].to;return n!==void 0&&Av(n)},gL=/*#__PURE__*/ gb(`~httpApiEncoding`),_L=/*#__PURE__*/ gb(`~httpApiWithHeaders`),vL=/*#__PURE__*/ gb(`httpApiStatus`),yL={_tag:`Json`,contentType:`application/json`},bL={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function xL(e){return gL(e)??yL}function SL(e,t){return gL(e)||(yO(t)?yL:bL)}function CL(e){let t=xL(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function wL(e){return vL(e)??200}function TL(e){return lL(e)?vL(e.ast)??wL(e.schema.ast):wL(e.ast)}function EL(e){return lL(e)&&gL(e.ast)===void 0?CL(e.schema.ast):CL(e.ast)}function DL(e){return vL(e)??500}function OL(e){return lL(e)?vL(e.ast)??DL(e.schema.ast):DL(e.ast)}function kL(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}const AL=`~effect/http-api/HttpApiEndpoint`;function jL(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function ML(e){let t=Array.from(e.success);return Ua(t)?t:[dfe]}function NL(e){let t=new Set(e.error),n=e.disableCodecs?M:HL;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}const PL={[AL]:AL,pipe(){return Ot(this,arguments)},prefix(e){return IL({...FL(this),path:jM(this.path,e)})},middleware(e){return IL({...FL(this),middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},annotate(e,t){return IL({...FL(this),annotations:fa(this.annotations,e,t)})},annotateMerge(e){return IL({...FL(this),annotations:Ca(this.annotations,e)})}},FL=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function IL(e){function t(){}return Object.setPrototypeOf(t,PL),Object.assign(t,e)}const LL=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?M:hC;return IL({identifier:t,path:n,method:e,params:RL(r?.params,a),query:RL(r?.query,a),headers:RL(r?.headers,a),payload:zL(r?.payload,e,i),success:VL(r?.success,e,i),error:UL(r?.error,i),annotations:la(),middlewares:/* @__PURE__ */ new Set,disableCodecs:i})};function RL(e,t){if(e!==void 0)return Vx(e)?t(e):t(W(e))}function zL(e,t,n){let r=/* @__PURE__ */ new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:Vx(e)?[e]:[W(e).pipe(mL())],a=n?M:$L;for(let e of i){let n=SL(e.ast,t),i=kL(n.contentType),o=r.get(i);if(o){if(o.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(o.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);o.schemas.push(a(e,t))}else r.set(i,{encoding:n,schemas:[a(e,t)]})}return r}const BL=`effect/http-api/stream/failure`;function VL(e,t,n){if(e===void 0)return/* @__PURE__ */ new Set;let r=Va(e);return WL(r,t),new Set(n?r:r.map(HL))}const HL=/*#__PURE__*/ Lt(e=>oL(e)?e:lL(e)?uL(e,oL(e.schema)?e.schema:QL(e.schema,EL(e)),hC(e.headers)):ZL(e));function UL(e,t){if(e===void 0)return/* @__PURE__ */ new Set;let n=Va(e);for(let e of n){let t=lL(e)?e.schema:e;if(oL(t))throw Error(`Streaming schemas are not supported in error responses`)}return KL(n,OL),new Set(t?n:n.map(HL))}function WL(e,t){let n=!1,r=/* @__PURE__ */ new Map;for(let i of e){let e=lL(i)?i.schema:i,a=TL(i);if(oL(e)){if(qL(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=GL(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(kL(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);r.set(a,{...i,stream:e})}else{let t=GL(r,a),n=hL(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=EL(i);if(kL(e.contentType)===kL(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(kL(EL(i).contentType)),t.noContent=t.noContent||n}}KL(e,TL)}function GL(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:/* @__PURE__ */ new Set,noContent:!1},e.set(t,n)),n}function KL(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=_L(r.ast),a=lL(r)?r.schema:i?.body??r,o=hL(a.ast)?``:kL(oL(a)?a.contentType:EL(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:/* @__PURE__ */ new Set},n.set(e,s));let c=()=>/* @__PURE__ */ Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(lL(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function qL(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(sL(e)&&JL(e.events.ast))throw Error(`SSE event name is reserved: ${BL}`)}function JL(e){return YL(ib(e),/* @__PURE__ */ new Set)}function YL(e,t){if(t.has(e))return!1;if(t.add(e),Fv(e))return e.types.some(e=>YL(e,t));if(Iv(e))return YL(e.thunk(),t);if(!Pv(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&XL(n.type,t)}function XL(e,t){if(t.has(e))return!1;t.add(e);let n=ib(e);return n===e?jv(e)?e.literal===BL:Fv(e)?e.types.some(e=>XL(e,t)):Iv(e)?XL(e.thunk(),t):!1:XL(n,t)}function ZL(e){let t=CL(e.ast),n=_L(e.ast);return n===void 0?QL(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:QL(n.body,t),headersCodec:hC(n.headers)}})}function QL(e,t){switch(t._tag){case`Json`:return mC(e);case`FormUrlEncoded`:return hC(e);case`Text`:case`Uint8Array`:return e}}function $L(e,t){switch(SL(e.ast,t)._tag){case`Json`:return mC(e);case`FormUrlEncoded`:return hC(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}const eR=/*#__PURE__*/ LL(`POST`),tR=`~effect/http-api/HttpApi`,nR={[tR]:tR,pipe(){return Ot(this,arguments)},add(...e){let t={...this.groups};for(let n of e)dr(t,n.identifier,n);return iR({...rR(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];dr(t,n,r.annotateMerge(Ca(e.annotations,r.annotations)))}return iR({...rR(this),groups:t})},prefix(e){return iR({...rR(this),groups:La(this.groups,t=>t.prefix(e))})},middleware(e){return iR({...rR(this),groups:La(this.groups,t=>t.middleware(e))})},annotate(e,t){return iR({...rR(this),annotations:fa(this.annotations,e,t)})},annotateMerge(e){return iR({...rR(this),annotations:Ca(this.annotations,e)})}},rR=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),iR=e=>{function t(){}return Object.setPrototypeOf(t,nR),Object.assign(t,e)},aR=e=>iR({identifier:e,groups:{},annotations:la()}),oR=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=Ca(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:Ca(n,e.annotations),successes:sR(ML(e),TL),errors:sR(NL(e),OL)})}},sR=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach(r),n;function r(e){let r=lL(e)?e.schema:e;if(oL(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}};var cR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/AdditionalSchemas`)){},lR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParseOptions`)){},uR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParamsParseOptions`)){},dR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/QueryParseOptions`)){},fR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/HeadersParseOptions`)){},pR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/PayloadParseOptions`)){},mR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/SuccessParseOptions`)){},hR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ErrorParseOptions`)){};const gR=e=>{let t=ha(e,lR);return{params:ha(e,uR)??t,query:ha(e,dR)??t,headers:ha(e,fR)??t,payload:ha(e,pR)??t,success:ha(e,mR)??t,error:ha(e,hR)??t}},_R=/*#__PURE__*/ fA({status:400}),vR=/*#__PURE__*/ fA({status:500}),yR=`~effect/http-api/HttpApiError/HttpApiSchemaError`;var bR=class e extends (/*#__PURE__*/ Fte(`HttpApiSchemaError`)){[yR]=yR;get[NE](){return this.kind!==`Body`&&this.kind!==`ResponseHeaders`}static is(e){return N(e,yR)}static wrap(t,n){return km(n,n=>new e({kind:t,cause:n}))}name=`HttpApiSchemaError`;message=this.kind;[qA](){return F(this[`~effect/ErrorReporter/ignore`]?_R:vR)}};const xR=`~effect/http-api/HttpApiMiddleware`,SR=`~effect/http-api/HttpApiMiddleware/Security`,CR=e=>N(e,SR),wR=()=>(e,t)=>{let n=sr(),r;n!==0&&(cr(2),r=new globalThis.Error,cr(n));class i extends P()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[xR]=xR,a.error=TR(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[SR]=SR,a.security=t.security}return a};function TR(e){return e===void 0?/* @__PURE__ */ new Set:new Set(Array.isArray(e)?e:[e])}const ER=(e,t)=>_f(e,(e,n)=>bp(e,e=>bR.is(e)?t(e,n):z(e))),DR=/*#__PURE__*/ new Set;function OR(e){if(e===void 0)return DR;let t=Hy(e.ast);return Pv(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function kR(e,t){if(t===void 0||!e.includes(`:`))return e;let n=OR(t);if(n===void 0)return e;let r=``,i=0,a=-1;for(let t=0;t<e.length;t++){let o=e[t];if(i>0||t===a){r+=o,o===`\\`?r+=e[++t]??``:o===`(`?i++:o===`)`&&i--;continue}if(o!==`:`){r+=o;continue}if(e[t+1]===`:`){r+=`::`,t++;continue}let s=/^:(\w+)/.exec(e.slice(t));if(s!==null&&n.has(s[1])){r+=s[0],t+=s[0].length-1;let n=e[t+1];n===`(`?a=t+1:n!==void 0&&!`/.-?`.includes(n)&&(r+=`(.*?)`)}else r+=`::`}return r}var AR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Identifier`)){},jR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Title`)){},MR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Version`)){},NR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Description`)){},PR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/License`)){},FR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/ExternalDocs`)){},IR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Servers`)){},LR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Format`)){},RR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Summary`)){},zR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Deprecated`)){},BR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Override`)){};const VR=/*#__PURE__*/ Ea(`effect/http-api/OpenApi/Exclude`,{defaultValue:Nt});var HR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Transform`)){};const UR={},WR=/*#__PURE__*/ new WeakMap,GR=e=>{if(Array.isArray(e))return e.map(GR);if(typeof e==`object`&&e&&!Object.isFrozen(e)){let t={};for(let n of Object.keys(e))dr(t,n,GR(e[n]));return t}return e};function KR(e,t,n){let r=Sa(e,t);Ii(r)&&n(r.value)}function qR(e,t){let n=t??UR,r=WR.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,WR.set(n,r));let i=r.get(e);if(i!==void 0)return GR(i);let a=JR(e,n);return r.set(e,GR(a)),a}function JR(e,t){let n={openapi:`3.1.0`,info:{title:`Api`,version:`0.0.1`},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]},r=[],i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[];function s(e,t=`Json`){let n=t===`Text`?{type:`string`}:{};return r.push({_tag:`schema`,ast:iz(e,t),target:n}),n}KR(e.annotations,jR,e=>{n.info.title=e}),KR(e.annotations,MR,e=>{n.info.version=e}),KR(e.annotations,NR,e=>{n.info.description=e}),KR(e.annotations,PR,e=>{n.info.license=e}),KR(e.annotations,RR,e=>{n.info.summary=e}),KR(e.annotations,IR,e=>{n.servers=[...e]}),oR(e,{onGroup({group:e}){if(va(e.annotations,VR))return;let t={name:ma(e.annotations,jR,()=>e.identifier)};KR(e.annotations,NR,e=>{t.description=e}),KR(e.annotations,FR,e=>{t.externalDocs=e}),KR(e.annotations,BR,e=>{for(let[n,r]of Object.entries(e))dr(t,n,r)}),KR(e.annotations,HR,e=>{t=e(t)}),n.tags.push(t)},onEndpoint({endpoint:e,group:t,mergedAnnotations:c,middleware:l}){if(va(c,VR))return;let u={tags:[ma(t.annotations,jR,()=>t.identifier)],operationId:ma(e.annotations,AR,()=>t.topLevel?e.identifier:`${t.identifier}.${e.identifier}`),parameters:[],security:[],responses:{}},d=OR(e.params),f=e.path.replace(/:(\w+)\??/g,(e,t)=>d===void 0||d.has(t)?`{${t}}`:e),p=e.method.toLowerCase(),m=p===`query`,h=m?`QUERY`:p;function g(e,t){for(let[n,{content:i,descriptions:a,headers:o,streamContent:c}]of e){let e=a.size>0?Array.from(a).join(` | `):t();dr(u.responses,n,{description:e});for(let e of o)r.push({_tag:`properties`,ast:e.ast,select:e=>String(e.name).toLowerCase()!==`content-type`,apply(e,t){let r=String(e.name).toLowerCase();u.responses[n].headers??={},dr(u.responses[n].headers,r,{schema:t,required:!e.isOptional})}});i!==void 0&&i.forEach((e,t)=>{e.forEach((e,r)=>{let i=Array.from(e,hy),a=i.length===1?i[0]:new Ty(i);u.responses[n].content??={},dr(u.responses[n].content,r,{schema:s(a,t)})})}),c!==void 0&&c.forEach((e,t)=>{u.responses[n].content??={},sL(e)?dr(u.responses[n].content,t,{schema:s(e.events.ast),"x-effect-stream":{encoding:`sse`,causeSchema:s(YS(e.error,zS()).ast),errorSchema:s(e.error.ast),failureEvent:$R}}):dr(u.responses[n].content,t,{schema:{type:`string`,format:`binary`},"x-effect-stream":{encoding:`uint8array`}})})}}function _(e,t){e&&r.push({_tag:`properties`,ast:e.ast,apply(e,n){u.parameters.push({name:String(e.name),in:t,schema:n,required:t===`path`||!e.isOptional})}})}KR(e.annotations,NR,e=>{u.description=e}),KR(e.annotations,RR,e=>{u.summary=e}),KR(e.annotations,zR,e=>{u.deprecated=e}),KR(e.annotations,FR,e=>{u.externalDocs=e}),l.forEach(e=>{if(CR(e))for(let[t,n]of Object.entries(e.security))v(t,n),u.security.push({[t]:[]})});function v(e,t){let r=oz(t);if(!Object.hasOwn(n.components.securitySchemes,e))dr(n.components.securitySchemes,e,r);else if(!Dn(sz(n.components.securitySchemes[e]),sz(r)))throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${e}`)}let y=yO(e.method);if(y){let t=/* @__PURE__ */ new Map;for(let n of jL(e)){if(hL(n.ast))continue;let r=SL(n.ast,e.method),i=t.get(r.contentType);i===void 0?t.set(r.contentType,{encoding:r,schemas:[n]}):i.schemas.push(n)}if(t.size>0){let e={};for(let[n,{encoding:r,schemas:i}]of t){let t=i.map(hy);dr(e,n,{schema:s(t.length===1?t[0]:new Ty(t),r._tag)})}u.requestBody={content:e,required:!0}}}if(_(e.params,`path`),!y&&e.payload.size===1){let t=e.payload.values().next().value;_(t.schemas[0],`query`)}_(e.headers,`header`),_(e.query,`query`),g(ez(e),()=>`Success`),g(tz(NL(e),OL,nz),()=>`Error`);let b=`${p} ${f.replace(/\{[^}]+\}/g,`{}`)}`;if(i.has(b))throw new globalThis.Error(`Duplicate OpenAPI operation for ${e.method} ${f}`);i.add(b),Object.hasOwn(n.paths,f)||dr(n.paths,f,{});let x=()=>{let e=n.paths[f];return m?e[`x-oai-additionalOperations`]??={}:e};x()[h]=u,o.push(()=>{let t=x(),n=t[h];KR(e.annotations,BR,e=>{for(let[t,r]of Object.entries(e))dr(n,t,r)}),KR(e.annotations,HR,e=>{n=e(n)});let r=n.operationId;if(r!==void 0){if(a.has(r))throw new globalThis.Error(`Duplicate OpenAPI operationId: ${r}`);a.add(r)}t[h]=n})}}),KR(e.annotations,cR,e=>{e.forEach(e=>{let t=_b(e.ast);if(t!==void 0){if(Object.hasOwn(n.components.schemas,t))throw new globalThis.Error(`Duplicate component schema identifier: ${t}`);dr(n.components.schemas,t,s(e.ast))}})}),YR(r,t,n.components.schemas);for(let e of o)e();return Object.keys(n.components.schemas).forEach(e=>{if(!Yb.test(e))throw new globalThis.Error(`Invalid component schema key: ${e}`)}),KR(e.annotations,BR,e=>{for(let[t,r]of Object.entries(e))dr(n,t,r)}),KR(e.annotations,HR,e=>{n=e(n)}),n}function YR(e,t,n){if(!Ua(e))return;let r=xx(qa(e,e=>e.ast),t),i=qa(r.representations,(t,n)=>{let i=e[n];return i._tag===`schema`?t:XR(t,r.references,i.select)}),a=Nae(roe({representations:i,references:QR(i,r.references)},{onExcessProperty:`error`}));for(let t=0;t<e.length;t++){let n=e[t],r=a.schemas[t];if(n._tag===`schema`){fr(n.target,r);continue}let o=i[t];if(o._tag!==`Objects`)throw new globalThis.Error(`Expected an object representation for HTTP properties`);let s=r.properties;for(let e of o.propertySignatures)n.apply(e,s[String(e.name)])}for(let[e,t]of Object.entries(a.definitions))dr(n,e,t)}function XR(e,t,n){let r=ZR(e,t);return{_tag:`Objects`,propertySignatures:r._tag===`Objects`?r.propertySignatures.filter(e=>n?.(e)??!0).map(e=>({...e,name:String(e.name)})):[],indexSignatures:[],checks:[]}}function ZR(e,t,n=/* @__PURE__ */ new Set){if(e._tag===`Suspend`)return ZR(e.thunk,t,n);if(e._tag!==`Reference`||n.has(e.$ref))return e;let r=t[e.$ref];return r===void 0?e:ZR(r,t,new Set(n).add(e.$ref))}function QR(e,t){let n={},r=/* @__PURE__ */ new WeakSet,i=[...e];function a(e){for(let t of e)t.representation?.schemas!==void 0&&i.push(...t.representation.schemas),t._tag===`FilterGroup`&&a(t.checks)}for(;i.length>0;){let e=i.pop();if(!r.has(e)){if(r.add(e),e._tag===`Reference`){if(Object.hasOwn(n,e.$ref))continue;let r=t[e.$ref];if(r===void 0)continue;dr(n,e.$ref,r),i.push(r)}else switch(a(e.checks),e._tag){case`Declaration`:i.push(...e.typeParameters);break;case`Suspend`:i.push(e.thunk);break;case`TemplateLiteral`:i.push(...e.parts);break;case`Arrays`:for(let t of e.elements)i.push(t.type);i.push(...e.rest);break;case`Objects`:for(let t of e.propertySignatures)i.push(t.type);for(let t of e.indexSignatures)i.push(t.parameter,t.type);break;case`Union`:i.push(...e.types)}}}return n}const $R=`effect/http-api/stream/failure`;function ez(e){return tz(ML(e),TL,nz)}function tz(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(i),r;function i(e){let i=_L(e.ast),c=lL(e)?e.schema:i?.body??e,l=lL(e)?e.headers:i?.headersCodec,u=t(e),d=c.ast;oL(c)?s(c,u):hL(d)?a(u,n(e.ast)??n(d)??`<No Content>`):o(c,u,EL(e),n(e.ast)??n(d)),l!==void 0&&r.get(u).headers.push(l)}function a(e,t){let n=r.get(e);n===void 0?r.set(e,{descriptions:/* @__PURE__ */ new Set([t]),content:void 0,headers:[],streamContent:void 0}):t!==void 0&&n.descriptions.add(t)}function o(e,t,n,i){let a=r.get(t),{_tag:o,contentType:s}=n;if(a===void 0)r.set(t,{descriptions:new Set(i===void 0?[]:[i]),content:/* @__PURE__ */ new Map([[o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]])]]),headers:[],streamContent:void 0});else if(i!==void 0&&a.descriptions.add(i),a.content===void 0)a.content=/* @__PURE__ */ new Map([[o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]])]]);else{let t=a.content.get(o);if(t===void 0)a.content.set(o,/* @__PURE__ */ new Map([[s,/* @__PURE__ */ new Set([e])]]));else{let n=t.get(s);n===void 0?t.set(s,/* @__PURE__ */ new Set([e])):n.add(e)}}}function s(e,t){let n=r.get(t);n===void 0?r.set(t,{descriptions:/* @__PURE__ */ new Set,content:void 0,headers:[],streamContent:/* @__PURE__ */ new Map([[e.contentType,e]])}):n.streamContent===void 0?n.streamContent=/* @__PURE__ */ new Map([[e.contentType,e]]):n.streamContent.set(e.contentType,e)}}function nz(e){return oae(e)??_b(e)}const rz=/*#__PURE__*/ U.annotate({format:`binary`});function iz(e,t){switch(t){case`Uint8Array`:return rz.ast;case`Text`:return kv(e)&&e.encoding===void 0?U.ast:e;case`Multipart`:e=az(e)}return tx(e)}function az(e){return kv(e)&&e.annotations?.representation?.id===`effect/http/PersistedFile`?rz.ast:typeof e?.recur==`function`?e.recur(az):e}const oz=e=>{let t={};switch(KR(e.annotations,NR,e=>{t.description=e}),e._tag){case`Basic`:return{...t,type:`http`,scheme:`basic`};case`Http`:{let n=Sa(e.annotations,LR).pipe(Ui(e=>({bearerFormat:e})),Vi);return{...t,type:`http`,scheme:e.scheme,...n}}case`ApiKey`:return{...t,type:`apiKey`,name:e.key,in:e.in}}},sz=e=>e.type===`http`?{...e,scheme:e.scheme.toLowerCase()}:e.in===`header`?{...e,name:e.name.toLowerCase()}:e,cz=(e,t)=>TM(H(function*(n){let r=yield*Lp(),i=[],a=Array.from(r.mapUnsafe.keys()).filter(e=>e.startsWith(`effect/http-api/HttpApiGroup/`)),o=Object.values(e.groups);for(let e of o){let t=r.mapUnsafe.get(e.key)?.routes;if(t===void 0){let t=a.length===0?`none`:a.join(`, `);return yield*up(`HttpApiGroup "${e.identifier}" not found (key: "${e.key}"). Did you forget to provide HttpApiBuilder.group(api, "${e.identifier}", ...)? Available groups: ${t}`)}i.push(...t)}if(yield*n.addAll(i),t?.openapiPath){let r=Lt(e=>vA(qR(e)));yield*n.add(`GET`,t.openapiPath,I(()=>r(e)))}})),lz=(e,t,n)=>Sf(R(function*(){let r=(yield*Lp()).pipe(Ta(Jd)),i=e.groups[t],a=n(gz(i)),o=Qf(a)?yield*a:a,s=[];for(let t of o.handlers.values())s.push(bz(e,i,t,r));return ra(/* @__PURE__ */ new Map([[i.key,{routes:s,handlers:o.handlers}]]))})),uz=`~effect/http-api/HttpApiBuilder/Handlers`,dz=e=>{switch(e._tag){case`Http`:return V(pM,t=>hg(pz(t.headers.authorization,e.scheme)??``));case`ApiKey`:{let t=e.in===`header`?e.key.toLowerCase():e.key,n=W({[t]:U}),r=e.in===`query`?qce(n):e.in===`cookie`?Gce(n):Kce(n);return Pp(r,{onFailure:()=>hg(``),onSuccess:e=>hg(e[t])})}case`Basic`:{let e={username:``,password:hg(``)};return V(pM,t=>{let n=pz(t.headers.authorization,fz);if(n===void 0)return e;let r=Yee(kh(n));if(r===void 0)return e;let i=r.indexOf(`:`);return i===-1?e:{username:r.slice(0,i),password:hg(r.slice(i+1))}})}}},fz=`Basic`;function pz(e,t){let n=t.length;if(e===void 0||e.length<=n||e.charCodeAt(n)!==32||e.slice(0,n).toLowerCase()!==t.toLowerCase())return;let r=n+1;for(;e.charCodeAt(r)===32;)r++;return r===e.length?void 0:e.slice(r)}const mz=(e,t,n,r,i)=>{if(!Object.hasOwn(e.group.endpoints,t))throw Error(`HttpApiEndpoint "${t}" not found in HttpApiGroup "${e.group.identifier}"`);if(e.handlers.has(t))throw Error(`Handler for HttpApiEndpoint "${t}" is already registered in HttpApiGroup "${e.group.identifier}"`);let a=e.group.endpoints[t];return e.handlers.set(t,{endpoint:a,handler:n,isRaw:r,uninterruptible:i?.uninterruptible??!1}),e},hz={[uz]:uz,pipe(){return Ot(this,arguments)},handle(e,t,n){return mz(this,e,t,!1,n)},handleAll(e){for(let[t,n]of Object.entries(e)){let e=typeof n==`function`?n:n.handler,r=typeof n==`function`?void 0:n.options;mz(this,t,e,!1,r)}return this},handleRaw(e,t,n){return mz(this,e,t,!0,n)}},gz=e=>{let t=Object.create(hz);return t.group=e,t.handlers=/* @__PURE__ */ new Map,t};function _z(e,t){let n=/* @__PURE__ */ new Map;return e.forEach(({encoding:e,schemas:r},i)=>{let a=K(r),o=Nx(e._tag===`FormUrlEncoded`?gC(a):a,t);e._tag===`Multipart`?n.set(i,{_tag:`Multipart`,mode:e.mode,limits:e.limits,decode:o}):n.set(i,{_tag:e._tag,decode:o,nullOnEmpty:r.some(e=>xie(ib(e.ast)))})}),n}function vz(e,t,n){let r=yO(t.method),i=r?kL(t.headers[`content-type`]??`application/json`):`application/x-www-form-urlencoded`,a=e.get(i);if(!a)return gA(`Unsupported content-type: ${i}`,{status:415});let{_tag:o,decode:s}=a;switch(o){case`Multipart`:if(a.mode===`buffered`){let e=Ep(t.multipart);return a.limits&&(e=Bp(e,sM(a.limits))),B(e,s)}return F(a.limits?iE(t.multipartStream,sM(a.limits)):t.multipartStream);case`Json`:return B(Ep(t.text),e=>{if(e===``)return s(a.nullOnEmpty?null:void 0);try{return s(JSON.parse(e))}catch{return z(new kx(new P_({message:`Expected a valid JSON body`})))}});case`Text`:return B(Ep(t.text),s);case`FormUrlEncoded`:{let e=r?V(Ep(t.urlParamsBody),qg):F(n);return B(e,s)}case`Uint8Array`:return B(V(Ep(t.arrayBuffer),e=>new Uint8Array(e)),s)}}function yz(e,t,n,r,i,a){let o=Ca(Ca(e.annotations,t.annotations),n.annotations),s=gR(o),c=Ix(Bz(n,s.headers),s.success),l=Ix(Vz(n,s.headers),s.error),u=YE(n.params,e=>Nx(e,s.params)),d=YE(n.headers,e=>Nx(e,s.headers)),f=YE(n.query,e=>Nx(gC(e),s.query)),p=kz(n,s.success),m=Oz(n,s.success,s.headers),h=n.payload.size>0&&!a?_z(n.payload,s.payload):void 0;return xz(t,n,r,R(function*(){let e=xC().context,r=_a(e,pM),a=_a(e,wM),o=_a(e,mM),s={request:r,endpoint:n,group:t};if(u&&(s.params=yield*bR.wrap(`Params`,u(a.params))),d&&(s.headers=yield*bR.wrap(`Headers`,d(r.headers))),f&&(s.query=yield*bR.wrap(`Query`,f(o))),h){let e=vz(h,r,o);if(dA(e))return e;e!==void 0&&(s.payload=yield*bR.wrap(`Payload`,e))}let l=yield*i(s);if(dA(l))return l;let g;m!==void 0&&pfe(l)&&(g=l.headers,l=l.body);let _=yield*bR.wrap(`Body`,p?.(l,e)??(g===void 0?c(l):m.encodeBody(l)));if(m===void 0||g===void 0)return _;let v=yield*bR.wrap(`ResponseHeaders`,m.encodeHeaders.get(_.status)(g));return wA(_,v)})).pipe(Yre,bp(e=>bR.is(e)?up(e):Ep(l(e))),Bp(r))}function bz(e,t,n,r){let i=n.endpoint;return kM(i.method,kR(i.path,i.params),yz(e,t,i,r,n.handler,n.isRaw),{uninterruptible:n.uninterruptible})}const xz=(e,t,n,r)=>{let i={group:e,endpoint:t};for(let e of t.middlewares){let t=e,a=_a(n,t);r=(CR(t)?Cz(t,a):a)(r,i)}return r},Sz=/*#__PURE__*/ new WeakMap,Cz=(e,t)=>{let n=Sz.get(t);if(n!==void 0)return n;let r=Object.entries(e.security).map(([e,n])=>({decode:dz(n),middleware:t[e]}));if(r.length===0)return M;let i=H(function*(e,t){e=Tp(e,e=>new Tz(e));let n;for(let i=0;i<r.length;i++){let{decode:a,middleware:o}=r[i],s=yield*gp(B(a,n=>o(e,{credential:n,endpoint:t.endpoint,group:t.group})));if(Na(s)){if(Ez(s.failure))return yield*z(s.failure.error);n=s}else return s.success}return yield*pp(n)});return Sz.set(t,i),i},wz=`~effect/http-api/HttpApiBuilder/HandlerError`;var Tz=class{[wz]=wz;error;constructor(e){this.error=e}};const Ez=e=>N(e,wz),Dz=/*#__PURE__*/ Ox(dA);function Oz(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let t of e.success)lL(t)&&(r.set(TL(t),Ix(t.headers,n)),oL(t.schema)||i.push(Lz(t,n)));return r.size===0?void 0:{encodeBody:Ix(i.length===0?qx:i.length===1?i[0]:K(i),t),encodeHeaders:r}}function kz(e,t){let n=Az(e);if(n===void 0)return;let r=n.body,i=jz(e),a=TL(n.schema),o=r.contentType;if(ffe(r))return(e,t)=>WT(e)?F(xA(iE(e,t),{status:a,contentType:o})):i?void 0:new kx(new P_({message:`Expected a streaming response`}));let s=Mz(r,t);return(e,t)=>WT(e)?F(xA(iE(Nz(e,s),t),{status:a,contentType:o})):i?void 0:new kx(new P_({message:`Expected a streaming response`}))}function Az(e){for(let t of e.success){let e=lL(t)?t.schema:t;if(oL(e))return{schema:t,body:e}}}function jz(e){for(let t of e.success){let e=lL(t)?t.schema:t;if(Vx(e)&&!oL(e))return!0}return e.success.size===0}function Mz(e,t){let n=mC(YS(e.error,zS()));return{sseMode:e.sseMode,encodeEvents:Ix(G(e.events),t),encodeCause:Ix(VS(n),t)}}function Nz(e,t){return e.pipe(t.sseMode===`data`?eE(e=>({id:void 0,event:`message`,data:e})):M,Tse(e=>Ep(t.encodeEvents(e))),Ose(e=>bse(Pz(e,t))),eE(Iz),Pse)}function Pz(e,t){return t.encodeCause(e).pipe(Ep,V(e=>({id:void 0,event:Fz,data:e})))}const Fz=`effect/http-api/stream/failure`;function Iz(e){return ufe.write({_tag:`Event`,event:e.event,id:e.id,data:e.data})}const Lz=/*#__PURE__*/ Hz(TL),Rz=/*#__PURE__*/ Hz(OL);function zz(e,t){return lL(e)?Wz({schema:e,status:OL(e),encoding:EL(e),body:e.schema,headers:e.headers,headersOptions:t,toPair:e=>e}):Rz(e,t)}function Bz(e,t){let n=ML(e).map(e=>Lz(e,t));return n.length===1?n[0]:K(n)}function Vz(e,t){let n=NL(e).map(e=>zz(e,t));return n.length===0?qx:n.length===1?n[0]:K(n)}function Hz(e){let t=/* @__PURE__ */ new WeakMap;return(n,r)=>{let i=_L(n.ast);if(i!==void 0)return Wz({schema:Wx(n),status:e(i.body),encoding:CL(i.body.ast),body:i.bodyCodec,headers:i.headersCodec,headersOptions:r,toPair:i.transformation.encode});let a=lL(n)?n:n.ast,o=t.get(a);if(o!==void 0)return o;let s=lL(n)?n.schema:n,c=Dz.pipe(lS(s,Uz(e,n)));return t.set(a,c),c}}function Uz(e,t){let n=lL(t)?t.schema:t;return Sv({decode:(e,t)=>z(new I_({message:`Encode only schema`},e,t)),encode:Gz(e(t),EL(t),hL(n.ast))})}function Wz(e){let t=Ix(e.body),n=Ix(e.headers,e.headersOptions),r=Gz(e.status,e.encoding,hL(e.body.ast)),i=e=>e.issue,a=Sv({decode:(e,t)=>z(new I_({message:`Encode only schema`},e,t)),encode:(a,o)=>{let s=e.toPair(a);return t(s.body,o).pipe(Tp(i),B(e=>r(e,o)),B(e=>V(Tp(n(s.headers),i),t=>wA(e,t))))}});return Dz.pipe(lS(e.schema,a))}function Gz(e,t,n){switch(t._tag){case`Json`:return(r,i)=>{if(r===void 0||n)return F(fA({status:e}));try{let n=JSON.stringify(r);return F(gA(n,{status:e,contentType:t.contentType}))}catch{return z(new P_({expected:`a JSON-serializable response body`},r,i))}};case`Text`:return n=>F(gA(n,{status:e,contentType:t.contentType}));case`Uint8Array`:return n=>F(mA(n,{status:e,contentType:t.contentType}));case`FormUrlEncoded`:return n=>F(yA(n,{status:e}).pipe(SA(`content-type`,t.contentType)))}}const Kz=`~effect/http-api/HttpApiGroup`,qz={[Kz]:Kz,add(...e){let t={...this.endpoints};for(let n of e)dr(t,n.identifier,n);return Yz({...Jz(this),endpoints:t})},prefix(e){return Yz({...Jz(this),endpoints:La(this.endpoints,t=>t.prefix(e))})},middleware(e){return Yz({...Jz(this),endpoints:La(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return Yz({...Jz(this),annotations:Ca(this.annotations,e)})},annotate(e,t){return Yz({...Jz(this),annotations:fa(this.annotations,e,t)})},annotateEndpointsMerge(e){return Yz({...Jz(this),endpoints:La(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return Yz({...Jz(this),endpoints:La(this.endpoints,n=>n.annotate(e,t))})},pipe(){return Ot(this,arguments)}},Jz=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),Yz=e=>{function t(){}return Object.setPrototypeOf(t,qz),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},Xz=(e,t)=>Yz({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:la()}),Zz=`~effect/http-api/HttpApiSecurity`,Qz={[Zz]:Zz,pipe(){return Ot(this,arguments)}},$z=/*#__PURE__*/ (e=>Object.assign(Object.create(Qz),{_tag:`Http`,scheme:e.scheme,schemeLength:e.scheme.length,annotations:la()}))({scheme:`Bearer`}),eB=e=>Object.assign(Object.create(Qz),{_tag:`ApiKey`,key:e.key,in:e.in??`header`,annotations:la()}),tB=/* @__PURE__ */ new Set([`Body`,`ResponseHeaders`]);var nB=class extends wR()(`effect-actions/http/SchemaErrors`,{error:[TI]}){};const rB=()=>ER(nB,e=>z(tB.has(e.kind)?e:TI.fromSchemaError(e.cause))),iB=e=>(e??`/api`).split(`/`).filter(e=>e!==``),aB=e=>`/${e.join(`/`)}`,oB=e=>e.join(`/`)||`/`,sB=(e,t)=>{let n=Xz(e,{topLevel:!0}),[r,...i]=t;return aR(`actions`).annotate(lR,{errors:`all`}).add(r===void 0?n:n.add(r,...i))},cB=(e,t,n)=>eR(e.name,t,{payload:e.input.pipe(pL()),success:e.success,error:n.flatMap(iL)}),lB=(e,t=[])=>t.reduce((e,t)=>e.middleware(t),e);function uB(e,t={}){let n=$de(`ActionHttp binding`,e,t),r=iB(t.prefix),i=n.authentication?.[`~middleware`],a=e.map(e=>{let t=i===void 0||e.caller===SI,a=cB(e,aB([...r,e.name]),Zde(e,n)).annotate(NR,e.description);return t?a:a.middleware(i)}),o=sB(oB(r),a);return{actions:e,...n,prefix:aB(r),api:o}}const dB=e=>df((t,n)=>nie(gf(e,t,n),la())),fB=()=>MM(V(Lp(),e=>{let t=Ta(Jd)(e);return e=>Up(e,e=>Ca(t,e))})).layer;var pB=class extends wR()(`effect-actions/ActionHttp/StepUp`){},mB=class extends wR()(`effect-actions/ActionHttp/JsonContentType`){};const hB=()=>_f(mB,e=>B(pM,t=>t.headers[`content-type`]===void 0?F(gA(`Unsupported content-type: none`,{status:415})):e));function gB(e,t,n={}){let{apps:r,actions:i,authentication:a}=nfe(`HTTP binding`,e,t,n),o=iB(e.prefix),s=oB(o),c=sB(s,i.map(t=>{let r=lB(cB(t,aB([...o,t.name]),II(t,e.error)).middleware(mB).middleware(nB),n.middleware);return t.caller===SI||a===void 0?r:r.middleware(pB).middleware(a[`~middleware`])})).annotate(pR,KI),l=Tf(R(function*(){let e=yield*GI(r),t=a===void 0?yf:yield*V(tL(a),e=>Df(_f(a[`~middleware`],e.middleware),_f(pB,e.stepUp))),i=yield*ep(n.middleware??[],e=>V(Vp(e),t=>_f(e,t))),o=Object.fromEntries(e.map(([e,t])=>[e.name,e=>t(e.payload)]));return lz(c,s,e=>e.handleAll(o)).pipe(Af([rB(),hB(),t,...i]),dB)})).pipe(WI(r));return cz(c).pipe(Af(l),Af(fB()))}const _B=(e,t)=>vA(Rx(mC(e))(t),{status:nL(e.ast)??422}),vB=(e,t)=>{let n=e.flatMap(iL).find(e=>Mx(e)(t));return n===void 0?void 0:_B(n,t)},yB=/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/,bB=(e,t)=>{let n=t.flatMap(([e,t])=>t===void 0?[]:[`${e}="${t.replace(/["\\]/g,`\\$&`)}"`]);return n.length===0?e:`${e} ${n.join(`, `)}`},xB=e=>bB(`Bearer`,e),SB=Mx(Kde),CB=(e,t)=>on(e,`Forbidden`)&&e.scopes!==void 0?xB([[`error`,`insufficient_scope`],[`scope`,e.scopes.join(` `)],[`resource_metadata`,t],[`error_description`,yB.test(e.message)?e.message:void 0]]):void 0,wB={Unauthenticated:EI,Forbidden:OI},TB=e=>_B(wB[e._tag],e),EB=(e,t)=>{let n=TB(e),r=CB(e,t);return r===void 0?n:SA(n,`www-authenticate`,r)};var DB=class extends P()(`effect-actions/SteppedUp`){};const OB=e=>SB(e)&&(!on(e,`Forbidden`)||e.scopes!==void 0),kB=e=>Dp(e,e=>OB(e)?B(Hp(DB),t=>Ii(t)?Hce(t.value,Pi(e)):L):L),AB=(e,t)=>R(function*(){let n=yield*Bce(Ni()),r=yield*_p(Wp(e,DB,n)),i=yield*Vce(n),a=Od(r)&&(sd(r.cause)||cd(r.cause));return Ii(i)&&!a?EB(i.value,t):yield*r}),jB=/^[ \t]*Bearer +(.*[^ \t])[ \t]*$/i,MB=e=>Ui(zi(jB.exec(e??``)?.[1]),e=>hg(e)),NB=e=>{let t=new URL(e.resource),n=new URL(t);return n.pathname=`/.well-known/oauth-protected-resource${t.pathname===`/`?``:t.pathname}`,n},PB=e=>({scope:e?.scopesRequired?.join(` `),metadataUrl:e===void 0?void 0:NB(e).href}),FB=e=>Ii(MB(e)),IB=(e,t)=>xB([[`error`,t?`invalid_token`:void 0],[`scope`,e.scope],[`resource_metadata`,e.metadataUrl]]),LB=(e,t)=>{if(t!==void 0){if(!e)throw Error(`A protected resource is published only for a Bearer scheme`);if(!Qf(t)){for(let e of[`scopesSupported`,`scopesRequired`]){let n=t[e]?.find(e=>!DI.test(e));if(n!==void 0)throw Error(`Invalid scope in ${e}: "${n}"`)}if(new URL(t.resource).href.includes(`#`))throw Error(`A protected resource has no fragment: ${t.resource}`)}}},RB=(e,t)=>wA(e,{...e.headers[`cache-control`]===void 0?{"cache-control":`no-store`}:{},...t!==void 0&&e.status===401&&e.headers[`www-authenticate`]===void 0?{"www-authenticate":t}:{}}),zB=(e,t)=>{let n=t?.authentication,r=n===void 0||UB(n.security);LB(r,t?.protectedResource);let i=PB(t?.protectedResource),a=n!==void 0&&!r?GB(n.security,n.name):IB(i,FB(t?.authorization));if(!SB(e)){let t=vB(n?.error??[],e);if(t===void 0)throw Error(`Not a refusal, nor an error the authentication declares`);return RB(t,a)}return RB(r?EB(e,i.metadataUrl):TB(e),a)},BB=/\.well-known|[\t\n\r]/,VB=e=>{let t=NB(e),n=t.href.slice(t.origin.length),r=vA({resource:e.resource,authorization_servers:e.authorizationServers,bearer_methods_supported:[`header`],scopes_supported:e.scopesSupported,resource_name:e.resourceName},{headers:{"access-control-allow-origin":`*`}}),i=e=>{let t=e.headers[`access-control-request-headers`];return fA({status:204,headers:{"access-control-allow-origin":`*`,"access-control-allow-methods":`GET, HEAD, OPTIONS`,...t===void 0?{}:{"access-control-allow-headers":t,vary:`Access-Control-Request-Headers`}}})};return e=>B(pM,a=>{let o=BB.test(a.url)&&URL.canParse(a.url,t.origin)&&new URL(a.url,t.origin).href.slice(t.origin.length)===n;return o&&(a.method===`GET`||a.method===`HEAD`)?F(r):o&&a.method===`OPTIONS`?F(i(a)):e})},HB=e=>{let t=PB(e);return{metadataUrl:t.metadataUrl,invalid:IB(t,!0),anonymous:IB(t,!1),published:e===void 0?void 0:VB(e)}},UB=e=>on(e,`Http`)&&e.scheme.toLowerCase()===`bearer`,WB=/^[\w.-]+$/,GB=(e,t)=>HE(e).pipe(WE(`Http`,({scheme:e})=>bB(e,[])),WE(`Basic`,()=>bB(`Basic`,[[`realm`,t]])),WE(`ApiKey`,()=>void 0),JE),KB=(e,t,...n)=>{let r=n[0]?.security??$z,i=FI(n[0]?.error);if(!WB.test(e))throw Error(`Invalid authentication name: ${JSON.stringify(e)}, not an OpenAPI key`);if(RI(`Authentication "${e}"`,i),!on(r,`Http`)&&!on(r,`ApiKey`)&&!on(r,`Basic`))throw Error(`Authentication takes one native HttpApiSecurity scheme`);return{name:e,identity:t,security:r,error:i,"~provider":P(`effect-actions/Authentication/Provider/${e}`),"~middleware":wR()(`effect-actions/Authentication/Security/${e}`,{security:{[e]:r}}),"~verified":P(`effect-actions/Authentication/Verified/${e}`)}},qB=e=>mg(e)?_g(e)!==``:e.username!==``||_g(e.password)!==``;function JB(e,t,n={}){let{security:r}=e,i=UB(r),a=n.protectedResource;LB(i,a);let o=Qf(a)?V(a,e=>(LB(i,e),HB(e))):F(HB(a)),s=new EI({message:i?`A bearer token is required.`:`A credential is required.`});return bf(e[`~provider`],R(function*(){let{metadataUrl:n,invalid:a,anonymous:c,published:l}=yield*o;l!==void 0&&(yield*(yield*CM).addGlobalMiddleware(l));let u=Qf(t)?yield*t:t;if(!Jt(u))return yield*up(/* @__PURE__ */ Error(`Missing verify: pass a verify function, or an Effect building one`));let d=e=>qB(e)?u(e):z(s),f=rle((e,t)=>F(SA(t,`cache-control`,`no-store`))),p=t=>i?qB(t)?a:c:GB(r,e.name),m=t=>SB(t)?F(i?EB(t,n):TB(t)):ap(()=>{let n=vB(e.error,t);return n===void 0?up(t):F(n)}),h=(e,t,n)=>{let r=p(e);return Ip(d(e),{onFailure:m,onSuccess:e=>Wp(t,n,e)}).pipe(Xp(()=>f),ile((e,t)=>F(RB(t,r))))};return{descriptor:e,authenticate:d,middleware:{[e.name]:(t,{credential:n})=>h(n,t,e.identity)},stepUp:e=>i?wp(e,OB,e=>F(EB(e,n))):e,http:((t,a)=>B(dz(r),r=>a&&!qB(r)?t:h(r,i?AB(t,n):t,e[`~verified`]))),route:(t=>B(dz(r),n=>h(n,wp(t,SB,m),e.identity)))}}))}var YB=class e extends fC()(`InternalServerError`,{message:U},{httpApiStatus:500}){cause;static of=t=>{let n=new e({message:`Request could not be completed`});return n.cause=t,n}},XB=class extends fC()(`ServiceUnavailable`,{message:U},{httpApiStatus:503}){},ZB=class e extends fC()(`ClientNotFound`,{clientId:U,message:U},{httpApiStatus:404}){static of=t=>new e({clientId:t,message:`No client ${t} is registered`})},QB=class e extends fC()(`ResourceNotFound`,{identifier:U,message:U},{httpApiStatus:404}){static of=t=>new e({identifier:t,message:`No resource ${t} exists`})},$B=class e extends fC()(`ApiKeyNotFound`,{keyId:U,message:U},{httpApiStatus:404}){static of=t=>new e({keyId:t,message:`No API key ${t} exists`})},eV=class e extends fC()(`ClientIsAutomatic`,{clientId:U,message:U},{httpApiStatus:409}){static of=t=>new e({clientId:t,message:`Client ${t} registered itself; revoke, block or delete it instead`})},tV=class e extends fC()(`OwnerExists`,{message:U},{httpApiStatus:409}){static of=()=>new e({message:`Setup already completed`})},nV=class extends fC()(`ProviderRefused`,{message:U},{httpApiStatus:400}){},rV=class extends fC()(`UnreadableRequest`,{message:U},{httpApiStatus:400}){};const iV=[XB,YB];var aV=class extends P()(`clankerauth/CurrentOwner`){};const oV=e=>KB(`clankerauth.OwnerSession`,aV,{security:eB({in:`cookie`,key:e}),error:iV}),sV=oV(`better-auth.session_token`),cV=KB(`clankerauth.OwnerToken`,aV,{error:iV}),lV=e=>new URL(`/`,e).href,uV={read:`clankerauth:read`,write:`clankerauth:write`},dV=`Passwords have 8 to 128 characters`,fV=W({email:U.check(SS(/\S/u,{message:`Setup requires an email`})),password:U.check(jS(8,{message:dV}),NS(128,{message:dV}))}),pV=oS([`none`,`client_secret_basic`,`client_secret_post`]),mV=oS([`web`,`native`]),hV=G(U).check(FS({message:`Choose unique Resources`})),gV=W({client_name:U,redirect_uris:G(U),resources:hV,token_endpoint_auth_method:pV,application_type:mV}),_V=W({client_id:U,client_name:U,redirect_uris:G(U),application_type:mV}),vV=W({client_id:U}),yV=W({client_id:U,resource:Ux(U)}),bV=W({client_id:U,blocked:Zx}),xV=W({onboarding:Ux(oS([`managed`,`dcr`,`cimd`])),blocked:Ux(Zx),client_id:U,client_name:Ux(U),redirect_uris:G(U),token_endpoint_auth_method:Ux(U),application_type:Ux(sS(U)),scope:Ux(U),grant_types:Ux(G(U))}),SV=xV.pipe(eS({client_secret:Ux(U),client_secret_expires_at:Ux(Xx)})),CV=W({identifier:U,name:U,scopes:G(U)}),wV=CV.pipe(eS({builtIn:Zx})),TV=W({identifier:U,name:U.check(SS(/\S/u,{message:`Resources require a name`})),scopes:G(U.check(SS(/^\s*[\x21\x23-\x5B\x5D-\x7E]+\s*$/u,{message:`Resources require well-formed custom scopes`})))}),EV=W({identifier:U}),DV=W({resource:CV,created:Zx}),OV=W({client_id:U,resource:U}),kV=W({client_id:U,resources:hV}),AV=W({clientAccess:G(OV)}),jV=tS(U,G(U)),MV=tS(U,G(U).check(jS(1,{message:`Select explicitly granted, currently available Resource scopes`}),FS({message:`Select explicitly granted, currently available Resource scopes`}))).check(Eoe(1,{message:`Select at least one Resource and scope`})),NV=U.check(NS(100,{message:`Key names require 1–100 characters`}),SS(/\S/u,{message:`Key names require 1–100 characters`})),PV=eC,FV=W({client_id:U,resource:U,scopes:G(U),approvedAt:sS(PV),refreshedAt:sS(PV)}),IV=W({name:NV,permissions:MV,expiresAt:sS(PV)}),LV=W({keyId:U}),RV=W({keyId:U,name:Ux(NV),permissions:Ux(MV),enabled:Ux(Zx)}),zV=W({keyId:U,name:U,enabled:Zx,permissions:jV,expiresAt:sS(PV),createdAt:PV}),BV={caller:SI},VV={caller:aV},HV=[QI(`setupStatus`,{description:`Check whether the issuer needs its first owner account.`,readOnly:!0,...BV,error:[YB],success:W({required:Zx})}),QI(`setupOwner`,{description:`Create the first owner account.`,readOnly:!1,...BV,error:[tV,nV,YB],input:fV,success:W({created:Zx}).pipe(aL(201))}),QI(`keyList`,{description:`The signed list a resource server verifies API keys against: one sealed entry per key granted on the resource, readable only with that key.`,readOnly:!0,...BV,error:[YB],input:W({resource:U}),success:W({list:U})})],UV=W({clients:G(xV),resources:G(wV),clientAccess:G(OV),connections:G(FV),email:U,issuer:U}),WV=[QI(`listClients`,{description:`List clients, resources, managed clients' resource access (what they may obtain), and every client's connections (what it holds).`,readOnly:!0,...VV,error:[YB],success:UV}),QI(`createClient`,{description:`Register a first-party OAuth client. Returns its secret once when confidential.`,readOnly:!1,...VV,error:[nV,YB],input:gV,success:SV.pipe(aL(201))}),QI(`updateClient`,{description:`Rename a first-party client or change its redirect URIs and application type.`,readOnly:!1,...VV,error:[ZB,eV,nV,YB],input:_V,success:xV}),QI(`deleteClient`,{description:`Delete a client and its stored authorization. An automatic client can register again; block it to keep it out.`,readOnly:!1,...VV,error:[ZB,YB],input:vV,success:W({deleted:Zx})}),QI(`revokeClient`,{description:`Revoke a client’s stored authorization, for one resource or all. It must authorize again; an automatic client asks for consent.`,readOnly:!1,...VV,error:[ZB,YB],input:yV,success:W({revoked:Zx})}),QI(`blockClient`,{description:`Block or unblock OAuth authorization for a client.`,readOnly:!1,...VV,error:[ZB,YB],input:bV,success:W({blocked:Zx})}),QI(`rotateClientSecret`,{description:`Rotate a confidential client secret. Returns the new secret once.`,readOnly:!1,...VV,error:[ZB,eV,nV,YB],input:vV,success:SV}),QI(`setClientAccess`,{description:`Set the resources a managed client may obtain. Removing one revokes its authorization for it. Automatic clients may ask for any resource with consent.`,readOnly:!1,...VV,error:[ZB,eV,YB],input:kV,success:AV}),QI(`getResource`,{description:`Get one resource and its scopes by identifier.`,readOnly:!0,...VV,error:[QB,YB],input:EV,success:wV}),QI(`putResource`,{description:`Create an OAuth resource, or update the one with its identifier, to exactly these name and scopes.`,readOnly:!1,...VV,error:[nV,YB],input:TV,success:DV}),QI(`deleteResource`,{description:`Delete a resource, its client access and every client’s authorization for it. API-key permissions are retained; recreating the resource restores them.`,readOnly:!1,...VV,error:[QB,YB],input:EV,success:W({deleted:Zx})}),QI(`listApiKeys`,{description:`List API key metadata without secret values.`,readOnly:!0,...VV,error:[YB],success:W({keys:G(zV)})}),QI(`createApiKey`,{description:`Create a scoped API key. Returns its secret once.`,readOnly:!1,...VV,error:[nV,YB],input:IV,success:zV.pipe(eS({key:U}),aL(201))}),QI(`updateApiKey`,{description:`Update an API key’s name, permissions or enabled state.`,readOnly:!1,...VV,error:[$B,nV,YB],input:RV,success:zV}),QI(`deleteApiKey`,{description:`Delete an API key.`,readOnly:!1,...VV,error:[$B,YB],input:LV,success:W({deleted:Zx})})],GV=[.../* @__PURE__ */ new Set([...[...HV,...WV].flatMap(e=>e.error),...iV,rV])],KV=e=>uB([...WV,...HV],{authentication:e});KV(sV);const qV=uB(WV,{prefix:`/api/owner`,authentication:cV});var JV=/* @__PURE__ */ e({NodeSqliteDialect:()=>eH}),YV=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},XV=class{#e;#t=new QV;#n;#r;constructor(e){this.#e={...e}}async init(){this.#n=this.#e.database,this.#r=new ZV(this.#n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#r)}async acquireConnection(){return await this.#t.lock(),this.#r}async beginTransaction(e){await e.executeQuery(d.raw(`begin`))}async commitTransaction(e){await e.executeQuery(d.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(d.raw(`rollback`))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#n?.close()}},ZV=class{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t),i=n;if(r.columns().length>0)return Promise.resolve({rows:r.all(...i)});let{changes:a,lastInsertRowid:o}=r.run(...i);return Promise.resolve({rows:[],numAffectedRows:BigInt(a),insertId:typeof o==`bigint`?o:BigInt(o)})}async*streamQuery(){throw Error(`Streaming query is not supported by SQLite driver.`)}},QV=class{#e;#t;async lock(){for(;this.#e!==void 0;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},$V=class extends r{getCurrentParameterPlaceholder(){return`?`}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}},eH=class{#e;constructor(e){this.#e={...e}}createDriver(){return new XV(this.#e)}createQueryCompiler(){return new $V}createAdapter(){return new YV}createIntrospector(e){return n(e)}};const tH=e=>{let t=Nx(e);return e=>Tp(t(e),YB.of)};function nH(e){return(n,...r)=>rp({try:async()=>(await t(n,...r).execute(e)).rows,catch:YB.of})}const rH=ym(`Database.transaction`)(function*(e,t){let n=yield*rp({try:()=>e.startTransaction().execute(),catch:YB.of}),r=yield*_p(t(nH(n))),i=kp(rp({try:()=>n.rollback().execute(),catch:YB.of})),a=rp({try:()=>n.commit().execute(),catch:YB.of}).pipe(Dp(()=>i));return yield*Dd(r)?a:i,yield*r},rm);async function iH(e){let n=new Et(e);try{n.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`);let e=new i({dialect:new eH({database:n})});return await t`SELECT 1`.execute(e),{kysely:e,sql:nH(e),close:()=>e.destroy()}}catch(e){throw n.close(),e}}var aH=class e extends P()(`clankerauth/Database`){static layer=t=>bf(e,R(function*(){yield*dp(()=>bt(at(t),{recursive:!0,mode:448}));let e=yield*qp(rp(()=>iH(t)),e=>np(()=>e.close()));return{kysely:e.kysely,sql:e.sql,transaction:t=>rH(e.kysely,t)}}))};let oH,sH=!1;function cH(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function lH(){if(oH)return oH;let e=cH();if(e)return oH??=e,oH;try{let{AsyncLocalStorage:e}=await import(
26
+ /* @vite-ignore */
27
+ /* webpackIgnore: true */
28
+ `node:async_hooks`);return oH??=e,oH}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return oH??=t,oH;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(sH||(sH=!0,console.warn(`[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.`),console.warn(`[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler`),console.warn(`[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag`)),e)}}const uH=()=>v().context.endpointContextAsyncStorage,dH=async()=>{let e=uH();if(e)return e;let t=await lH(),n=v().context;return n.endpointContextAsyncStorage??=new t};function fH(){return x()}function pH(){let e=fH();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function mH(e,t){return(await dH()).run(e,t)}const hH=async()=>{let e=v(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await lH();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function gH(){return(await hH()).getStore()!==void 0}async function _H(){let e=(await hH()).getStore();if(!e)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return e}async function vH(e,t){return(await hH()).run(e,t)}function yH(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await _H();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await _H()).set(t,e)}}}function bH(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}const Y=bH({USER_NOT_FOUND:`User not found`,FAILED_TO_CREATE_USER:`Failed to create user`,FAILED_TO_CREATE_SESSION:`Failed to create session`,FAILED_TO_UPDATE_USER:`Failed to update user`,FAILED_TO_GET_SESSION:`Failed to get session`,INVALID_PASSWORD:`Invalid password`,INVALID_EMAIL:`Invalid email`,INVALID_EMAIL_OR_PASSWORD:`Invalid email or password`,INVALID_USER:`Invalid user`,SOCIAL_ACCOUNT_ALREADY_LINKED:`Social account already linked`,PROVIDER_NOT_FOUND:`Provider not found`,INVALID_TOKEN:`Invalid token`,TOKEN_EXPIRED:`Token expired`,ID_TOKEN_NOT_SUPPORTED:`id_token not supported`,FAILED_TO_GET_USER_INFO:`Failed to get user info`,USER_EMAIL_NOT_FOUND:`User email not found`,EMAIL_NOT_VERIFIED:`Email not verified`,PASSWORD_TOO_SHORT:`Password too short`,PASSWORD_TOO_LONG:`Password too long`,USER_ALREADY_EXISTS:`User already exists.`,USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:`User already exists. Use another email.`,EMAIL_CAN_NOT_BE_UPDATED:`Email can not be updated`,CHANGE_EMAIL_DISABLED:`Change email is disabled`,CREDENTIAL_ACCOUNT_NOT_FOUND:`Credential account not found`,SESSION_EXPIRED:`Session expired. Re-authenticate to perform this action.`,FAILED_TO_UNLINK_LAST_ACCOUNT:`You can't unlink your last account`,ACCOUNT_NOT_FOUND:`Account not found`,USER_ALREADY_HAS_PASSWORD:`User already has a password. Provide that to delete the account.`,CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:`Cross-site navigation login blocked. This request appears to be a CSRF attack.`,VERIFICATION_EMAIL_NOT_ENABLED:`Verification email isn't enabled`,EMAIL_ALREADY_VERIFIED:`Email is already verified`,EMAIL_MISMATCH:`Email mismatch`,SESSION_NOT_FRESH:`Session is not fresh`,LINKED_ACCOUNT_ALREADY_EXISTS:`Linked account already exists`,INVALID_ORIGIN:`Invalid origin`,INVALID_CALLBACK_URL:`Invalid callbackURL`,INVALID_REDIRECT_URL:`Invalid redirectURL`,INVALID_ERROR_CALLBACK_URL:`Invalid errorCallbackURL`,INVALID_NEW_USER_CALLBACK_URL:`Invalid newUserCallbackURL`,MISSING_OR_NULL_ORIGIN:`Missing or null Origin`,CALLBACK_URL_REQUIRED:`callbackURL is required`,FAILED_TO_CREATE_VERIFICATION:`Unable to create verification`,FIELD_NOT_ALLOWED:`Field not allowed to be set`,ASYNC_VALIDATION_NOT_SUPPORTED:`Async validation is not supported`,VALIDATION_ERROR:`Validation Error`,MISSING_FIELD:`Field is required`,METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:`POST method requires deferSessionRefresh to be enabled in session config`,BODY_MUST_BE_AN_OBJECT:`Body must be an object`,PASSWORD_ALREADY_SET:`User already has a password set`}),xH=async()=>{let e=v(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await lH();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},SH=async e=>xH().then(t=>t.getStore()?.adapter||e).catch(()=>e),CH=async(e,t)=>{let n=!1;return xH().then(async r=>{n=!0;let i=[],a,o,s=!1;try{a=await r.run({adapter:e,pendingHooks:i,isTransactionActive:!1},t)}catch(e){o=e,s=!0}for(let e of i)await e();if(s)throw o;return a}).catch(e=>{if(!n)return t();throw e})},wH=async(e,t,n)=>{let r=!1;return xH().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=Ze(e)?.();a&&await a;let o=[],s,c,l=!1;try{s=await e.transaction(async e=>(o=[],i.run({adapter:e,pendingHooks:o,isTransactionActive:!0},t)))}catch(e){l=!0,c=e}let u=async e=>{for(let t of o)try{await t()}catch(t){if(!n?.onAfterCommitHookError){if(e===`throw`)throw t;try{f.error(`Failed to run an after-commit hook for work that could not roll back`,t)}catch{}continue}try{await n.onAfterCommitHookError(t)}catch{}}};if(l)throw e.options?.adapterConfig.transaction===!1&&await u(`log`),c;return await u(`throw`),s}).catch(e=>{if(!r)return t();throw e})},TH=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await xH()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)};function EH(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function DH(e){let t=``;for(let n=0;n<e.length;n++)t+=EH(e[n]);return t}function OH(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${OH(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=DH(n),r.length>1?(r=`(?:${r})`,i=`((?!${r}).)`):i=`[^${r}]`);let a=t?`${r}+?`:``,o=t?`${r}*?`:``,s=t?e.split(n):[e],c=``;for(let e=0;e<s.length;e++){let n=s[e],r=s[e+1],l=``;if(!(!n&&e>0)){if(t&&(l=e===s.length-1?o:r===`**`?``:a),t&&n===`**`)l&&(c+=e===0?``:l,c+=`(?:${i}*?${l})*?`);else{for(let e=0;e<n.length;e++){let t=n[e];t===`\\`?e<n.length-1&&(c+=EH(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:EH(t)}c+=l}}}return c}function kH(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function AH(e,t){if(typeof e!=`string`&&!Array.isArray(e))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof e} given`);if((typeof t==`string`||typeof t==`boolean`)&&(t={separator:t}),arguments.length===2&&!(t===void 0||typeof t==`object`&&t&&!Array.isArray(t)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof t} given`);if(t||={},t.separator===`\\`)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let n=OH(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=kH.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}function jH(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function MH(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}function NH(e){try{return(MH(new URL(e).pathname)||`/`)!==`/`}catch{throw new D(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function PH(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new D(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof D?t:new D(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function FH(e,t=`/api/auth`){if(PH(e),NH(e))return e;let n=MH(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function IH(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function LH(e,t,n,r,i){if(e)return FH(e,t);if(r!==!1){let e=C.BETTER_AUTH_URL||C.NEXT_PUBLIC_BETTER_AUTH_URL||C.PUBLIC_BETTER_AUTH_URL||C.NUXT_PUBLIC_BETTER_AUTH_URL||C.NUXT_PUBLIC_AUTH_URL||(C.BASE_URL===`/`?void 0:C.BASE_URL);if(e)return FH(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&IH(o,`proto`)&&IH(a,`host`))try{return FH(`${o}://${a}`,t)}catch{}if(n){let e=RH(n.url);if(!e)throw new D(`Could not get origin from request. Please provide a valid base URL.`);return FH(e,t)}if(typeof window<`u`&&window.location)return FH(window.location.origin,t)}function RH(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function zH(e){try{return new URL(e).protocol}catch{return null}}function BH(e){try{return new URL(e).host}catch{return null}}function VH(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function HH(e){if(e instanceof Request)return!0;if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Request]`)return!1;let t=e;return typeof t.url==`string`&&typeof t.headers==`object`&&t.headers!==null&&typeof t.headers.get==`function`}function UH(e,t){let n=HH(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&IH(e,`host`))return e}let r=n.get(`host`);if(r&&IH(r,`host`))return r;if(HH(e))try{return new URL(e.url).host}catch{return null}return null}function WH(e,t,n){if(t===`http`||t===`https`)return t;let r=HH(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&IH(e,`proto`))return e}if(HH(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=UH(e,n);return i&&jH(i)?`http`:`https`}const GH=(e,t)=>{if(!e||!t)return!1;let n=e.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase(),r=t.replace(/^https?:\/\//,``).split(`/`)[0].toLowerCase();return r.includes(`*`)||r.includes(`?`)?AH(r)(n):n.toLowerCase()===r.toLowerCase()};function KH(e,t,n,r){let i=UH(t,r);if(!i){if(e.fallback)return FH(e.fallback,n);throw new D(`Could not determine host from request headers. Please provide a fallback URL in your baseURL config.`)}if(e.allowedHosts.some(e=>GH(i,e)))return FH(`${WH(t,e.protocol,r)}://${i}`,n);if(e.fallback)return FH(e.fallback,n);throw new D(`Host "${i}" is not in the allowed hosts list. Allowed hosts: ${e.allowedHosts.join(`, `)}. Add this host to your allowedHosts config or provide a fallback URL.`)}function qH(e,t,n,r,i){if(VH(e))return n?KH(e,n,t,i):e.fallback?FH(e.fallback,t):LH(void 0,t,void 0,r,i);let a=HH(n)?n:void 0;return LH(typeof e==`string`?e:void 0,t,a,r,i)}const JH=h(`a-z`,`0-9`,`A-Z`,`-_`);var YH=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ae(e),fe(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Ce(r)}update(e){return de(this),this.iHash.update(e),this}digestInto(e){de(this),we(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const XH=/* @__PURE__ */ (()=>{let e=((e,t,n)=>new YH(e,t).update(n).digest());return e.create=(e,t)=>new YH(e,t),e})(),ZH=/* @__PURE__ */ Uint8Array.of(0),QH=/* @__PURE__ */ Uint8Array.of();function $H(e,t,n,r=32,i){ae(e),eee(r,`length`),fe(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=QH:fe(n,void 0,`info`),!o)return i&&Ce(t),/* @__PURE__ */ new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=XH.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){ZH[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(ZH).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(ZH[0]=o,o>1&&c.update(u),c.update(n).update(ZH).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&Ce(u),Ce(ZH),r===s.length)return s;let f=s.slice(0,r);return Ce(s),f}const eU=(e,t,n,r,i)=>{ae(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=XH.create(e,n).update(t);return $H(e,a.digest(),r,i,a)},tU=e=>e/2**32|0,nU=e=>e>>>0;function rU(e,t,n,r){let i=tU(n),a=nU(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function iU(e,t,n){return e&t^~e&n}function aU(e,t,n){return e&t^e&n^t&n}var oU=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=m(this.buffer)}update(e){de(this),fe(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=m(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0}else n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){de(this),we(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),rU(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:m(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const sU=/* @__PURE__ */ Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cU=/* @__PURE__ */ Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lU=/* @__PURE__ */ new Uint32Array(64);var uU=class extends oU{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)lU[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=lU[e-15],n=lU[e-2],r=w(t,7)^w(t,18)^t>>>3,i=w(n,17)^w(n,19)^n>>>10;lU[e]=i+lU[e-7]+r+lU[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=w(o,6)^w(o,11)^w(o,25),u=l+t+iU(o,s,c)+cU[e]+lU[e]|0,d=(w(n,2)^w(n,13)^w(n,22))+aU(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){Ce(lU)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ce(this.buffer)}},dU=class extends uU{constructor(){super(32,sU)}};const fU=/* @__PURE__ */ ne(()=>new dU,/* @__PURE__ */ tee(1));async function pU(e,t,n=3600){return await new iI(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function mU(e,t){try{return(await nI(e,new TextEncoder().encode(t))).payload}catch{return null}}const hU=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),gU=()=>Date.now()/1e3|0,_U=`A256CBC-HS512`;function vU(e,t){return eU(fU,new TextEncoder().encode(e),new TextEncoder().encode(t),hU,64)}function yU(e){if(typeof e==`string`)return e;let t=e.keys.get(e.currentVersion);if(!t)throw Error(`Secret version ${e.currentVersion} not found in keys`);return t}function bU(e){if(typeof e==`string`)return[{version:0,value:e}];let t=[];for(let[n,r]of e.keys)t.push({version:n,value:r});return e.legacySecret&&!t.some(t=>t.value===e.legacySecret)&&t.push({version:-1,value:e.legacySecret}),t}async function xU(e,t,n,r=3600){let i=vU(yU(t),n),a=await lI({kty:`oct`,k:_P(i)},`sha256`);return await new Ade(e).setProtectedHeader({alg:`dir`,enc:_U,kid:a}).setIssuedAt().setExpirationTime(gU()+r).setJti(crypto.randomUUID()).encrypt(i)}const SU={clockTolerance:15,keyManagementAlgorithms:[`dir`],contentEncryptionAlgorithms:[_U,`A256GCM`]};async function CU(e,t,n){if(!e)return null;let r=!1;try{r=gI(e).kid!==void 0}catch{return null}try{let r=bU(t),{payload:i}=await rI(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=vU(e.value,n);if(t===await lI({kty:`oct`,k:_P(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,vU(r[0].value,n)},SU);return i}catch{if(r)return null;let i=bU(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await rI(e,vU(r.value,n),SU);return a}catch{continue}return null}}function wU(e,t){typeof e==`string`&&(e=new TextEncoder().encode(e)),typeof t==`string`&&(t=new TextEncoder().encode(t));let n=new Uint8Array(e),r=new Uint8Array(t),i=n.length^r.length,a=Math.max(n.length,r.length);for(let e=0;e<a;e++)i|=(e<n.length?n[e]:0)^(e<r.length?r[e]:0);return i===0}const TU={N:16384,r:16,p:1,dkLen:64};function EU(e,t){return new Promise((n,r)=>{nt(e.normalize(`NFKC`),t,TU.dkLen,{N:TU.N,r:TU.r,p:TU.p,maxmem:128*TU.N*TU.r*2},(e,t)=>{e?r(e):n(t)})})}async function DU(e){let t=tt(16).toString(`hex`);return`${t}:${(await EU(e,t)).toString(`hex`)}`}async function OU(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await EU(t,n)).toString(`hex`)===r}const kU=DU,AU=async({hash:e,password:t})=>OU(e,t);function jU(){let e=typeof globalThis<`u`&&globalThis.crypto;if(e&&typeof e.subtle==`object`&&e.subtle!=null)return e.subtle;throw Error(`crypto.subtle must be defined`)}function MU(e,t){return{digest:async n=>{let r=_e(n),i=await jU().digest(e,r);return t===`hex`?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``):t===`base64`||t===`base64url`||t===`base64urlnopad`?t.includes(`url`)?ye.encode(i,{padding:t!==`base64urlnopad`}):ue.encode(i):i}}}
29
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
30
+ function NU(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const PU=e=>e?`"${e}" `:``;function FU(e,t=``){if(typeof e!=`boolean`)throw TypeError(PU(t)+`expected boolean, got type=`+typeof e);return e}function IU(e,t=``){if(typeof e!=`number`)throw TypeError(PU(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(PU(t)+`expected integer >= 0, got `+e);return e}function LU(e,t,n=``){if(NU(e)&&(t===void 0||e.length===t))return e;t!==void 0&&IU(t,`length`);let r=NU(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=PU(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const RU=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function zU(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function BU(e,t){LU(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function VU(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function HU(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function UU(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const WU=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function GU(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function KU(e){for(let t=0;t<e.length;t++)e[t]=GU(e[t]);return e}const qU=WU?e=>e:KU,JU=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,YU=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function XU(e){if(LU(e),JU)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=YU[e[n]];return t}function ZU(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function QU(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(JU)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=ZU(e.charCodeAt(i)),a=ZU(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function $U(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function eW(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function tW(e,t){if(eW(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function nW(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];LU(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function rW(e,t){return RU(e,`defaults`),RU(t,`opts`),Object.assign(e,t)}function iW(e,t){if(e=LU(e),t=LU(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function aW(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(/* @__PURE__ */ new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}const oW=(e,t)=>{function n(n,...r){if(LU(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];LU(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(NU(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&LU(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);LU(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,LU(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(LU(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function sW(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(LU(t,e,`output`),n&&!lW(t))throw Error(`invalid output, must be aligned`);return t}function cW(e,t,n){IU(e),IU(t),FU(n);let r=/* @__PURE__ */ new Uint8Array(16),i=UU(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function lW(e){return e.byteOffset%4==0}function uW(e){return Uint8Array.from(LU(e))}function dW(e=32){IU(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}function fW(e,t=dW){if(typeof e!=`function`)throw TypeError(`"fn" expected cipher constructor, got type=`+typeof e);if(typeof t!=`function`)throw TypeError(`"randomBytes_" expected function, got type=`+typeof t);let{nonceLength:n}=e;IU(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=nW(e,t);return eW(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){LU(o,void 0,`data`);let s=t(n),c=e(i,s,...a).encrypt(o);return c instanceof Promise?c.then(e=>r(s,e,o)):r(s,c,o)},decrypt(t){LU(t,void 0,`data`);let r=t.subarray(0,n),o=t.subarray(n);return e(i,r,...a).decrypt(o)}}));return`blockSize`in e&&(i.blockSize=e.blockSize),`tagLength`in e&&(i.tagLength=e.tagLength),`withAAD`in e&&(i.withAAD=e.withAAD),i}const pW=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),mW=/* @__PURE__ */ qU(VU(pW(`expand 16-byte k`))),hW=/* @__PURE__ */ qU(VU(pW(`expand 32-byte k`)));function gW(e,t){return e<<t|e>>>32-t}const _W=2**32-1,vW=/* @__PURE__ */ Uint32Array.of();function yW(e,t,n,r,i,a,o,s){let c=i.length,l=/* @__PURE__ */ new Uint8Array(64),u=VU(l),d=WU&&lW(i)&&lW(a),f=d?VU(i):vW,p=d?VU(a):vW;if(WU)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=_W)throw Error(`arx: counter overflow`);let h=Math.min(64,c-m);if(d&&h===64){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<16;t++)n=e+t,p[n]=f[n]^u[t];m+=64}else{for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}else for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),qU(u),o>=_W)throw Error(`arx: counter overflow`);let f=Math.min(64,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}}function bW(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=rW({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return IU(i),IU(o),FU(a),FU(n),(t,s,c,l,u=0)=>{LU(t,void 0,`key`),LU(s,void 0,`nonce`),LU(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=sW(d,l,!1),f&&tW(c,l),IU(u),u<0||u>=_W)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=uW(t)),g=hW;else if(m===16&&n)h=/* @__PURE__ */ new Uint8Array(32),h.set(t),h.set(t,16),g=mW,p.push(h);else throw LU(t,32,`arx key`),Error(`invalid key size`);(!WU||!lW(s))&&p.push(s=uW(s));let _=VU(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(WU)r(g,_,VU(e),_);else{let t=qU(Uint32Array.from(g));r(t,_,VU(e),_),HU(t),qU(_)}s=s.subarray(16)}else WU||qU(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=/* @__PURE__ */ new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=qU(VU(s));try{return yW(e,g,_,y,c,l,u,o),l}finally{HU(...p)}}}function xW(e,t){return e[t++]&255|(e[t++]&255)<<8}var SW=class{blockLen=16;outputLen=16;buffer=/* @__PURE__ */ new Uint8Array(16);r=/* @__PURE__ */ new Uint16Array(10);h=/* @__PURE__ */ new Uint16Array(10);pad=/* @__PURE__ */ new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=uW(LU(e,32,`key`));let t=xW(e,0),n=xW(e,2),r=xW(e,4),i=xW(e,6),a=xW(e,8),o=xW(e,10),s=xW(e,12),c=xW(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=xW(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=xW(e,t+0),_=xW(e,t+2),v=xW(e,t+4),y=xW(e,t+6),b=xW(e,t+8),x=xW(e,t+10),S=xW(e,t+12),ee=xW(e,t+14),C=i[0]+(g&8191),te=i[1]+((g>>>13|_<<3)&8191),ne=i[2]+((_>>>10|v<<6)&8191),w=i[3]+((v>>>7|y<<9)&8191),T=i[4]+((y>>>4|b<<12)&8191),re=i[5]+(b>>>1&8191),ie=i[6]+((b>>>14|x<<2)&8191),ae=i[7]+((x>>>11|S<<5)&8191),oe=i[8]+((S>>>8|ee<<8)&8191),se=i[9]+(ee>>>5|r),ce=0,le=ce+C*o+5*h*te+5*m*ne+5*p*w+5*f*T;ce=le>>>13,le&=8191,le+=5*d*re+5*u*ie+5*l*ae+5*c*oe+5*s*se,ce+=le>>>13,le&=8191;let ue=ce+C*s+te*o+5*h*ne+5*m*w+5*p*T;ce=ue>>>13,ue&=8191,ue+=5*f*re+5*d*ie+5*u*ae+5*l*oe+5*c*se,ce+=ue>>>13,ue&=8191;let de=ce+C*c+te*s+ne*o+5*h*w+5*m*T;ce=de>>>13,de&=8191,de+=5*p*re+5*f*ie+5*d*ae+5*u*oe+5*l*se,ce+=de>>>13,de&=8191;let fe=ce+C*l+te*c+ne*s+w*o+5*h*T;ce=fe>>>13,fe&=8191,fe+=5*m*re+5*p*ie+5*f*ae+5*d*oe+5*u*se,ce+=fe>>>13,fe&=8191;let pe=ce+C*u+te*l+ne*c+w*s+T*o;ce=pe>>>13,pe&=8191,pe+=5*h*re+5*m*ie+5*p*ae+5*f*oe+5*d*se,ce+=pe>>>13,pe&=8191;let me=ce+C*d+te*u+ne*l+w*c+T*s;ce=me>>>13,me&=8191,me+=re*o+5*h*ie+5*m*ae+5*p*oe+5*f*se,ce+=me>>>13,me&=8191;let he=ce+C*f+te*d+ne*u+w*l+T*c;ce=he>>>13,he&=8191,he+=re*s+ie*o+5*h*ae+5*m*oe+5*p*se,ce+=he>>>13,he&=8191;let ge=ce+C*p+te*f+ne*d+w*u+T*l;ce=ge>>>13,ge&=8191,ge+=re*c+ie*s+ae*o+5*h*oe+5*m*se,ce+=ge>>>13,ge&=8191;let _e=ce+C*m+te*p+ne*f+w*d+T*u;ce=_e>>>13,_e&=8191,_e+=re*l+ie*c+ae*s+oe*o+5*h*se,ce+=_e>>>13,_e&=8191;let ve=ce+C*h+te*m+ne*p+w*f+T*d;ce=ve>>>13,ve&=8191,ve+=re*u+ie*l+ae*c+oe*s+se*o,ce+=ve>>>13,ve&=8191,ce=(ce<<2)+ce|0,ce=ce+le|0,le=ce&8191,ce>>>=13,ue+=ce,i[0]=le,i[1]=ue,i[2]=de,i[3]=fe,i[4]=pe,i[5]=me,i[6]=he,i[7]=ge,i[8]=_e,i[9]=ve}finalize(){let{h:e,pad:t}=this,n=/* @__PURE__ */ new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;HU(n)}update(e){zU(this),LU(e),e=uW(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n)for(;n<=r-i;i+=n)this.process(e,i);else t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,HU(this.h,this.r,this.buffer,this.pad)}digestInto(e){zU(this),BU(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};const CW=/* @__PURE__ */ aW(32,e=>new SW(e));function wW(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],x=n[2],S=o,ee=s,C=c,te=l,ne=u,w=d,T=f,re=p,ie=m,ae=h,oe=g,se=_,ce=v,le=y,ue=b,de=x;for(let e=0;e<a;e+=2)S=S+ne|0,ce=gW(ce^S,16),ie=ie+ce|0,ne=gW(ne^ie,12),S=S+ne|0,ce=gW(ce^S,8),ie=ie+ce|0,ne=gW(ne^ie,7),ee=ee+w|0,le=gW(le^ee,16),ae=ae+le|0,w=gW(w^ae,12),ee=ee+w|0,le=gW(le^ee,8),ae=ae+le|0,w=gW(w^ae,7),C=C+T|0,ue=gW(ue^C,16),oe=oe+ue|0,T=gW(T^oe,12),C=C+T|0,ue=gW(ue^C,8),oe=oe+ue|0,T=gW(T^oe,7),te=te+re|0,de=gW(de^te,16),se=se+de|0,re=gW(re^se,12),te=te+re|0,de=gW(de^te,8),se=se+de|0,re=gW(re^se,7),S=S+w|0,de=gW(de^S,16),oe=oe+de|0,w=gW(w^oe,12),S=S+w|0,de=gW(de^S,8),oe=oe+de|0,w=gW(w^oe,7),ee=ee+T|0,ce=gW(ce^ee,16),se=se+ce|0,T=gW(T^se,12),ee=ee+T|0,ce=gW(ce^ee,8),se=se+ce|0,T=gW(T^se,7),C=C+re|0,le=gW(le^C,16),ie=ie+le|0,re=gW(re^ie,12),C=C+re|0,le=gW(le^C,8),ie=ie+le|0,re=gW(re^ie,7),te=te+ne|0,ue=gW(ue^te,16),ae=ae+ue|0,ne=gW(ne^ae,12),te=te+ne|0,ue=gW(ue^te,8),ae=ae+ue|0,ne=gW(ne^ae,7);let fe=0;r[fe++]=o+S|0,r[fe++]=s+ee|0,r[fe++]=c+C|0,r[fe++]=l+te|0,r[fe++]=u+ne|0,r[fe++]=d+w|0,r[fe++]=f+T|0,r[fe++]=p+re|0,r[fe++]=m+ie|0,r[fe++]=h+ae|0,r[fe++]=g+oe|0,r[fe++]=_+se|0,r[fe++]=v+ce|0,r[fe++]=y+le|0,r[fe++]=b+ue|0,r[fe++]=x+de|0}function TW(e,t,n,r){let i=WU?e:qU(e.slice(0,4)),a=WU?t:qU(t.slice(0,8)),o=WU?n:qU(n.slice(0,4)),s=/* @__PURE__ */ new Uint32Array(16);wW(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,qU(r),WU||HU(i,a,o),HU(s)}const EW=/* @__PURE__ */ bW(wW,{counterRight:!1,counterLength:8,extendNonceFn:TW,allowShortKeys:!1}),DW=/* @__PURE__ */ new Uint8Array(16),OW=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(DW.subarray(n))},kW=/* @__PURE__ */ new Uint8Array(32);function AW(e,t,n,r,i){i!==void 0&&LU(i,void 0,`AAD`);let a=e(t,n,kW),o=cW(r.length,i?i.length:0,!0),s=CW.create(a);i&&OW(s,i),OW(s,r),s.update(o);let c=s.digest();return HU(a,o),c}const jW=/* @__PURE__ */ oW({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},/* @__PURE__ */ (e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=sW(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=AW(e,t,n,s,r);return a.set(c,o),HU(c),a},decrypt(i,a){a=sW(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=AW(e,t,n,o,r);if(!iW(s,c))throw HU(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),HU(c),a}}))(EW)),MW={name:`HMAC`,hash:`SHA-256`},NW=`$ba$`;function PW(e){if(!e.startsWith(NW))return null;let t=e.indexOf(`$`,4);if(t===-1)return null;let n=parseInt(e.slice(4,t),10);return!Number.isInteger(n)||n<0?null:{version:n,ciphertext:e.slice(t+1)}}function FW(e,t){return`${NW}${e}$${t}`}async function IW(e,t){let n=await MU(`SHA-256`).digest(e),r=$U(t);return XU(fW(jW)(new Uint8Array(n)).encrypt(r))}async function LW(e,t){let n=await MU(`SHA-256`).digest(e),r=QU(t),i=fW(jW)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}const RW=async({key:e,data:t})=>{if(typeof e==`string`)return IW(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await IW(n,t);return FW(e.currentVersion,r)},zW=async({key:e,data:t})=>{if(typeof e==`string`)return LW(e,t);let n=PW(t);if(n){let t=e.keys.get(n.version);if(!t)throw Error(`Secret version ${n.version} not found in keys (key may have been retired)`);return LW(t,n.ciphertext)}if(e.legacySecret)return LW(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},BW=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await jU().importKey(`raw`,t,MW,!1,[`sign`,`verify`])},VW=async(e,t)=>{let n=await BW(t),r=await jU().sign(MW.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))};function HW(e){return!!e.database||!!e.secondaryStorage}function UW(e){return!!e.database}function WW(e){return UW(e)}function GW(e){return ree(aee,e)}function KW(e){return De(oee,e)}function qW(e){return Oe(cee,e)}const JW=A({id:k(),createdAt:qe().default(()=>/* @__PURE__ */ new Date),updatedAt:qe().default(()=>/* @__PURE__ */ new Date)}),YW=JW.extend({userId:GW(),expiresAt:qe(),token:k(),ipAddress:k().nullish(),userAgent:k().nullish()}),XW=JW.extend({email:k().transform(e=>e.toLowerCase()),emailVerified:He().default(!1),name:k(),image:k().nullish()});function ZW(e,t){if(!e||!t)return e;let n=Object.entries(t).filter(([,{returned:e}])=>e===!1).map(([e])=>e);return Object.entries(structuredClone(e)).filter(([e])=>!n.includes(e)).reduce((e,[t,n])=>({...e,[t]:n}),{})}const QW=/* @__PURE__ */ new WeakMap;function $W(e,t,n){let r=`${t}:${n}`;QW.has(e)||QW.set(e,/* @__PURE__ */ new Map);let i=QW.get(e);if(i.has(r))return i.get(r);let a=n===`output`?p(e)[t]?.fields??{}:{},o=t===`user`||t===`session`||t===`account`?e[t]?.additionalFields:void 0,s={...a,...o??{}};for(let n of e.plugins||[])n.schema&&n.schema[t]&&(s={...s,...n.schema[t].fields});return i.set(r,s),s}function eG(e,t){return ZW(t,$W(e,`user`,`output`))}function tG(e,t){let n=$W(e,`user`,`output`),r={};for(let e in n){let i=n[e];i.returned!==!1&&(e in t&&t[e]!==void 0?r[e]=t[e]:i.defaultValue===void 0?i.required||(r[e]=null):r[e]=typeof i.defaultValue==`function`?i.defaultValue():i.defaultValue)}return`id`in t&&(r.id=t.id),r}function nG(e,t){return ZW(t,$W(e,`session`,`output`))}function rG(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=ZW(t,$W(e,`account`,`output`));return c}function iG(e,t){let n=t.action||`create`,r=t.fields,i=Object.create(null);for(let t in r)if(t in e){if(r[t].input===!1){if(r[t].defaultValue!==void 0&&n!==`update`){i[t]=r[t].defaultValue;continue}if(e[t])throw E.from(`BAD_REQUEST`,{...Y.FIELD_NOT_ALLOWED,message:`${t} is not allowed to be set`});continue}if(r[t].validator?.input&&e[t]!==void 0){let n=r[t].validator.input[`~standard`].validate(e[t]);if(n instanceof Promise)throw E.from(`INTERNAL_SERVER_ERROR`,Y.ASYNC_VALIDATION_NOT_SUPPORTED);if(`issues`in n&&n.issues)throw E.from(`BAD_REQUEST`,{...Y.VALIDATION_ERROR,message:n.issues[0]?.message||`Validation Error`});i[t]=n.value;continue}if(r[t].transform?.input&&e[t]!==void 0){i[t]=r[t].transform?.input(e[t]);continue}i[t]=e[t]}else if(r[t].defaultValue!==void 0&&n===`create`){if(typeof r[t].defaultValue==`function`){i[t]=r[t].defaultValue();continue}i[t]=r[t].defaultValue}else if(r[t].required&&n===`create`)throw E.from(`BAD_REQUEST`,{...Y.MISSING_FIELD,message:`${t} is required`});return i}function aG(e,t={},n){return iG(t,{fields:$W(e,`user`,`input`),action:n})}function oG(e,t={},n){let r=$W(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return iG(i,{fields:r,action:n})}function sG(e,t,n){return iG(t,{fields:$W(e,`session`,`input`),action:n})}function cG(e){let t=$W(e,`session`,`input`),n={};for(let e in t)t[e].defaultValue!==void 0&&(n[e]=typeof t[e].defaultValue==`function`?t[e].defaultValue():t[e].defaultValue);return n}function lG(e,t){if(!t)return e;for(let n in t){let r=t[n]?.modelName;r&&(e[n].modelName=r);for(let r in e[n].fields){let i=t[n]?.fields?.[r];i&&(e[n].fields[r].fieldName=i)}}return e}const uG=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function dG(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}const fG=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;function pG(e){let t=fG.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time string format: "${e}". Use formats like "7d", "30m", "1 hour", etc.`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`years`:case`year`:case`yrs`:case`yr`:case`y`:i=n*315576e5;break;case`months`:case`month`:case`mo`:i=n*2592e6;break;case`weeks`:case`week`:case`w`:i=n*6048e5;break;case`days`:case`day`:case`d`:i=n*864e5;break;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:i=n*36e5;break;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:i=n*6e4;break;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:i=n*1e3;break;default:throw TypeError(`Unknown time unit: "${r}"`)}return t[1]===`-`||t[4]===`ago`?-i:i}function mG(e){return Math.round(pG(e)/1e3)}const hG=Re({session:YW.loose(),user:XW.loose(),updatedAt:Me(),version:k().optional()}),gG=A({session:Ne(k(),Je()),expiresAt:Me(),signature:k()});function _G(e){let t=le(e);if(t===null)return null;let n=hG.safeParse(t);return n.success?n.data:(f.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function vG(e){let t=gG.safeParse(e);return t.success?t.data:null}function yG(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function bG(e){if(!e)return[];let t=[],n=0,r=0;for(;r<e.length;){if(e[r]===`,`){let i=r+1;for(;i<e.length&&e[i]===` `;)i++;for(;i<e.length&&e[i]!==`=`&&e[i]!==`;`&&e[i]!==`,`;)i++;if(i<e.length&&e[i]===`=`){let i=e.slice(n,r).trim();for(i&&t.push(i),n=r+1;n<e.length&&e[n]===` `;)n++;r=n;continue}}r++}let i=e.slice(n).trim();return i&&t.push(i),t}function xG(e){let t=/* @__PURE__ */ new Map;return bG(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=wG(a.join(`=`));if(!i)return;let s={value:yG(o)};r.forEach(e=>{let[t,...n]=e.split(`=`),r=n.join(`=`),i=t.trim().toLowerCase();switch(i){case`max-age`:s[`max-age`]=r?parseInt(r.trim(),10):void 0;break;case`expires`:s.expires=r?new Date(r.trim()):void 0;break;case`domain`:s.domain=r?r.trim():void 0;break;case`path`:s.path=r?r.trim():void 0;break;case`secure`:s.secure=!0;break;case`httponly`:s.httponly=!0;break;case`samesite`:s.samesite=r?r.trim().toLowerCase():void 0;break;case`partitioned`:s.partitioned=!0;break;default:s[i]=!r||r.trim()}}),t.set(i,s)}),t}const SG=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,CG=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function wG(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function TG(e){let t=0,n=e.length;for(;t<n;){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}for(;n>t;){let t=e.charCodeAt(n-1);if(t!==32&&t!==9)break;n--}return t===0&&n===e.length?e:e.slice(t,n)}function EG(e){let t=/* @__PURE__ */ new Map;if(e.length<2)return t;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e===-1)continue;let r=TG(n.slice(0,e)),i=wG(TG(n.slice(e+1)));SG.test(r)&&CG.test(i)&&t.set(r,yG(i))}return t}function DG(e){let t={clockTolerance:15,audience:e?.audience??`better-auth:session-cache`};return e?.issuer&&(t.issuer=e.issuer),t}function OG(e){let t=_G(e);return!t||typeof e.iss!=`string`||!e.iss||e.sub!==t.user.id||e.sid!==t.session.token?null:{...e,...t}}const kG={name:`HMAC`,hash:`SHA-256`},AG=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await jU().importKey(`raw`,t,kG,!1,[`sign`,`verify`])},jG=async(e,t,n)=>{try{let r=atob(e),i=new Uint8Array(r.length);for(let e=0,t=r.length;e<t;e++)i[e]=r.charCodeAt(e);return await jU().verify(kG,n,i,new TextEncoder().encode(t))}catch{return!1}},MG=async(e,t)=>{let n=await AG(t),r=await jU().sign(kG.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},NG=async(e,t)=>{let n=await MG(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},PG=/^application\/([a-z0-9.+-]*\+)?json/i;async function FG(e,t){let n=e.headers.get(`content-type`)||``,r=n.toLowerCase();if(e.body){if(t&&t.length>0&&!t.some(e=>{let t=r.split(`;`)[0].trim(),n=e.toLowerCase().trim();return t===n||t.includes(n)}))throw r?new O(415,{message:`Content-Type "${n}" is not allowed. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`}):new O(415,{message:`Content-Type is required. Allowed types: ${t.join(`, `)}`,code:`UNSUPPORTED_MEDIA_TYPE`});if(PG.test(r))try{return await e.json()}catch(e){throw e instanceof SyntaxError?new O(400,{message:`Invalid JSON in request body`,code:`BAD_REQUEST`}):e}if(r.includes(`application/x-www-form-urlencoded`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e.toString()}),n}if(r.includes(`multipart/form-data`)){let t=await e.formData(),n={};return t.forEach((e,t)=>{n[t]=e}),n}return r.includes(`text/plain`)?await e.text():r.includes(`application/octet-stream`)?await e.arrayBuffer():r.includes(`application/pdf`)||r.includes(`image/`)||r.includes(`video/`)?await e.blob():r.includes(`application/stream`)||e.body instanceof ReadableStream?e.body:await e.text()}}function IG(e){return e instanceof O||e?.name===`APIError`}function LG(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function RG(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function zG(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}const BG={secure:`__Secure-`,host:`__Host-`},VG=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return BG[t]+e};function HG(e){if(typeof e!=`string`)throw TypeError(`argument str must be a string`);let t=/* @__PURE__ */ new Map,n=0;for(;n<e.length;){let r=e.indexOf(`=`,n);if(r===-1)break;let i=e.indexOf(`;`,n);if(i===-1)i=e.length;else if(i<r){n=e.lastIndexOf(`;`,r-1)+1;continue}let a=e.slice(n,r).trim();if(!t.has(a)){let n=e.slice(r+1,i).trim();n.codePointAt(0)===34&&(n=n.slice(1,-1)),t.set(a,LG(n))}n=i+1}return t}function UG(e,t,n={}){let r=VG(e,n.prefix)??e,i={...n},a=r.toLowerCase();return a.startsWith(`__host-`)?(i.secure=!0,i.path=`/`,i.domain=void 0):a.startsWith(`__secure-`)&&(i.secure=!0),(i.partitioned===!0||i.sameSite?.toLowerCase()===`none`)&&(i.secure=!0),{name:r,value:t,options:i}}function WG({name:e,value:t,options:n}){let r=`${e}=${t}`;if(typeof n.maxAge==`number`&&n.maxAge>=0){if(n.maxAge>3456e4)throw Error(`Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.`);r+=`; Max-Age=${Math.floor(n.maxAge)}`}if(n.domain&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw Error(`Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.`);r+=`; Expires=${n.expires.toUTCString()}`}return n.httpOnly&&(r+=`; HttpOnly`),n.secure&&(r+=`; Secure`),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.partitioned&&(r+=`; Partitioned`),r}const GG=(e,t,n)=>(t=encodeURIComponent(t),WG(UG(e,t,n))),KG=async(e,t,n,r)=>(t=await NG(t,n),WG(UG(e,t,r)));async function qG(e,t={}){let n={body:t.body,query:t.query};if(e.body){let r=await e.body[`~standard`].validate(t.body);if(r.issues)return{data:null,error:JG(r.issues,`body`)};n.body=r.value}if(e.query){let r=await e.query[`~standard`].validate(t.query);if(r.issues)return{data:null,error:JG(r.issues,`query`)};n.query=r.value}return e.requireHeaders&&!t.headers?{data:null,error:{message:`Headers is required`,issues:[]}}:e.requireRequest&&!t.request?{data:null,error:{message:`Request is required`,issues:[]}}:{data:n,error:null}}function JG(e,t){return{message:e.map(e=>`[${e.path?.length?`${t}.`+e.path.map(e=>typeof e==`object`?e.key:e).join(`.`):t}] ${e.message}`).join(`; `),issues:e}}const YG=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await qG(t,e);if(o)throw new Ae(o.message,o.issues);let s=e.headers===void 0?`request`in e&&zG(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?HG(c):void 0,u={...e,body:a.body,query:a.query,path:e.path||n||`virtual:`,context:`context`in e&&e.context?e.context:{},returned:void 0,headers:e?.headers,request:e?.request,params:`params`in e?e.params:void 0,method:e.method??(Array.isArray(t.method)?t.method[0]:t.method===`*`?`GET`:t.method),setHeader:(e,t)=>{r.set(e,t)},getHeader:e=>s?s.get(e):null,getCookie:(e,t)=>{let n=VG(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=VG(e,n);if(!r)return null;let i=l?.get(r);if(!i)return null;let a=i.lastIndexOf(`.`);if(a<1)return null;let o=i.substring(0,a),s=i.substring(a+1);return s.length!==44||!s.endsWith(`=`)?null:await jG(s,o,await AG(t))?o:!1},setCookie:(e,t,n)=>{let i=GG(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await KG(e,t,n,i);return r.append(`set-cookie`,a),a},redirect:e=>(r.set(`location`,e),new O(`FOUND`,void 0,r)),error:(e,t,n)=>new O(e,t,n),setStatus:e=>{i=e},json:(t,n)=>e.asResponse?{body:n?.body||t,routerResponse:n,_flag:`json`}:t,responseHeaders:r,get responseStatus(){return i}};for(let e of t.use||[]){let t=await e({...u,returnHeaders:!0,asResponse:!1});t.response&&Object.assign(u.context,t.response),t.headers&&t.headers.forEach((e,t)=>{u.responseHeaders.set(t,e)})}return u};function XG(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function ZG(e){let t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap,r=0,i=(e,n)=>{let r=n;for(;r;){if(r===e)return!0;r=t.get(r)}return!1};return JSON.stringify(e,function(e,a){if(typeof a==`bigint`)return a.toString();if(typeof a==`object`&&a){if(i(a,this))return`[Circular ref-${n.get(a)}]`;t.set(a,this),n.has(a)||n.set(a,r++)}return a})}function QG(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}const $G=/* @__PURE__ */ new Set(/* @__PURE__ */ `host.user-agent.referer.from.expect.authorization.proxy-authorization.cookie.origin.accept-charset.accept-encoding.accept-language.if-match.if-none-match.if-modified-since.if-unmodified-since.if-range.range.max-forwards.connection.keep-alive.transfer-encoding.te.upgrade.trailer.proxy-connection.content-length`.split(`.`));function eK(e){for(let t of $G)e.delete(t)}function tK(e,t){if(t)for(let[n,r]of new Headers(t).entries())n.toLowerCase()===`set-cookie`?e.append(n,r):e.set(n,r)}function nK(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);eK(n),tK(e.headers,n)}return e}if(QG(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if(tK(i,r?.headers),tK(i,e.headers),t?.headers){let e=new Headers(t.headers);eK(e),tK(i,e)}i.set(`Content-Type`,`application/json`);let a=e.status??t?.status??r?.status,o=t?.statusText??r?.statusText;return new Response(JSON.stringify(n),{...r,headers:i,...a===void 0?{}:{status:a},...o===void 0?{}:{statusText:o}})}if(IG(e))return nK(e.body,{status:t?.status??e.statusCode,statusText:e.status.toString(),headers:t?.headers||e.headers});let n=e,r=new Headers(t?.headers);return eK(r),e?typeof e==`string`?(n=e,r.set(`Content-Type`,`text/plain`)):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?(n=e,r.set(`Content-Type`,`application/octet-stream`)):e instanceof Blob?(n=e,r.set(`Content-Type`,e.type||`application/octet-stream`)):e instanceof FormData?n=e:e instanceof URLSearchParams?(n=e,r.set(`Content-Type`,`application/x-www-form-urlencoded`)):e instanceof ReadableStream?(n=e,r.set(`Content-Type`,`application/octet-stream`)):XG(e)&&(n=ZG(e),r.set(`Content-Type`,`application/json`)):(e===null&&(n=JSON.stringify(null)),r.set(`content-type`,`application/json`)),new Response(n,{...t,headers:r})}function rK(e,t,n){let r=typeof e==`string`?e:void 0,i=typeof t==`object`?t:e,a=typeof t==`function`?t:n;if((i.method===`GET`||i.method===`HEAD`)&&i.body)throw new ke(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new ke(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await RG(YG(t,{options:i,path:r}));if(o)throw o instanceof Ae?(i.onValidationError&&await i.onValidationError({message:o.message,issues:o.issues}),new O(400,{message:o.message,code:`VALIDATION_ERROR`})):o;let s=await a(n).catch(async e=>{if(IG(e)){let n=i.onAPIError;if(n&&await n(e),t.asResponse)return e}throw e}),c=n.responseHeaders,l=n.responseStatus;return t.asResponse?nK(s,l===void 0?{headers:c}:{headers:c,status:l}):t.returnHeaders?t.returnStatus?{headers:c,response:s,status:l}:{headers:c,response:s}:t.returnStatus?{response:s,status:l}:s};return o.options=i,o.path=r,o}function iK(e,t){return[...e??[],...t??[]]}rK.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return rK(n,{...r,use:iK(r.use,e?.use)},i)}let[n,r]=t;return rK({...n,use:iK(n.use,e?.use)},r)}return t};function aK(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await YG(r,{options:typeof e==`function`?{}:e,path:`/`});if(!i)throw Error(`handler must be defined`);try{let e=await i(a),t=a.responseHeaders;return r.returnHeaders?{headers:t,response:e}:e}catch(e){throw IG(e)&&Object.defineProperty(e,je,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}aK.create=e=>{function t(t,n){if(typeof t==`function`)return aK({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return aK({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};const oK={};function sK(e){switch(e.constructor.name){case`ZodString`:return`string`;case`ZodNumber`:return`number`;case`ZodBoolean`:return`boolean`;case`ZodObject`:return`object`;case`ZodArray`:return`array`;default:return`string`}}function cK(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof Ge&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof Ge&&t.push({name:e,in:`query`,schema:{type:sK(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function lK(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof Ge||e.body instanceof ze)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof Ge&&(n[e]={type:sK(t),description:t.description},t instanceof ze||r.push(e))}),{required:e.body instanceof ze?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function uK(e){return{400:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Bad Request. Usually due to missing parameters, or invalid parameters.`},401:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}},required:[`message`]}}},description:`Unauthorized. Due to missing or invalid authentication.`},403:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Forbidden. You do not have permission to access this resource or to perform this action.`},404:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Not Found. The requested resource was not found.`},429:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Too Many Requests. You have exceeded the rate limit. Try again later.`},500:{content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}},description:`Internal Server Error. This is a problem with the server that you cannot fix.`},...e}}async function dK(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(oK[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:cK(n),responses:uK(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=lK(n);oK[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:cK(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:uK(n.metadata?.openapi?.responses)}}}}),{openapi:`3.1.1`,info:{title:`Better Auth`,description:`API Reference for your Better Auth Instance`,version:`1.1.0`},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:t?.url}],tags:[{name:`Default`,description:`Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin.`}],paths:oK}}const fK=(e,t)=>`<!doctype html>
31
+ <html>
32
+ <head>
33
+ <title>Scalar API Reference</title>
34
+ <meta charset="utf-8" />
35
+ <meta
36
+ name="viewport"
37
+ content="width=device-width, initial-scale=1" />
38
+ </head>
39
+ <body>
40
+ <script
41
+ id="api-reference"
42
+ type="application/json">
43
+ ${JSON.stringify(e)}
44
+ <\/script>
45
+ <script>
46
+ var configuration = {
47
+ favicon: ${t?.logo?`data:image/svg+xml;utf8,${encodeURIComponent(t.logo)}`:void 0} ,
48
+ theme: ${t?.theme||`saturn`},
49
+ metaData: {
50
+ title: ${t?.title||`Open API Reference`},
51
+ description: ${t?.description||`Better Call Open API`},
52
+ }
53
+ }
54
+ document.getElementById('api-reference').dataset.configuration =
55
+ JSON.stringify(configuration)
56
+ <\/script>
57
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"><\/script>
58
+ </body>
59
+ </html>`,pK=/* @__PURE__ */ (()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function mK(){return{root:{key:``},static:new pK}}function hK(e){let t=0,n=0;for(;t<e.length;t++){let r=e.charCodeAt(t);if(r===92)t++;else if(r===40)n++;else if(r===41&&n>0)n--;else if(r===123&&n===0)break}if(t>=e.length)return;let r=t+1;for(n=0;r<e.length;r++){let t=e.charCodeAt(r);if(t===92)r++;else if(t===40)n++;else if(t===41&&n>0)n--;else if(t===125&&n===0)break}if(r>=e.length)return;let i=e[r+1],a=i===`?`||i===`+`||i===`*`;return[e.slice(0,t),e.slice(t+1,r),e.slice(r+(a?2:1)),a?i:void 0]}function gK(e){if(!e.includes(`{`))return;let t=hK(e);if(!t)return;let[n,r,i,a]=t;if(!a)return[n+r+i];if(a===`?`)return[n+r+i,n+i];if(r.includes(`/`))throw Error(`unsupported group repetition across segments`);return[`${n}(?:${r})${a}${i}`]}function _K(e){return`__rou3_unnamed_${e}`}function vK(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:`__rou3_esc_`+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function yK(e){return e.charCodeAt(0)===95?e.startsWith(`__rou3_esc_`)?e.slice(11).replace(/__|_h/g,e=>e===`__`?`_`:`-`):e.startsWith(`__rou3_unnamed_`)?e.slice(15):e:e}function bK(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r===92)n++;else if(r===40)t++;else if(r===41&&t>0)t--;else if(r===42&&t===0)return!0}return!1}function xK(e,t,n=_K){let r=0,i=t,a=``;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t);o===92?(a+=e[t],t+1<e.length&&(a+=e[++t])):o===40?(r++,a+=e[t]):o===41&&r>0?(r--,a+=e[t]):a+=o===42&&r===0?`(?<${n(i++)}>[^/]*)`:e[t]}return[a,i]}function SK(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function CK(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||bK(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function wK(e){for(let t=0;t<e.length;t++){let n=e[t].charCodeAt(e[t].length-1);if(n!==63&&n!==43&&n!==42)continue;let r=e[t].match(/^(.*:[\w-]+(?:\([^)]*\))?)([?+*])$/);if(!r)continue;let i=e.slice(0,t),a=e.slice(t+1);if(r[2]===`?`)return[`/`+i.concat(r[1]).concat(a).join(`/`),`/`+i.concat(a).join(`/`)];let o=r[1].match(/:([\w-]+)/)?.[1]||`_`,s=`/`+[...i,`**:${o}`,...a].join(`/`),c=`/`+[...i,...a].join(`/`);return r[2]===`+`?[s]:[s,c]}}function TK(e){if(!e.includes(`/.`))return e;let t=[];for(let n of e.split(`/`))if(n===`.`)continue;else n===`..`&&t.length>1?t.pop():t.push(n);return t.join(`/`)||`/`}function EK(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function DK(e){let t=EK(e);for(;t[t.length-1]===``;)t.pop();return t}function OK(e,t){let n=new pK;for(let[r,i]of t){let t=r<0?e.slice(-(r+1)).join(`/`):e[r];if(typeof i==`string`)n[i]=t;else{let e=t.match(i);if(e)for(let t in e.groups)n[yK(t)]=e.groups[t]}}return n}function kK(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=gK(n);if(i){for(let n of i)kK(e,t,n,r);return}n=SK(n);let a=DK(n),o=wK(a);if(o){for(let n of o)kK(e,t,n,r);return}let s=e.root,c=0,l=[],u=[];for(let e=0;e<a.length;e++){let t=a[e],n=CK(t);if(n===2){s.wildcard||(s.wildcard={key:`**`}),s=s.wildcard,l.push([-(e+1),t.split(`:`)[1]||`_`,t.length===2]);break}if(n===1){if(s.param||(s.param={key:`*`}),s=s.param,t===`*`)l.push([e,String(c++),!0]);else if(t.includes(`(`)||t.includes(`:`,1)||!/^:[\w-]+$/.test(t)){let[n,r]=AK(t,c);c=r,u[e]=n,s.hasRegexParam=!0,l.push([e,n,!1])}else l.push([e,t.slice(1),!1]);continue}t=a[e]=n;let r=s.static?.[t];if(r)s=r;else{let e={key:t};s.static||(s.static=new pK),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new pK;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function AK(e,t=0){let n=t,r=``,i=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n===40)i++;else if(n===41&&i>0)i--;else if(n===92&&i===0&&t+1<e.length){let n=e[t+1];if(n!==`:`&&n!==`(`&&n!==`*`&&n!==`\\`){r+=`￾`+n,t++;continue}}else if(n===46&&i===0){r+=`\\.`;continue}r+=e[t]}[r,n]=xK(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${vK(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${_K(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function jK(e,t=``,n,r){r?.normalize&&(n=TK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=e.static[n];if(i&&i.methods){let e=i.methods[t]||i.methods[``];if(e!==void 0)return e[0]}let a=EK(n),o=MK(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?OK(a,o.paramsMap):void 0}}function MK(e,t,n,r){if(r===n.length){if(e.methods){let r=NK(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&NK(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&NK(e.wildcard.methods,t,n,!0,!0)||void 0}let i=n[r];if(e.static){let a=e.static[i];if(a){let e=MK(a,t,n,r+1);if(e)return e}}if(e.param){let i=MK(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return NK(e.wildcard.methods,t,n,!0,!1)}function NK(e,t,n,r,i){let a=e[t]||e[``];if(!a)return;let o=a[0];if(a.length===1&&o.paramsRegexp.length===0){if(!i)return o;let e=o.paramsMap;return e?.[e.length-1]?.[2]?o:void 0}let s,c=-1;for(let e of a){let t=e.paramsMap,a=t?.[t.length-1]?.[2];if(i&&!a)continue;let o=r&&t&&!a?1:0,l=e.paramsRegexp;for(let e=0;e<l.length;e++)if(l[e]){if(!l[e].test(n[e])){o=-1;break}o++}o>c&&(s=e,c=o)}return s}function PK(e,t=``,n,r){r?.normalize&&(n=TK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=EK(n),a=FK(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?OK(i,e.paramsMap):void 0}))}function FK(e,t,n,r,i=[]){let a=n[r];if(e.wildcard&&e.wildcard.methods){let a=e.wildcard.methods[t]||e.wildcard.methods[``];if(a){if(r<n.length)IK(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}IK(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(FK(e.param,t,n,r+1,i),e.param.hasRegexParam)for(let e=i.length-1;e>=o;e--)i[e].paramsRegexp[r]?.test(a)===!1&&i.splice(e,1)}else if(e.param.methods){let n=e.param.methods[t]||e.param.methods[``];if(n){let e=[];for(let t of n){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}IK(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&FK(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&IK(i,n,e.key===`*`)}return i}function IK(e,t,n){t.length>1&&(t=t.map(e=>{let t=0,{paramsRegexp:r,paramsMap:i}=e;for(let e=0;e<r.length;e++)r[e]&&t++;return n&&i&&!i[i.length-1][2]&&t++,[e,t]}).sort((e,t)=>e[1]-t[1]).map(e=>e[0]));for(let n of t)e.push(n)}const LK=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=rK(n.path,{method:`GET`},async t=>{let r=await dK(e);return new Response(fK(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=mK(),r=mK();for(let t of Object.values(e)){if(!t.options||!t.path||t.options?.metadata?.SERVER_ONLY)continue;let e=Array.isArray(t.options?.method)?t.options.method:[t.options?.method];for(let r of e)kK(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)kK(r,`*`,e,n);let i=t?.basePath&&t.basePath!==`/`?t.basePath.replace(/\/+$/,``):``,a=async e=>{let a=new URL(e.url),o=a.pathname,s;if(i){if(!o.startsWith(`${i}/`))return new Response(null,{status:404,statusText:`Not Found`});s=o.slice(i.length)}else s=o;if(s.length===0||/\/{2,}/.test(s))return new Response(null,{status:404,statusText:`Not Found`});let c=jK(n,e.method,s);if(s.endsWith(`/`)!==c?.data?.path?.endsWith(`/`)&&!t?.skipTrailingSlashes||!c?.data)return new Response(null,{status:404,statusText:`Not Found`});let l={};a.searchParams.forEach((e,t)=>{t in l?Array.isArray(l[t])?l[t].push(e):l[t]=[l[t],e]:l[t]=e});let u=c.data;try{let n=u.options.metadata?.allowedMediaTypes||t?.allowedMediaTypes,i={path:s,method:e.method,headers:e.headers,params:c.params?{...c.params}:{},request:e,body:u.options.disableBody?void 0:await FG(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=PK(r,`*`,s);if(a?.length)for(let{data:e,params:t}of a){let n=await e({...i,params:t?{...t}:{},asResponse:!1});if(n instanceof Response)return n}return await u(i)}catch(n){if(t?.onError)try{let r=await t.onError(n,e);if(r instanceof Response)return nK(r)}catch(e){if(IG(e))return nK(e);throw e}if(t?.throwError)throw n;return IG(n)?nK(n):(console.error(`# SERVER_ERROR: `,n),new Response(null,{status:500,statusText:`Internal Server Error`}))}};return{handler:async e=>{let n=await t?.onRequest?.(e);if(n instanceof Response)return n;let r=zG(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}},RK=4050;function zK(e,t){return RK-GG(e,``,{...t}).length}function BK(e,t){let n=`${e}.`;if(!t.startsWith(n))return null;let r=t.slice(n.length),i=Number(r);return!Number.isSafeInteger(i)||i<0||String(i)!==r?null:i}function VK(e,t){let n={},r=EG(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||BK(e,t)!==null)&&(n[t]=i);return n}function HK(e,t,n,r){let i=zK(`${t.name}.99`,t.attributes),a=i>0?Math.ceil(t.value.length/i):1/0;if(a<=1)return n[t.name]=t.value,[t];if(a>100)return r.warn(`${e} cookie is too large to store even after chunking, so the cookie cache was skipped. Reduce the cached data size or avoid storing this data in cookies.`),[];let o=[];for(let e=0;e<a;e++){let r=`${t.name}.${e}`,a=e*i,s=t.value.substring(a,a+i);o.push({...t,name:r,value:s}),n[r]=s}return r.debug(`CHUNKING_${e.toUpperCase()}_COOKIE`,{message:`${e} cookie exceeds the ${RK} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function UK(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}const WK=e=>(t,n,r)=>{let i=VK(t,r),a=r.context.logger,o=()=>{let e=UK(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=HK(e,{name:t,value:r,attributes:{...n,...s}},i,a);for(let e of l)c[e.name]=e;return Object.values(c)},clean(){return Object.values(o())},setCookies(e){for(let t of e)r.setCookie(t.name,t.value,t.attributes)}}},GK=WK(`Session`),KK=WK(`Account`);function qK(e,t){let n=e.getCookie(t);if(n)return n;let r=[],i=e.headers?.get(`cookie`);if(!i)return null;for(let[e,n]of EG(i)){let i=BK(t,e);i!==null&&r.push({index:i,value:n})}return r.length>0?(r.sort((e,t)=>e.index-t.index),r.map(e=>e.value).join(``)):null}async function JK(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await xU(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=KK(n.name,r,e);a.setCookies(a.chunk(i,r))}async function YK(e){let t=qK(e,e.context.authCookies.accountData.name);if(t){let n=le(await CU(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}const XK=Xe(A({disableCookieCache:qW().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:qW().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()})),ZK=/* @__PURE__ */ new Map,QK=new TextEncoder,$K={decode:(e,t=`utf-8`)=>(ZK.has(t)||ZK.set(t,new TextDecoder(t)),ZK.get(t).decode(e)),encode:e=>QK.encode(e)},eq=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>jU().importKey(`raw`,_e(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await jU().sign(`HMAC`,e,_e(r));return t===`hex`?Se.encode(i):t===`base64`?ue.encode(i):t===`base64url`||t===`base64urlnopad`?ye.encode(i,{padding:t!==`base64urlnopad`}):i},verify:async(e,r,i)=>(typeof e==`string`&&(e=await n.importKey(e,`verify`)),t===`hex`&&(i=typeof i==`string`?Se.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await ue.decode(i)),jU().verify(`HMAC`,e,_e(i),_e(r)))};return n};function tq(e){let t=typeof e.baseURL==`string`?e.baseURL:void 0,n=typeof e.baseURL==`object`&&e.baseURL!==null?e.baseURL.protocol:void 0,r=(e.advanced?.useSecureCookies===void 0?n===`https`||n!==`http`&&(t?t.startsWith(`https://`):te):e.advanced?.useSecureCookies)?`__Secure-`:``,i=!!e.advanced?.crossSubDomainCookies?.enabled,a=i?e.advanced?.crossSubDomainCookies?.domain||(t?new URL(t).hostname:void 0):void 0;if(i&&!a&&!VH(e.baseURL))throw new D(`baseURL is required when crossSubdomainCookies are enabled.`);function o(t,n={}){let o=e.advanced?.cookiePrefix||`better-auth`,s=e.advanced?.cookies?.[t]?.name||`${o}.${t}`,c=e.advanced?.cookies?.[t]?.attributes??{};return{name:`${r}${s}`,attributes:{secure:!!r,sameSite:`lax`,path:`/`,httpOnly:!0,...i?{domain:a}:{},...e.advanced?.defaultCookieAttributes,...n,...c}}}return o}function nq(e){let t=tq(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||mG(`7d`)}),r=t(`session_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),i=t(`account_data`,{maxAge:e.session?.cookieCache?.maxAge||300}),a=t(`dont_remember`);return{sessionToken:{name:n.name,attributes:n.attributes},sessionData:{name:r.name,attributes:r.attributes},dontRememberToken:{name:a.name,attributes:a.attributes},accountData:{name:i.name,attributes:i.attributes}}}async function rq(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=ZW(t.session,e.context.options.session?.additionalFields),i=eG(e.context.options,t.user),a=e.context.options.session?.cookieCache?.version,o=`1`;if(a){if(typeof a==`string`)o=a;else if(typeof a==`function`){let e=a(t.session,t.user);o=dG(e)?await e:e}}let s={session:r,user:i,updatedAt:Date.now(),version:o},c={...e.context.authCookies.sessionData.attributes,maxAge:n?void 0:e.context.authCookies.sessionData.attributes.maxAge},l=uG(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,d;if(u===`jwe`)d=await xU(s,e.context.secretConfig,`better-auth-session`,c.maxAge||300);else if(u===`jwt`){let t=e.context.sessionConfig.cookieCacheSigner;d=t?await t.sign(e,s,c.maxAge||300):await pU(s,e.context.secret,c.maxAge||300)}else d=ye.encode(JSON.stringify({session:s,expiresAt:l,signature:await eq(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let f=GK(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(d,c)),e.context.options.account?.storeAccountCookie&&!sq(e,e.context.authCookies.accountData.name)){let n=await YK(e);if(n){if(!WW(e.context.options)||n.userId===t.user.id)await JK(e,n);else{cq(e,e.context.authCookies.accountData);let t=KK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function iq(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await CU(t,e.context.secretConfig,`better-auth-session`),r=_G(n);return r?{session:r,expiresAt:n?.exp?n.exp*1e3:Date.now()}:null}if(n===`jwt`){let n=e.context.sessionConfig.cookieCacheSigner;if(n){let r=await n.verify(e,t);return r?{session:r.payload,expiresAt:r.expiresAt}:null}let r=await mU(t,e.context.secret),i=_G(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=vG(le($K.decode(ye.decode(t))));if(!r||!await eq(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=_G(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function aq(e,t,n,r){let i=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);n=n===void 0?!!i:n;let a=e.context.authCookies.sessionToken.attributes,o=n?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...a,maxAge:o,...r}),n&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,`true`,e.context.secret,e.context.authCookies.dontRememberToken.attributes),await rq(e,t,n),e.context.setNewSession(t)}function oq(e,t){let n=e,r=/* @__PURE__ */ new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r){let t=typeof e.getSetCookie==`function`?e.getSetCookie():bG(e.get(`set-cookie`)||``);if(!t.length)continue;let n=t.filter(e=>!e.startsWith(i)&&!e.startsWith(a));if(n.length!==t.length){e.delete(`set-cookie`);for(let t of n)e.append(`set-cookie`,t)}}}function sq(e,t){let n=e,r=/* @__PURE__ */ new Set;n.responseHeaders&&r.add(n.responseHeaders),n.context?.responseHeaders&&r.add(n.context.responseHeaders);let i=`${t}=`,a=`${t}.`;for(let e of r)if((typeof e.getSetCookie==`function`?e.getSetCookie():bG(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function cq(e,t){oq(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function lq(e,t){if(cq(e,e.context.authCookies.sessionToken),cq(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){cq(e,e.context.authCookies.accountData);let t=KK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&cq(e,e.context.createAuthCookie(`oauth_state`));let n=GK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||cq(e,e.context.authCookies.dontRememberToken)}const uq=g(`better-auth:oauth-encryption:v1`);function dq(e,t){return se(eU(fU,g(e),uq,g(`better-auth:${t}:v1`),32))}function fq(e,t){return typeof e==`string`?dq(e,t):{keys:new Map(Array.from(e.keys,([e,n])=>[e,dq(n,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:dq(e.legacySecret,t)}}}const pq=Re({callbackURL:k(),codeVerifier:k(),errorURL:k().optional(),newUserURL:k().optional(),expiresAt:Me(),oauthState:k().optional(),link:A({email:k(),userId:GW()}).optional(),requestSignUp:He().optional(),idTokenNonce:k().optional(),serverContext:Ne(k(),Je()).optional()}),mq=e=>`auth-state:${e}`;new Set(Object.keys(pq.shape));var hq=class extends D{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function gq(e,t,n){let r=JH(32);if(e.context.oauthConfig.storeStateStrategy===`cookie`){let i={...t,oauthState:r},a=await RW({key:fq(e.context.secretConfig,`oauth-state-cookie`),data:JSON.stringify(i)}),o=e.context.createAuthCookie(n?.cookieName??`oauth_state`,{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:r,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(n?.cookieName??`state`,{maxAge:300});await e.setSignedCookie(i.name,r,e.context.secret,i.attributes);let a=/* @__PURE__ */ new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:r}),identifier:mq(r),expiresAt:a}))throw new hq(`Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database`,{code:`state_generation_error`});return{state:r,codeVerifier:t.codeVerifier}}async function _q(e,t,n){if(!t)throw new hq(`State not found in OAuth callback`,{code:`state_not_found`});let r=e.context.oauthConfig.storeStateStrategy,i;if(r===`cookie`){let r=e.context.createAuthCookie(n?.cookieName??`oauth_state`),a=e.getCookie(r.name);if(!a)throw new hq(`State mismatch: auth state cookie not found`,{code:`state_mismatch`,details:{state:t}});try{let t=await zW({key:fq(e.context.secretConfig,`oauth-state-cookie`),data:a});i=pq.parse(JSON.parse(t))}catch(e){throw new hq(`State invalid: Failed to decrypt or parse auth state`,{code:`state_invalid`,details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new hq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});cq(e,r)}else{let r=await e.context.internalAdapter.findVerificationValue(mq(t));if(!r)throw new hq(`State mismatch: verification not found`,{code:`state_mismatch`,details:{state:t}});if(i=pq.parse(JSON.parse(r.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new hq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});let a=e.context.createAuthCookie(n?.cookieName??`state`),o=await e.getSignedCookie(a.name,e.context.secret);if(!(n?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new hq(`State mismatch: State not persisted correctly`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});cq(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(mq(t))}if(i.expiresAt<Date.now())throw new hq(`Invalid state: request expired`,{code:`state_mismatch`,details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function vq(e,t){let n;try{n=new URL(e).pathname.replace(/\/+$/,``)||`/`}catch{return`/`}let r=t.replace(/\/+$/,``);return r===``?n:n===r?`/`:n.startsWith(r+`/`)?n.slice(r.length).replace(/\/+$/,``)||`/`:n}const yq=`https://better-auth.invalid`;function bq(e,t){let n=e.startsWith(`/`);if(e.startsWith(`//`)||e.startsWith(`/\\`))throw TypeError(`Expected an absolute or root-relative URL`);let r=n?new URL(e,yq):new URL(e);if(n&&r.origin!==yq)throw TypeError(`Expected an absolute or root-relative URL`);let i=t.toString();if(!i)return e;let a=r.search.endsWith(`&`)?``:`&`;return r.search=r.search?`${r.search}${a}${i}`:i,n?r.href.slice(r.origin.length):r.href}const xq=[`javascript:`,`data:`,`vbscript:`],Sq={NO_CODE:`no_code`,PROVIDER_NOT_FOUND:`oauth_provider_not_found`,ISSUER_MISSING:`issuer_missing`,ISSUER_MISMATCH:`issuer_mismatch`,INVALID_CODE:`invalid_code`,NONCE_BINDING_MISSING:`nonce_binding_missing`,UNABLE_TO_GET_USER_INFO:`unable_to_get_user_info`,NO_CALLBACK_URL:`no_callback_url`,UNABLE_TO_LINK_ACCOUNT:`unable_to_link_account`,EMAIL_DOES_NOT_MATCH:`email_does_not_match`,ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:`account_already_linked_to_different_user`,EMAIL_NOT_FOUND:`email_not_found`,EMAIL_NOT_VERIFIED:`email_not_verified`};function Cq(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=bq(t,i);throw e.redirect(a)}function wq(e,t){return`${t?.source===`generic`?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source===`id_token`?` in the id token`:``}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}const{get:Tq,set:Eq}=yH(()=>null),Dq=async()=>await Tq(),{get:Oq,set:kq}=yH(()=>null),Aq=async e=>{await kq({...await Oq()??{},...e})};function jq(e){return e.requiresIdTokenNonce?JH(32):void 0}async function Mq(e,t){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw E.from(`BAD_REQUEST`,Y.CALLBACK_URL_REQUIRED);let r=t?.codeVerifier??JH(128),i=await Oq(),a=i&&Object.keys(i).length?i:void 0,o={...t?.additionalData?t.additionalData:{},callbackURL:n,codeVerifier:r,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:a,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await Eq(o);try{return gq(e,o)}catch(t){throw e.context.logger.error(`Failed to create verification`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`Unable to create verification`,cause:t})}}async function Nq(e){let t=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,r;try{r=await _q(e,t)}catch(t){e.context.logger.error(`Failed to parse state`,t);let r=`internal_server_error`,i=n;t instanceof hq&&(r=t.code===`state_security_mismatch`?`state_mismatch`:t.code,i=t.errorURL||n),Cq(e,i,r)}return r.errorURL||(r.errorURL=n),r&&await Eq(r),r}const Pq={scope:`server`};function Fq(e){return e instanceof O||e instanceof E||e?.name===`APIError`}const Iq={"Cache-Control":`no-store`,Pragma:`no-cache`};function Lq(e,t){Fq(t)&&e&&Object.defineProperty(t,je,{enumerable:!1,configurable:!0,value:e,writable:!1})}const Rq=aK(async()=>({})),zq=aK.create({use:[Rq,aK(async()=>({}))]}),Bq=rK.create({use:[Rq]});function Vq(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(Iq))t.setHeader(e,n);try{return await mH(t,()=>e(t))}catch(e){throw Lq(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return Bq(t,n,Vq(r,n))}let[t,n]=e;return Bq(t,Vq(n,t))}function Hq(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(Hq(e),t);const Uq=/[\u0000-\u001f\u007f-\u009f]/,Wq=`https://better-auth.invalid`,Gq=/%2[fF]|%5[cC]/,Kq=e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let n=[];for(let e of t.split(`/`))e===`..`?n.pop():e!==`.`&&e!==``&&n.push(e);return n.length>0?`/${n.join(`/`)}`:``},qq=e=>{if(Uq.test(e))return null;let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1),i=``;if(r.startsWith(`//`)){r=r.slice(2);let e=r.search(/[/?#]/);e===-1?(i=r,r=``):(i=r.slice(0,e),r=r.slice(e))}let a=r.search(/[?#]/),o=Kq(a===-1?r:r.slice(0,a));return{scheme:n,authority:i.toLowerCase(),path:o}},Jq=e=>{if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||Uq.test(e))return!1;let t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t);if(Gq.test(n))return!1;try{return new URL(e,Wq).origin===Wq}catch{return!1}},Yq=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths===!0&&Jq(e);if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return AH(t)(RH(e)||e);let n=BH(e);return n?AH(t)(n):!1}let r=zH(e);if(r===`http:`||r===`https:`||!r)return t===RH(e);let i=qq(e),a=qq(t);return!i||!a||i.scheme!==a.scheme||a.authority&&i.authority!==a.authority?!1:!a.path||i.path===a.path||i.path.startsWith(`${a.path}/`)};function Xq(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function Zq(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function Qq(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let n=new URL(e.context.baseURL).pathname,r=vq(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}const $q=Xq(function(){},`disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.`),eJ=zq(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await nJ(e),Qq(e)))return;let{body:t,query:n}=e,r=t?.callbackURL||n?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,n)=>{if(t){if(typeof t!=`string`)throw E.fromStatus(`BAD_REQUEST`,{message:`Invalid ${n}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:n!==`origin`}))throw e.context.logger.error(`Invalid ${n}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,Y.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,Y.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,Y.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})}};r&&s(r,`callbackURL`),i&&s(i,`redirectURL`),a&&s(a,`errorCallbackURL`),o&&s(o,`newUserCallbackURL`)}),tJ=e=>zq(async t=>{if(!t.request||Qq(t))return;let n=e(t),r=(e,n)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:n!==`origin`}))throw t.context.logger.error(`Invalid ${n}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),n===`origin`?E.from(`FORBIDDEN`,Y.INVALID_ORIGIN):n===`callbackURL`?E.from(`FORBIDDEN`,Y.INVALID_CALLBACK_URL):n===`redirectURL`?E.from(`FORBIDDEN`,Y.INVALID_REDIRECT_URL):n===`errorCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?E.from(`FORBIDDEN`,Y.INVALID_NEW_USER_CALLBACK_URL):E.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})},i=Array.isArray(n)?n:[n];for(let e of i)r(e,`callbackURL`)});async function nJ(e,t=!1){let n=e.request?.headers;if(!n||!e.request)return;let r=n.get(`origin`),i=r||n.get(`referer`)||``,a=n.has(`cookie`);if(e.context.skipCSRFCheck)return;if(Zq(e)){e.context.options.advanced?.disableOriginCheck===!0&&$q();return}if(Qq(e)||!(t||a))return;let o=r===`null`&&n.get(`sec-fetch-site`)===`same-origin`?LH(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(o?RH(o):void 0)??i;if(!s||s===`null`)throw E.from(`FORBIDDEN`,Y.MISSING_OR_NULL_ORIGIN);let c=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!c.some(e=>Yq(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${c}`),E.from(`FORBIDDEN`,Y.INVALID_ORIGIN)}const rJ=zq(async e=>{e.request&&await iJ(e)});async function iJ(e){let t=e.request;if(!t||e.context.skipCSRFCheck||Zq(e))return;let n=t.headers;if(n.has(`cookie`))return await nJ(e);let r=n.get(`Sec-Fetch-Site`),i=n.get(`Sec-Fetch-Mode`),a=n.get(`Sec-Fetch-Dest`);if(r&&r.trim()||i&&i.trim()||a&&a.trim()){if(r===`cross-site`&&i===`navigate`)throw e.context.logger.error(`Blocked cross-site navigation login attempt (CSRF protection)`,{secFetchSite:r,secFetchMode:i,secFetchDest:a}),E.from(`FORBIDDEN`,Y.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await nJ(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await nJ(e,!0)}const aJ=Ie(),oJ=see();function sJ(e){return cJ(e)||lJ(e)}function cJ(e){return Ve(aJ,e)}function lJ(e){return Ve(oJ,e)}function uJ(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(cJ(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&cJ(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=dJ(e);if(t.length===8&&t[0]===`0000`&&t[1]===`0000`&&t[2]===`0000`&&t[3]===`0000`&&t[4]===`0000`&&t[5]===`ffff`&&t[6]&&t[7])return`${Number.parseInt(t[6].substring(0,2),16)}.${Number.parseInt(t[6].substring(2,4),16)}.${Number.parseInt(t[7].substring(0,2),16)}.${Number.parseInt(t[7].substring(2,4),16)}`}return null}function dJ(e){if(e.includes(`::`)){let t=e.split(`::`),n=t[0]?t[0].split(`:`):[],r=t[1]?t[1].split(`:`):[],i=8-n.length-r.length,a=Array(i).fill(`0000`),o=n.map(e=>e.padStart(4,`0`)),s=r.map(e=>e.padStart(4,`0`));return[...o,...a,...s]}return e.split(`:`).map(e=>e.padStart(4,`0`))}function fJ(e,t){let n=dJ(e);if(t!==void 0&&t<128){let e=Math.max(0,Math.floor(t));return n.map(t=>{if(e<=0)return`0000`;if(e>=16)return e-=16,t;let n=Number.parseInt(t,16)&65535<<16-e&65535;return e=0,n.toString(16).padStart(4,`0`)}).join(`:`).toLowerCase()}return n.join(`:`).toLowerCase()}function pJ(e,t={}){if(cJ(e)||!lJ(e))return e.toLowerCase();let n=uJ(e);return n?n.toLowerCase():fJ(e,t.ipv6Subnet??64)}function mJ(e){if(cJ(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!lJ(e))return null;let t=uJ(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=dJ(e),r=/* @__PURE__ */ new Uint8Array(16);for(let e=0;e<8;e++){let t=Number.parseInt(n[e]??`0`,16);r[e*2]=t>>8&255,r[e*2+1]=t&255}return r}const hJ=/^\d+$/;function gJ(e){let t=e.lastIndexOf(`/`),n=mJ(t===-1?e:e.slice(0,t));if(!n)return null;let r=n.length*8;if(t===-1)return{bytes:n,prefix:r};let i=e.slice(t+1);if(!hJ.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function _J(e,t){if(e.length!==t.bytes.length)return!1;let n=t.prefix;for(let r=0;r<e.length&&n>0;r++){let i=n>=8?8:n,a=i===8?255:255<<8-i&255;if(((e[r]??0)&a)!==((t.bytes[r]??0)&a))return!1;n-=8}return!0}function vJ(e){return e.filter(e=>gJ(e)===null)}function yJ(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(gJ).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?mJ(i):null;if(!i||!a)return null;if(!r.some(e=>_J(a,e)))return pJ(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!sJ(i)?null:pJ(i,{ipv6Subnet:t.ipv6Subnet})}const bJ=[`x-forwarded-for`];function xJ(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||bJ;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=yJ(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return Te()||S()?`127.0.0.1`:null}function SJ(e,t){return`${e}|${t}`}const CJ=/* @__PURE__ */ new Map,wJ=1e5;function TJ(){let e=Date.now();for(let[t,n]of CJ)e>=n.expiresAt&&CJ.delete(t);if(CJ.size<=wJ)return;let t=CJ.size-wJ,n=0;for(let e of CJ.keys())if(CJ.delete(e),++n>=t)break}function EJ(e,t,n){let r=t.window*1e3;return e?n-e.lastRequest>=r?{next:{...e,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:OJ(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:{next:{key:``,count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null}}function DJ(e){return new Response(JSON.stringify({message:`Too many requests. Please try again later.`}),{status:429,statusText:`Too Many Requests`,headers:{"Content-Type":`application/json`,"X-Retry-After":e.toString()}})}function OJ(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function kJ(e){let t=`rateLimit`,n=e.adapter,r=Math.max(...AJ(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return typeof r?.lastRequest==`bigint`&&(r.lastRequest=Number(r.lastRequest)),r},a=async(e,s)=>{s.window>r&&(r=s.window);let c=s.window*1e3,l=await i(e),u=Date.now();if(!l)try{return await n.create({model:t,data:{key:e,count:1,lastRequest:u}}),{allowed:!0,retryAfter:null}}catch(t){if(!await i(e))throw t;return a(e,s)}if(u-l.lastRequest>=c)return await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`lte`,value:l.lastRequest}],increment:{},set:{count:1,lastRequest:u}})?(await o(u),{allowed:!0,retryAfter:null}):a(e,s);let d=u-c;if(await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`gt`,value:d},{field:`count`,operator:`lt`,value:s.max}],increment:{count:1},set:{lastRequest:u}}))return{allowed:!0,retryAfter:null};let f=await i(e);return!f||u-f.lastRequest>=c?a(e,s):{allowed:!1,retryAfter:OJ(f.lastRequest,s.window)}},o=async i=>{let a=i-r*1e3;await e.runInBackgroundOrAwait(n.deleteMany({model:t,where:[{field:`lastRequest`,operator:`lt`,value:a}]}).then(()=>void 0).catch(t=>e.logger.error(`Error pruning rate limit rows`,t)))};return{consume:a}}function AJ(e){let t=[e.rateLimit.window,...FJ().map(e=>e.window)];for(let n of e.options.plugins||[])n.rateLimit&&t.push(...n.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let n of Object.values(e.rateLimit.customRules))n&&typeof n!=`function`&&t.push(n.window);let n=t.filter(e=>Number.isFinite(e)&&e>0);return n.length>0?n:[e.rateLimit.window]}function jJ(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let n=e.rateLimit.storage;if(n===`secondary-storage`){let t=t=>t??e.options.rateLimit?.window??10,n=e.options.secondaryStorage?.increment;if(!n)throw new D(`Secondary-storage rate limiting requires SecondaryStorage.increment.`);return{consume:async(e,r)=>await n(e,t(r.window))<=r.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:r.window}}}if(n===`memory`){let t=t=>t??e.options.rateLimit?.window??10;return{async consume(e,n){TJ();let r=Date.now(),i=CJ.get(e),a=EJ(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&CJ.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return kJ(e)}let MJ=!1;async function NJ(e,t){let n=new URL(t.baseURL).pathname,r=vq(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=xJ(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!MJ&&(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),MJ=!0);let s=SJ(o??`no-trusted-ip`,r),c=FJ().find(e=>e.pathMatcher(r));c&&(i=c.window,a=c.max);for(let e of t.options.plugins||[])if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(r));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let n=Object.keys(t.rateLimit.customRules).find(e=>e.includes(`*`)?AH(e)(r):e===r);if(n){let r=t.rateLimit.customRules[n],o=typeof r==`function`?await r(e,{window:i,max:a}):r;if(o&&(i=o.window,a=o.max),o===!1)return null}}return{key:s,currentWindow:i,currentMax:a}}async function PJ(e,t){if(!t.rateLimit.enabled)return;let n=await NJ(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=jJ(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return DJ(l??i)}function FJ(){return[{pathMatcher(e){return e.startsWith(`/sign-in`)||e.startsWith(`/sign-up`)||e.startsWith(`/change-password`)||e.startsWith(`/change-email`)},window:10,max:3},{pathMatcher(e){return e===`/request-password-reset`||e===`/send-verification-email`||e.startsWith(`/forget-password`)||e===`/email-otp/send-verification-otp`||e===`/email-otp/request-password-reset`},window:60,max:3}]}const{get:IJ,set:mfe}=yH(()=>!1),LJ=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:XK,requireHeaders:!0,metadata:{openapi:{operationId:`getSession`,description:`Get the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:[`object`,`null`],properties:{session:{$ref:`#/components/schemas/Session`},user:{$ref:`#/components/schemas/User`}},required:[`session`,`user`]}}}}}}}},async e=>{e.setHeader(`cache-control`,`no-store`),e.setHeader(`pragma`,`no-cache`);let t=e.context.options.session?.deferSessionRefresh,n=e.method===`POST`;if(n&&!t)throw E.from(`METHOD_NOT_ALLOWED`,Y.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let r=e.context.options.session?.cookieCache?.enabled===!0,i=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!i&&r)return null;let a=qK(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=GK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e);t.setCookies(t.clean())}if(!i)return null;let o=r&&!e.query?.disableCookieCache,s=o&&a?await iq(e,a):null;o&&a&&!s&&cq(e,e.context.authCookies.sessionData);let c=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);if(s?.session){let t=s.session,n=t.session.token!==i;if(!n){let r=e.context.options.session?.cookieCache?.version,i=`1`;if(r){if(typeof r==`string`)i=r;else if(typeof r==`function`){let e=r(t.session,t.user);i=e instanceof Promise?await e:e}}n=(t.version||`1`)!==i}if(!n){let e=Date.now(),r=new Date(t.session.expiresAt).getTime();n=s.expiresAt<e||!Number.isFinite(r)||r<e}if(n)cq(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=nG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=eG(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.json({session:n,user:r})}let r=s.expiresAt-Date.now(),i=n.updateAge*1e3,a=await IJ();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await rq(e,n,!1);let r=e.context.authCookies.sessionToken.attributes,i=c?void 0:e.context.sessionConfig.expiresIn;await e.setSignedCookie(e.context.authCookies.sessionToken.name,t.session.token,e.context.secret,{...r,maxAge:i});let a=nG(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=eG(e.context.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)});return e.context.session={session:a,user:o},e.json({session:a,user:o})}let o=nG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=eG(e.context.options,{...t.user,createdAt:new Date(t.user.createdAt),updatedAt:new Date(t.user.updatedAt)});return e.context.session={session:o,user:l},e.json({session:o,user:l})}}let l=await e.context.internalAdapter.findSession(i);if(e.context.session=l,!l||l.session.expiresAt</* @__PURE__ */ new Date)return lq(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=nG(e.context.options,l.session),n=eG(e.context.options,l.user);return e.json({session:t,user:n})}let u=e.context.sessionConfig.expiresIn,d=e.context.sessionConfig.updateAge,f=l.session.expiresAt.valueOf()-u*1e3+d*1e3<=Date.now(),p=e.query?.disableRefresh||e.context.options.session?.disableSessionRefresh,m=await IJ(),h=f&&!p&&!m;if(t&&!n){await rq(e,l,!!c);let t=nG(e.context.options,l.session),n=eG(e.context.options,l.user);return e.json({session:t,user:n,needsRefresh:h})}if(h){let t=await e.context.internalAdapter.updateSession(l.session.token,{expiresAt:uG(e.context.sessionConfig.expiresIn,`sec`),updatedAt:/* @__PURE__ */ new Date});if(!t)throw lq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await aq(e,{session:t,user:l.user},!1,{maxAge:n});let r=nG(e.context.options,t),i=eG(e.context.options,l.user);return e.json({session:r,user:i})}await rq(e,l,!!c);let g=nG(e.context.options,l.session),_=eG(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw Fq(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION))}}),RJ=e=>HW(e.context.options),zJ=async(e,t)=>{if(e.context.session)return e.context.session;let n=await LJ()({...e,method:`GET`,asResponse:!1,headers:e.headers,returnHeaders:!0,returnStatus:!1,query:{...t,...e.query,disableCookieCache:t?.disableCookieCache||e.query?.disableCookieCache,disableRefresh:t?.disableRefresh||e.query?.disableRefresh}}).catch(()=>null);return n?(n.headers&&n.headers.forEach((t,n)=>{let r=n.toLowerCase();r!==`cache-control`&&r!==`pragma`&&(r===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t))}),e.context.session=n.response,n.response):(e.context.session=null,null)},BJ=async e=>RJ(e)?(e.context.session=null,zJ(e,{disableCookieCache:!0})):zJ(e),VJ=zq(async e=>{let t=await zJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),HJ=zq(async e=>{let t=await BJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});zq(async e=>{let t=await zJ(e);if(!t?.session&&(e.request||e.headers))throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});const UJ=zq(async e=>{let t=await zJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});if(e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`FORBIDDEN`,Y.SESSION_NOT_FRESH)}return{session:t}}),WJ=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[UJ],requireHeaders:!0,metadata:{openapi:{operationId:`listUserSessions`,description:`List all active sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{$ref:`#/components/schemas/Session`}}}}}}}}},async e=>{try{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id,{onlyActiveSessions:!0})).filter(e=>e.expiresAt>/* @__PURE__ */ new Date);return e.json(t.map(t=>nG(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),GJ=X(`/revoke-session`,{method:`POST`,body:A({token:k().meta({description:`The token to revoke`})}),use:[HJ],requireHeaders:!0,metadata:{openapi:{description:`Revoke a single session`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,description:`The token to revoke`}},required:[`token`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the session was revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.body.token;if((await e.context.internalAdapter.findSession(t))?.session.userId===e.context.session.user.id)try{await e.context.internalAdapter.deleteSession(t)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),KJ=X(`/revoke-sessions`,{method:`POST`,use:[HJ],requireHeaders:!0,metadata:{openapi:{description:`Revoke all sessions for the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{try{await e.context.internalAdapter.deleteUserSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t&&typeof t==`object`&&`name`in t?t.name:``,t),E.from(`INTERNAL_SERVER_ERROR`,{message:`Internal Server Error`,code:`INTERNAL_SERVER_ERROR`})}return e.json({status:!0})}),qJ=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[HJ],metadata:{openapi:{description:`Revoke all other sessions for the user except the current one`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if all other sessions were revoked successfully`}},required:[`status`]}}}}}}}},async e=>{let t=e.context.session;if(!t.user)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});let n=(await e.context.internalAdapter.listSessions(t.user.id)).filter(e=>e.expiresAt>/* @__PURE__ */ new Date).filter(t=>t.token!==e.context.session.session.token);return await Promise.all(n.map(t=>e.context.internalAdapter.deleteSession(t.token))),e.json({status:!0})});function JJ(e){if(!e?.method)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`User validation source is required`});if(e.method===`oauth`&&!e.oauth?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`OAuth user validation source requires oauth.providerId`});if((e.method===`sso-oidc`||e.method===`sso-saml`)&&!e.sso?.providerId)throw new E(`FORBIDDEN`,{code:`validation_source_missing`,message:`SSO user validation source requires sso.providerId`})}async function YJ(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;JJ(t.source);let r;try{r=await n(t,e)}catch(t){throw e.context.logger.error(`validateUserInfo callback threw`,t),new E(`FORBIDDEN`,{code:`validation_failed`,message:`User validation failed`})}if(r?.error)throw new E(`FORBIDDEN`,{code:r.error,message:r.errorDescription||r.error})}const XJ=async e=>{let t=await MU(`SHA-256`).digest(new TextEncoder().encode(e));return ye.encode(new Uint8Array(t),{padding:!1})};async function ZJ(e,t){return!t||t===`plain`?e:t===`hashed`?XJ(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function QJ(e,t){if(t){if(typeof t==`object`&&`default`in t){if(t.overrides){for(let[n,r]of Object.entries(t.overrides))if(e.startsWith(n))return r}return t.default}return t}}const $J=`better_auth.operation_id`,eY=`better_auth.hook.type`,tY=`better_auth.context`;function nY(e,t){let n=oe(t.options),r=t.hooks;async function i(t,i,a){let o=fH(),s=t;for(let{source:e,hooks:t}of r){let r=t[i]?.create?.before;if(r){let t=await n(`db create.before ${i}`,{[eY]:`create.before`,[ve]:i,[tY]:e},()=>r(s,o));if(t===!1)return null;typeof t==`object`&&`data`in t&&(s={...s,...t.data})}}let c=null;(!a||a.executeMainFn)&&(c=await(await SH(e)).create({model:i,data:s,forceAllowId:!0})),a?.fn&&(c=await a.fn(c??s));for(let{source:e,hooks:t}of r){let r=t[i]?.create?.after;r&&await TH(async()=>{await n(`db create.after ${i}`,{[eY]:`create.after`,[ve]:i,[tY]:e},()=>r(c,o))})}return c}async function a(t,i,a,o){let s=fH(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db update.before ${a}`,{[eY]:`update.before`,[ve]:a,[tY]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await SH(e)).update({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await TH(async()=>{await n(`db update.after ${a}`,{[eY]:`update.after`,[ve]:a,[tY]:e},()=>r(u,s))})}return u}async function o(t,i,a,o){let s=fH(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db updateMany.before ${a}`,{[eY]:`updateMany.before`,[ve]:a,[tY]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await SH(e)).updateMany({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await TH(async()=>{await n(`db updateMany.after ${a}`,{[eY]:`updateMany.after`,[ve]:a,[tY]:e},()=>r(u,s))})}return u}async function s(t,i,a){let o=fH(),s=null;try{s=(await(await SH(e)).findMany({model:i,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":e},()=>r(s,o))===!1)return null}let c=a?await a.fn(t):null,l=(!a||a.executeMainFn)&&s?await(await SH(e)).delete({model:i,where:t}):c;if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.after;r&&await TH(async()=>{await n(`db delete.after ${i}`,{[eY]:`delete.after`,[ve]:i,[tY]:e},()=>r(s,o))})}return l}async function c(t,i,a){let o=fH(),s=[];try{s=await(await SH(e)).findMany({model:i,where:t})}catch{}for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":t},()=>r(e,o))===!1)return null}let c=a?await a.fn(t):null,l=!a||a.executeMainFn?await(await SH(e)).deleteMany({model:i,where:t}):c;for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.after;r&&await TH(async()=>{await n(`db delete.after ${i}`,{[eY]:`delete.after`,[ve]:i,[tY]:t},()=>r(e,o))})}return l}async function l(t,i,a,o){let s=fH(),c=r.flatMap(({source:e,hooks:n})=>{let r=n[t]?.delete?.before;return r?[{source:e,fn:r}]:[]}),l=o??null;if(c.length){if(!l)try{l=(await(await SH(e)).findMany({model:t,where:i,limit:1}))[0]||null}catch{}if(l){for(let{source:e,fn:r}of c)if(await n(`db delete.before ${t}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":t,"better_auth.context":e},()=>r(l,s))===!1)return null}}let u=await a();if(!u)return null;for(let{source:e,hooks:i}of r){let r=i[t]?.delete?.after;r&&await TH(async()=>{await n(`db delete.after ${t}`,{[eY]:`delete.after`,[ve]:t,[tY]:e},()=>r(u,s))})}return u}return{createWithHooks:i,updateWithHooks:a,updateManyWithHooks:o,deleteWithHooks:s,deleteManyWithHooks:c,consumeOneWithHooks:l}}function rY(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}const iY=(e,t)=>{let n=t.logger,r=t.options,i=r.secondaryStorage,a=/* @__PURE__ */ new Map,o=r.session?.expiresIn||604800,s=!!i&&r.session?.storeSessionInDatabase===!0&&r.session?.preserveSessionInDatabase!==!0,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:u,deleteWithHooks:d,deleteManyWithHooks:f,consumeOneWithHooks:p}=nY(e,t),m=t=>{let n=[...t,{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}];return f(n,`session`,{fn:async()=>{await(await SH(e)).updateMany({model:`session`,where:n,update:{expiresAt:/* @__PURE__ */ new Date}})},executeMainFn:!1})};async function h(e){if(!i)return;let t=await i.get(`active-sessions-${e.id}`);if(!t)return;let n=Date.now(),r=(le(t)||[]).filter(e=>e.expiresAt>n);await Promise.all(r.map(async({token:t})=>{let r=await i.get(t);if(!r)return;let a=le(r);if(!a)return;let o=rY(a.session.expiresAt,n);await i.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function g(e){if(!i)return[];let t=await i.get(`active-sessions-${e}`);return t&&le(t)||[]}async function _(e,t){if(!i)return;let n=new Set(t.map(e=>e.token));for(let{token:e}of t)await i.delete(e);let r=`active-sessions-${e}`,a=await g(e),o=Date.now(),s=a.filter(e=>e.expiresAt>o&&!n.has(e.token));s.sort((e,t)=>e.expiresAt-t.expiresAt);let c=s.at(-1)?.expiresAt;c?await i.set(r,JSON.stringify(s),rY(c,o)):await i.delete(r)}async function v(e,t){if(!i)return;let r=t??await g(e);await TH(()=>_(e,r),{onError(e){n.error(`Failed to delete committed user sessions from secondary storage`,e)}})}async function y(e,t){let n=a.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>i);a.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),a.get(e)===o&&a.delete(e)}}return{createOAuthUser:async(t,n)=>wH(e,async()=>{let e=await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...t,email:t.email?.toLowerCase()},`user`,void 0);if(!e)throw new E(`BAD_REQUEST`,{message:`Failed to create user`});return{user:e,account:await c({...n,userId:e.id,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date},`account`,void 0)}}),createUser:async(e,t)=>{let i={createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,email:e.email?.toLowerCase()};if(r.user?.validateUserInfo){let e={...t,action:`create-user`};JJ(e);let r;try{r=pH()}catch(e){throw n.error(`Unable to run validateUserInfo: missing endpoint context`,e),new E(`FORBIDDEN`,{code:`validation_context_missing`,message:`User validation requires an endpoint context`})}await YJ(r,{user:i,source:e})}return await c(i,`user`,void 0)},createAccount:async e=>await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e},`account`,void 0),listSessions:async(n,r)=>{if(s)return(await(await SH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]})).map(e=>nG(t.options,e));if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=le(e)||[],a=Date.now(),o=/* @__PURE__ */ new Set,s=[];for(let{token:e,expiresAt:n}of r){if(n<=a||o.has(e))continue;o.add(e);let r=await i.get(e);if(r)try{let e=typeof r==`string`?JSON.parse(r):r;if(!e?.session)continue;s.push(nG(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await SH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},...r?.onlyActiveSessions?[{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]:[]]})},listUsers:async(t,n,r,i)=>await(await SH(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await SH(e)).count({model:`user`,where:t});return typeof n==`string`?parseInt(n):n},deleteUser:async e=>{let t=await g(e);(!i||r.session?.storeSessionInDatabase)&&await f([{field:`userId`,value:e}],`session`,void 0),await f([{field:`userId`,value:e}],`account`,void 0),await d([{field:`id`,value:e}],`user`,void 0)!==null&&await v(e,t)},createSession:async(a,l,u,d,f)=>{let p=await(async()=>{let e=fH();return e?.headers||e?.request?.headers})(),m=r.session?.storeSessionInDatabase,h=f?.deferSecondaryStorageWrites===!0&&s,{id:g,..._}=u||{},v;if(i&&!m){let e=t.generateId({model:`session`});v=e===!1?pe():e}let y=cG(r),b={...v?{id:v}:{},ipAddress:p&&xJ(p,r)||``,userAgent:p?.get(`user-agent`)||``,..._,expiresAt:uG(l?86400:o,`sec`),userId:a,token:pe(32),createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...y,...d?_:{}},x=async t=>{if(!i)return t;let n=await i.get(`active-sessions-${a}`),r=[],o=Date.now();n&&(r=le(n)||[],r=r.filter(e=>e.expiresAt>o&&e.token!==b.token));let s=[...r,{token:b.token,expiresAt:b.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=rY(s.at(-1)?.expiresAt??b.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await SH(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=rY(b.expiresAt,o);return u>0&&await i.set(b.token,JSON.stringify({session:t,user:l}),u),t};return await c(b,`session`,i?{fn:async e=>h?(await TH(async()=>{await x(e)},{onError(e){n.error(`Failed to mirror committed session to secondary storage`,e)}}),e):x(e),executeMainFn:m}:void 0)},findSession:async n=>{if(i){let e=await i.get(n);if(!e&&(!r.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let n=le(e);return n?{session:nG(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:eG(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await SH(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:nG(t.options,s),user:eG(t.options,o)}:null},findSessions:async(t,n)=>{let r=[...new Set(t)],a=/* @__PURE__ */ new Map,o=[];if(i)for(let e of r){let t=await i.get(e);if(t)try{let r=typeof t==`string`?JSON.parse(t):t;if(!r)continue;let i=new Date(r.session.expiresAt);if(n?.onlyActiveSessions&&i<=/* @__PURE__ */ new Date)continue;let o={session:{...r.session,expiresAt:new Date(r.session.expiresAt)},user:{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)}};a.set(e,o)}catch{continue}else o.push(e)}let c=i?o:r;if(c.length>0&&(!i||s)){let t=await(await SH(e)).findMany({model:`session`,limit:c.length,where:[{field:`token`,value:c,operator:`in`},...n?.onlyActiveSessions?[{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]:[]],join:{user:!0}});for(let{user:e,...n}of t)e&&a.set(n.token,{session:n,user:e})}return r.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,n)=>await l(n,[{field:`token`,value:e}],`session`,i?{async fn(n){let r=await i.get(e);if(!r)return null;let a=le(r);if(!a)return null;let o={...a.session,...n,expiresAt:new Date(n.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(n.updatedAt??a.session.updatedAt)},s=nG(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=rY(l,c);if(u>0){await i.set(e,JSON.stringify({session:s,user:a.user}),u);let t=`active-sessions-${s.userId}`,n=await i.get(t),r=(n&&le(n)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=r.at(-1)?.expiresAt;o&&o>c?await i.set(t,JSON.stringify(r),rY(o,c)):await i.delete(t)}return s},executeMainFn:r.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(i){let a=await i.get(e);if(a){let{session:t}=le(a)??{};if(!t){n.error(`Session not found in secondary storage`);return}let r=t.userId,o=await i.get(`active-sessions-${r}`);if(o){let t=le(o)||[],n=Date.now(),a=t.filter(t=>t.expiresAt>n&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await i.set(`active-sessions-${r}`,JSON.stringify(a),rY(s,n)):await i.delete(`active-sessions-${r}`)}else n.error(`Active sessions list not found in secondary storage`)}if(await i.delete(e),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e}]);return}}await d([{field:`token`,value:e}],`session`,void 0)},deleteAccounts:async e=>{await f([{field:`userId`,value:e}],`account`,void 0)},deleteAccount:async e=>{await d([{field:`id`,value:e}],`account`,void 0)},deleteUserSessions:async e=>{let n=await g(e);if(i){if(!r.session?.storeSessionInDatabase){await v(e,n);return}if(t.options.session?.preserveSessionInDatabase){await m([{field:`userId`,value:e}])!==null&&await v(e,n);return}}await f([{field:`userId`,value:e}],`session`,void 0)!==null&&await v(e,n)},deleteSessions:async e=>{if(i){if(await Promise.all(e.map(e=>i.delete(e))),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e,operator:`in`}]);return}}await f([{field:`token`,value:e,operator:`in`}],`session`,void 0)},findAccountOwnerByKey:async({providerId:t,accountId:n})=>{let r=await(await SH(e)).findMany({model:`account`,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}],limit:2,join:{user:!0}});if(r.length>1)throw new D(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let i=r[0];if(!i)return null;let{user:a,...o}=i;return a?{kind:`owned`,user:a,account:o}:{kind:`orphaned`,account:o}},findUserByEmail:async(t,n)=>{let r=await(await SH(e)).findOne({model:`user`,where:[{value:t.toLowerCase(),field:`email`}],join:{...n?.includeAccounts?{account:!0}:{}}});if(!r)return null;let{account:i,...a}=r;return{user:a,accounts:i??[]}},findUserById:async t=>t?await(await SH(e)).findOne({model:`user`,where:[{field:`id`,value:t}]}):null,linkAccount:async e=>await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e},`account`,void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`id`,value:e}],`user`,void 0);return await TH(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`email`,value:e.toLowerCase()}],`user`,void 0);return await TH(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updatePassword:async(e,t)=>{await u({password:t},[{field:`userId`,value:e},{field:`providerId`,value:`credential`},{field:`accountId`,value:e}],`account`,void 0)},findAccounts:async t=>await(await SH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await SH(e)).findOne({model:`account`,where:[{field:`userId`,value:t},{field:`providerId`,value:`credential`},{field:`accountId`,value:t}]}),findAccountByKey:async({providerId:t,accountId:n})=>{let r=await(await SH(e)).findMany({model:`account`,limit:2,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}]});if(r.length>1)throw new D(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return r[0]??null},findAccountByUserId:async t=>await(await SH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:`id`,value:e}],`account`,void 0),createVerificationValue:async e=>{let t=QJ(e.identifier,r.verification?.storeIdentifier),n=await ZJ(e.identifier,t);return await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=rY(e.expiresAt);return t>0&&await i.set(`verification:${n}`,JSON.stringify(e),t),e},executeMainFn:r.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let n=QJ(t,r.verification?.storeIdentifier),a=await ZJ(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=le(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=le(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await SH(e);async function s(e){return o.findMany({model:`verification`,where:[{field:`identifier`,value:e}],sortBy:{field:`createdAt`,direction:`desc`},limit:1})}let c=await s(a);return!c.length&&n&&n!==`plain`&&(c=await s(t)),r.verification?.disableCleanup||await f([{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`lt`}],`verification`,void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await ZJ(e,QJ(e,r.verification?.storeIdentifier));i&&await i.delete(`verification:${t}`),(!i||r.verification?.storeInDatabase)&&await d([{field:`identifier`,value:t}],`verification`,void 0)},consumeVerificationValue:async t=>{let n=QJ(t,r.verification?.storeIdentifier),a=await ZJ(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?le(e):typeof e==`object`?e:null;if(!t)return null;let n=new Date(t.expiresAt);return Number.isFinite(n.getTime())?{...t,expiresAt:n}:null},c=null;if(i&&!r.verification?.storeInDatabase){let e=async e=>s(await i.getAndDelete(e));for(let t of o){let n=await e(`verification:${t}`);if(n){await Promise.all(o.filter(e=>e!==t).map(e=>i.delete(`verification:${e}`))),c=n;break}}}else{let t=async t=>y(`verification:${t}`,()=>wH(e,async()=>{let n=await SH(e),r=[{field:`identifier`,value:t}],i=(await n.findMany({model:`verification`,where:r,sortBy:{field:`createdAt`,direction:`desc`},limit:1}))[0]??null;return i?p(`verification`,[{field:`id`,value:i.id}],async()=>{let e=await n.consumeOne({model:`verification`,where:[{field:`id`,value:i.id}]});return e?(await n.deleteMany({model:`verification`,where:r}),e):null},i):null}));for(let e of o)if(c=await t(e),c)break;c&&i&&await Promise.all(o.map(e=>i.delete(`verification:${e}`)))}return!c||c.expiresAt</* @__PURE__ */ new Date?null:c},reserveVerificationValue:async t=>{let n=xe(new Uint8Array(await MU(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),r),a=QJ(t.identifier,r.verification?.storeIdentifier),o=await ZJ(t.identifier,a);if(i&&!r.verification?.storeInDatabase)throw new D(`reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.`);try{await e.create({model:`verification`,data:{id:n,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:`verification`,where:[{field:`id`,value:n}]}))return!1;throw t}if(i){let e=rY(t.expiresAt);e>0&&await i.set(`verification:${o}`,JSON.stringify({id:n,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let n=await ZJ(e,QJ(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=le(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=rY(o instanceof Date?o:new Date(o));if(s>0&&await i.set(`verification:${n}`,JSON.stringify(e),s),!r.verification?.storeInDatabase)return e}}}return!i||r.verification?.storeInDatabase?await l(t,[{field:`identifier`,value:n}],`verification`,void 0):t},refreshUserSessions:h}};function aY(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function oY(e,t,n=`.`,r){if(!aY(t))return oY(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:aY(a)&&aY(i[t])?oY(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function sY(e){return(...t)=>t.reduce((t,n)=>oY(t,n,``,e),{})}const cY=sY(),lY=/* @__PURE__ */ new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function uY(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function dY(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t===-1?e:e.slice(0,t+1)}let t=e.indexOf(`:`);return t===-1||e.indexOf(`:`,t+1)!==-1?e:e.slice(0,t)}function fY(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function pY(e){return e.replace(/\.+$/,``)}function mY(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function hY(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function gY(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function _Y(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=hY(e);return gY(t,hY(`127.0.0.0`),8)?`loopback`:gY(t,hY(`10.0.0.0`),8)||gY(t,hY(`172.16.0.0`),12)||gY(t,hY(`192.168.0.0`),16)?`private`:gY(t,hY(`169.254.0.0`),16)?`linkLocal`:gY(t,hY(`100.64.0.0`),10)?`sharedAddressSpace`:gY(t,hY(`192.0.2.0`),24)||gY(t,hY(`198.51.100.0`),24)||gY(t,hY(`203.0.113.0`),24)?`documentation`:gY(t,hY(`198.18.0.0`),15)?`benchmarking`:gY(t,hY(`224.0.0.0`),4)?`multicast`:gY(t,hY(`0.0.0.0`),8)||gY(t,hY(`192.0.0.0`),24)||gY(t,hY(`192.88.99.0`),24)||gY(t,hY(`240.0.0.0`),4)?`reserved`:`public`}function vY(e,t,n={}){let r=t*5,i=Number.parseInt(e.slice(r,r+4),16),a=Number.parseInt(e.slice(r+5,r+9),16);if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=(i<<16|a)>>>0;return n.xor&&(o=(o^4294967295)>>>0),`${o>>>24&255}.${o>>>16&255}.${o>>>8&255}.${o&255}`}function yY(e){if(e===`0000:0000:0000:0000:0000:0000:0000:0000`)return`unspecified`;if(e===`0000:0000:0000:0000:0000:0000:0000:0001`)return`loopback`;let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16);if(t===255)return`multicast`;if(t===254&&(n&192)==128)return`linkLocal`;if(t===254&&(n&192)==192)return`reserved`;if((t&254)==252)return`private`;if(e.startsWith(`2001:0db8:`))return`documentation`;if(e.startsWith(`2001:0002:0000:`))return`benchmarking`;if(e.startsWith(`2002:`)){let t=vY(e,1);return t&&_Y(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=vY(e,6);return t&&_Y(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=vY(e,6,{xor:!0});return t&&_Y(t),`reserved`}return e.startsWith(`0100:0000:0000:0000:`)?`reserved`:e.startsWith(`3fff:0`)?`documentation`:e.startsWith(`5f00:`)||e.startsWith(`0000:0000:0000:0000:0000:0000:`)?`reserved`:`public`}function bY(e){let t=pY(fY(uY(dY(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!sJ(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:lY.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(mY(t))return{kind:_Y(t),literal:`ipv4`,canonical:t};let n=pJ(t,{ipv6Subnet:128});return mY(n)?{kind:_Y(n),literal:`ipv4`,canonical:n}:{kind:yY(n),literal:`ipv6`,canonical:n}}function xY(e){return bY(e).kind===`loopback`}function SY(e){let t=bY(e).kind;return t===`loopback`||t===`localhost`}function CY(e){return bY(e).kind===`public`}async function wY(e){let t=e.options,n=t.plugins||[],r=[],i=[];for(let a of n)if(a.init){let n=a.init(e),o;if(o=dG(n)?await n:n,typeof o==`object`){if(o.options){let{databaseHooks:e,trustedOrigins:n,...s}=o.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),n&&r.push(n),t=cY(t,s)}o.context&&Object.assign(e,o.context)}}if(r.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...r],n=e.filter(Array.isArray).flat(),i=e.filter(e=>typeof e==`function`);i.length>0?t.trustedOrigins=async e=>{let t=await Promise.all(i.map(t=>t(e)));return[...n,...t.flat()].filter(e=>typeof e==`string`&&e!==``)}:t.trustedOrigins=n}t.databaseHooks&&i.push({source:`user`,hooks:t.databaseHooks}),e.internalAdapter=iY(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function TY(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function EY(e,t){let n=[];if(VH(e.baseURL)){let t=e.baseURL.allowedHosts,r=e.baseURL.protocol;for(let e of t)e.includes(`://`)?n.push(e):((!r||r===`https`||r===`auto`)&&n.push(`https://${e}`),(r===`http`||r===`auto`||SY(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=LH(typeof e.baseURL==`string`?e.baseURL:void 0,e.basePath,t);r&&n.push(new URL(r).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&n.push(...e.trustedOrigins),typeof e.trustedOrigins==`function`)){let r=await e.trustedOrigins(t);n.push(...r)}let r=C.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function DY(e){if(HH(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has(`host`)||t.has(`x-forwarded-host`))return t}function OY(e){return e.advanced?.trustedProxyHeaders??!1}async function kY(e,t,n){let r=e.options.baseURL,i=qH(r,e.options.basePath||`/api/auth`,t,void 0,n);if(!i)throw new D(`Could not resolve base URL from request. Check your allowedHosts config.`);let a=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));a.baseURL=i,a.options={...e.options,baseURL:RH(i)||void 0};let o={...a.options,baseURL:r},s=typeof e.options.trustedOrigins==`function`||typeof e.options.account?.accountLinking?.trustedProviders==`function`,c;return c=s?HH(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await EY(o,c),a.trustedProviders=await jY(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=nq(a.options),a.createAuthCookie=tq(a.options)),a}async function AY(e,t){if(e)for(let n of e){let e=typeof n==`function`?await n():n;if(e[t.field??`id`]===t.value)return e}}async function jY(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function MY(e){return e}async function NY(e,t,n){let r={tokens:t,profile:n},i=e.accountSubject,a=await i(r),o=String(a);if(typeof a==`number`&&!Number.isFinite(a)||o.trim().length===0||o===`undefined`||o===`null`)throw new D(`OAUTH_ACCOUNT_SUBJECT_INVALID`);return{providerId:e.id,accountId:o}}async function PY(e,t,n){try{return await NY(e,t,n)}catch{throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO)}}function FY(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function IY(e,t){return e&&(t.options.account?.encryptOAuthTokens&&FY(e)?zW({key:t.secretConfig,data:e}):e)}function LY(e,t){return t.options.account?.encryptOAuthTokens&&e?RW({key:t.secretConfig,data:e}):e}function RY(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function zY(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}async function BY(e,t,n,r=3600,i){return await pU({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function VY(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,Y.VERIFICATION_EMAIL_NOT_ENABLED);let n=await BY(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:n},e.request)}const HY=X(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:A({email:Fe().meta({description:`The email to send the verification email to`}),callbackURL:k().meta({description:`The URL to use for email verification callback`}).optional()}),metadata:{openapi:{operationId:`sendVerificationEmail`,description:`Send a verification email to the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{email:{type:`string`,description:`The email to send the verification email to`,example:`user@example.com`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`,example:`https://example.com/callback`,nullable:!0}},required:[`email`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the email was sent successfully`,example:!0}}}}}},400:{description:`Bad Request`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`,description:`Error message`,example:`Verification email isn't enabled`}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),E.from(`BAD_REQUEST`,Y.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,n=await zJ(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await BY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await VY(e,r.user)}catch(e){i=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),i)throw i;return e.json({status:!0})}if(n?.user.email.toLowerCase()!==t.toLowerCase())throw E.from(`BAD_REQUEST`,Y.EMAIL_MISMATCH);if(n?.user.emailVerified)throw E.from(`BAD_REQUEST`,Y.EMAIL_ALREADY_VERIFIED);return await VY(e,n.user),e.json({status:!0})}),UY=X(`/verify-email`,{method:`GET`,operationId:`verifyEmail`,query:A({token:k().meta({description:`The token to verify the email`}),callbackURL:k().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[tJ(e=>e.query.callbackURL)],metadata:{openapi:{description:`Verify the email of the user`,parameters:[{name:`token`,in:`query`,description:`The token to verify the email`,required:!0,schema:{type:`string`}},{name:`callbackURL`,in:`query`,description:`The URL to redirect to after email verification`,required:!1,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the email was verified successfully`}},required:[`user`,`status`]}}}}}}}},async e=>{function t(t){if(e.query.callbackURL){let n=new URLSearchParams({error:t.code}),r=bq(e.query.callbackURL,n);throw e.redirect(r)}throw E.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await nI(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof iP?t(Y.TOKEN_EXPIRED):t(Y.INVALID_TOKEN)}let i=A({email:Fe(),updateTo:k().optional(),requestType:k().optional()}).parse(r.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t(Y.USER_NOT_FOUND);if(i.updateTo){let n=await zJ(e);if(n&&n.user.email!==i.email)return t(Y.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await BY(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:r,token:t},zY(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case`change-email-verification`:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(r,e.request),await aq(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:eG(e.context.options,r)})}default:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await BY(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},zY(e.request))),await aq(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:eG(e.context.options,r)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await zJ(e);if(!t||t.user.email!==i.email){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_CREATE_SESSION);await aq(e,{session:t,user:{...a.user,emailVerified:!0}})}else await aq(e,{session:t.session,user:{...t.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function WY(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.trim().split(/\s+/).filter(Boolean):[]}function GY(e){let t=e=>new Date((/* @__PURE__ */ new Date()).getTime()+e*1e3);return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?t(e.expires_in):void 0,refreshTokenExpiresAt:e.refresh_token_expires_in?t(e.refresh_token_expires_in):void 0,scopes:WY(e.scope),idToken:e.id_token,raw:e}}function KY(e,t){let n=e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[],r=(t??[]).map(e=>e.trim()).filter(Boolean);return[.../* @__PURE__ */ new Set([...n,...r])].join(`,`)}function qY(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function JY(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return ye.encode(new Uint8Array(n),{padding:!1})}const YY=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],XY=new Set(YY);async function ZY({id:e,options:t,authorizationEndpoint:n,state:r,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:u,responseType:d,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:_,scopeJoiner:v}){t=typeof t==`function`?await t():t;let y=new URL(t.authorizationEndpoint||n);y.searchParams.set(`response_type`,d||`code`);let b=qY(t.clientId);if(!b)throw Error(`OAuth provider requires clientId`);if(y.searchParams.set(`client_id`,b),y.searchParams.set(`state`,r),a?.length&&y.searchParams.set(`scope`,a.join(v||` `)),y.searchParams.set(`redirect_uri`,t.redirectURI||s),c&&y.searchParams.set(`duration`,c),f&&y.searchParams.set(`display`,f),p&&y.searchParams.set(`login_hint`,p),m&&y.searchParams.set(`nonce`,m),l&&y.searchParams.set(`prompt`,l),h&&y.searchParams.set(`hd`,h),u&&y.searchParams.set(`access_type`,u),g&&y.searchParams.set(`response_mode`,g),i){let e=await JY(i);y.searchParams.set(`code_challenge_method`,`S256`),y.searchParams.set(`code_challenge`,e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});y.searchParams.set(`claims`,JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(_)for(let[e,t]of Object.entries(_))XY.has(e)||y.searchParams.set(e,t);return y}const QY=Ne(k(),k()).refine(e=>!Object.keys(e).some(e=>XY.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${YY.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional(),$Y=/^Basic +(.*)$/i;function eX(e){return new URLSearchParams({v:e}).toString().slice(2)}function tX(e){let t=new URLSearchParams(`v=${e}`).get(`v`);if(t===null)throw Error(`form-url-encoded value could not be decoded`);return t}function nX(e,t){let n=`${eX(e)}:${eX(t)}`;return`Basic ${ue.encode(n)}`}function rX(e){let t=e.match($Y);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(ue.decode(n)),i=r.indexOf(`:`);if(i===-1)throw Error(`Basic credential is missing the client id/secret separator`);let a=r.slice(0,i),o=r.slice(i+1);if(!a||!o)throw Error(`Basic credential client id and secret must both be non-empty`);return{clientId:tX(a),clientSecret:tX(o)}}const iX=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`];async function aX({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`}}var oX=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}};const sX=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}};var cX=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},lX=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function uX(e){if(typeof e==`number`)return new cX({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new cX(e);case`exponential`:return new lX(e);default:throw Error(`Invalid retry strategy`)}}const dX=[`get`,`post`,`put`,`patch`,`delete`];function fX(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return dX.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}const pX=e=>e===`.`||e===`..`,mX=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function hX(e,t){let n=t.get(e);if(n===void 0)return mX(e);if(pX(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function gX(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=fX(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=/* @__PURE__ */ new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>hX(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}const _X=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},vX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function yX(e){let t=e.headers.get(`content-type`),n=/* @__PURE__ */ new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return vX.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function bX(e){try{return JSON.parse(e),!0}catch{return!1}}function xX(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function SX(e){try{return JSON.parse(e)}catch{return e}}function CX(e){return typeof e==`function`}function wX(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&CX(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&CX(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function TX(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function EX(e){let t=new Headers(TX(e?.headers,await _X(e)));if(!t.has(`content-type`)){let n=DX(e?.body);n&&t.set(`content-type`,n)}return t}function DX(e){return xX(e)?`application/json`:null}function OX(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function kX(e,t){let{body:n}=e;return n?!xX(n)||typeof n==`string`?n:OX(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function AX(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=fX(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function jX(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var MX=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function NX(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new MX(n.issues);return n.value}function PX(e){"@babel/helpers - typeof";return PX=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},PX(e)}function FX(e,t){if(PX(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(PX(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function IX(e){var t=FX(e,`string`);return PX(t)==`symbol`?t:t+``}function LX(e,t,n){return(t=IX(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RX(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function zX(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?RX(Object(n),!0).forEach(function(t){LX(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):RX(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const BX=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await sX(e,t),o=wX(a),s=new AbortController,c=a.signal??s.signal,l=gX(i,a),u=await EX(a),d=kX(a,u),f=AX(i,a),p=zX(zX({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=jX(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(zX(zX({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=yX(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??SX)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await NX(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(zX(zX({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??SX,b=await h.text(),x=bX(b),S=x?await y(b):null,ee={response:h,responseText:b,request:p,error:zX(zX({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var C;await e(zX(zX({},ee),{},{response:t!=null&&(C=t.hookOptions)!=null&&C.cloneResponse?h.clone():h}))}if(t?.retry){let n=uX(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await BX(e,zX(zX({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new oX(h.status,h.statusText,x?S:b);return{data:null,error:zX(zX({},S),{},{status:h.status,statusText:h.statusText})}},VX=/* @__PURE__ */ new Set([301,302,303,307,308]);function HX(e){return e.type===`opaqueredirect`||VX.has(e.status)}function UX(e){return new D(`The OAuth endpoint "${e}" returned an HTTP redirect. Server-side OAuth fetches refuse redirects to prevent SSRF; configure the final endpoint URL.`)}const WX={redirect:`manual`};async function GX(e,t){let n=!1,r=t?.onError,i=await BX(e,{...t,...WX,async onError(e){HX(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?UX(e):t});if(n)throw UX(e);return i}function KX(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function qX(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function JX(e,t){t&&e.set(`client_id`,t)}function YX(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function XX(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function ZX({body:e,options:t,clientId:n,requireClientSecret:r}){r&&YX(`client_secret_post`,t),t.clientSecret&&(XX(`client_secret_post`,n),JX(e,n),e.set(`client_secret`,t.clientSecret))}function QX({headers:e,options:t,clientId:n,body:r}){if(r.has(`client_secret`))throw Error(`client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters`);YX(`client_secret_basic`,t),XX(`client_secret_basic`,n),e.authorization=nX(n,t.clientSecret)}function $X(e){if(e.has(`client_assertion`)!==e.has(`client_assertion_type`))throw Error(`client_assertion and client_assertion_type must both be provided`)}async function eZ({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){$X(e);let s=qY(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);qX(`private_key_jwt`,n,e),JX(e,s);return}let c=a??KX(n,o);if(c.method===`custom`)await c.customizeRequest({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i}),$X(e);else if(c.method===`private_key_jwt`){if(qX(c.method,n,e),XX(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await aX({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});JX(e,s);for(let[n,r]of Object.entries(t))e.set(n,r)}else if(c.method===`none`){if(qX(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);XX(c.method,s),JX(e,s)}else c.method===`client_secret_basic`?QX({headers:t,options:n,clientId:s,body:e}):ZX({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}const tZ=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],nZ=/* @__PURE__ */ new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function rZ(e){return{reserve:({key:t,expiresAt:n})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:n})}}function iZ(e,t){return Object.assign(Error(t),{code:e})}function aZ(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function oZ(e){if(!e)return;let t=e.trim();if(!t)return;let n=/^([A-Za-z][A-Za-z0-9!#$%&'*+.^_`|~-]*)\s+(.+)$/.exec(t);if(!n)return{scheme:`Unknown`,token:t};let r=n[1]??``,i=n[2]?.trim()??``;return r.toLowerCase()===`bearer`?{scheme:`Bearer`,token:i}:r.toLowerCase()===`dpop`?{scheme:`DPoP`,token:i}:{scheme:`Unknown`,token:t}}function sZ(e){return oZ(e)?.token??e}function cZ(e){let t=new URL(e);if(t.hash)throw Error(`DPoP proof htu must not contain a fragment`);return`${t.origin}${t.pathname}`}async function lZ(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return _P(new Uint8Array(t))}async function uZ(e){return lI(e,`sha256`)}function dZ(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.jkt;return typeof t==`string`&&t.length>0?t:void 0}function fZ(e){return dZ(e.cnf)}function pZ(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function mZ(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function hZ(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw iZ(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw iZ(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function gZ(e){if(!e||typeof e!=`object`||Array.isArray(e))throw iZ(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw iZ(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of nZ)if(t in e)throw iZ(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function _Z(e){let t=`${e.jkt}\n${e.htm}\n${e.htu}\n${e.jti}`,n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t));return _P(new Uint8Array(n))}async function vZ(e,t){if(e&&!await e.reserve(t))throw iZ(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function yZ({proofJwt:e,method:t,url:n,accessToken:r,expectedJkt:i,requireAth:a=!1,nowSeconds:o=Math.floor(Date.now()/1e3),proofMaxAgeSeconds:s=300,signingAlgorithms:c=tZ,replayStore:l}){if(!e||e.split(`.`).length!==3)throw iZ(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=gI(e)}catch(e){throw iZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw iZ(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);hZ(u.alg,c),gZ(u.jwk);let d;try{d=(await nI(e,await hI(u.jwk,u.alg),{typ:`dpop+jwt`})).payload}catch(e){throw iZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=pZ(d,`htm`),p=pZ(d,`htu`),m=pZ(d,`jti`),h=mZ(d,`iat`);if(!f||!p||!m||h===void 0)throw iZ(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>512)throw iZ(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw iZ(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=cZ(n),_=cZ(p)}catch(e){throw iZ(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw iZ(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw iZ(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=pZ(d,`ath`);if(a&&!v)throw iZ(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await lZ(r))throw iZ(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await uZ(u.jwk);if(i!==void 0&&y!==i)throw iZ(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await _Z({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=/* @__PURE__ */ new Date((h+s)*1e3);return await vZ(l,{key:b,expiresAt:x,now:/* @__PURE__ */ new Date(o*1e3)}),{jwk:u.jwk,jkt:y,jti:m,htm:f,htu:g,iat:h,ath:v,replayKey:b,expiresAt:x}}function bZ(e,t){return Object.assign(Error(t),{code:e})}function xZ(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function SZ({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=fZ(e);if(c){if(t.scheme!==`DPoP`)throw bZ(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw bZ(`invalid_dpop_proof`,`DPoP proof header is required`);try{await yZ({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw aZ(e)?bZ(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw bZ(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}const CZ=/* @__PURE__ */ new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function wZ({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=EZ({refreshToken:e,options:t,extraParams:a,resource:o});return await eZ({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function TZ(e,t){if(t)for(let[n,r]of Object.entries(t))CZ.has(n)||e.set(n,r)}function EZ({refreshToken:e,options:t,extraParams:n,resource:r}){let i=new URLSearchParams,a={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`};if(i.set(`grant_type`,`refresh_token`),i.set(`refresh_token`,e),r){if(typeof r==`string`)i.append(`resource`,r);else for(let e of r)i.append(`resource`,e)}return n&&TZ(i,n),{body:i,headers:a}}async function DZ({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await wZ({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await GX(n,{method:`POST`,body:s,headers:c});if(u)throw u;let d={accessToken:l.access_token,refreshToken:l.refresh_token,tokenType:l.token_type,scopes:WY(l.scope),idToken:l.id_token};return l.expires_in&&(d.accessTokenExpiresAt=new Date((/* @__PURE__ */ new Date()).getTime()+l.expires_in*1e3)),l.refresh_token_expires_in&&(d.refreshTokenExpiresAt=new Date((/* @__PURE__ */ new Date()).getTime()+l.refresh_token_expires_in*1e3)),d}async function OZ({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:i,tokenEndpointAuth:a,tokenEndpoint:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){r=typeof r==`function`?await r():r;let d=kZ({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await eZ({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function kZ({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:i,headers:a,additionalParams:o={},resource:s}){let c=new URLSearchParams,l={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`,...a};if(c.set(`grant_type`,`authorization_code`),c.set(`code`,e),t&&c.set(`code_verifier`,t),r.clientKey&&c.set(`client_key`,r.clientKey),i&&c.set(`device_id`,i),c.set(`redirect_uri`,r.redirectURI||n),s){if(typeof s==`string`)c.append(`resource`,s);else for(let e of s)c.append(`resource`,e)}for(let[e,t]of Object.entries(o))c.has(e)||c.append(e,t);return{body:c,headers:l}}async function AZ({code:e,codeVerifier:t,redirectURI:n,options:r,tokenEndpoint:i,authentication:a,tokenEndpointAuth:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){let{body:d,headers:f}=await OZ({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:a,tokenEndpointAuth:o,tokenEndpoint:i,deviceId:s,headers:c,additionalParams:l,resource:u}),{data:p,error:m}=await GX(i,{method:`POST`,body:d,headers:f});if(m)throw m;return GY(p)}hP.code,fP.code,mP.code;const jZ=/* @__PURE__ */ new Map,MZ=/* @__PURE__ */ new WeakMap,NZ=5e3;function PZ(e,t){let n=e.get(t);return n||(n={fetchedAt:0,refetchedAt:0},e.set(t,n)),n}function FZ(e,t){return e.pending!==void 0&&t-e.pending.startedAt<NZ}async function IZ(e,t){let n=Date.now();if(!e.pending||!FZ(e,n)){let r={startedAt:n,promise:RZ(t).then(t=>(n>=e.fetchedAt&&(e.jwks=t,e.fetchedAt=n),t)).finally(()=>{e.pending===r&&(e.pending=void 0)})};e.pending=r}let{promise:r,startedAt:i}=e.pending,a;try{return await Promise.race([r,new Promise((e,t)=>{a=setTimeout(()=>t(new hP),i+NZ-n)})])}finally{clearTimeout(a)}}async function LZ(e,t,n){if(e.jwks!==t)return e.jwks;let r=Date.now();if(!FZ(e,r)){if(r-e.refetchedAt<3e4)return;e.refetchedAt=r}return IZ(e,n)}async function RZ(e){try{let t=typeof e==`string`?await GX(e,{headers:{Accept:`application/json`}}).then(async e=>{if(e.error)throw Error(`Jwks failed: ${e.error.message??e.error.statusText}`);return e.data}):await e();if(!t)throw Error(`No jwks found`);return t}catch(e){if(e instanceof TypeError){try{f.error(`JWKS fetch failed:`,e)}catch{}throw Error(`JWKS fetch failed`)}throw e}}async function zZ(e,t){return(await BZ(e,t)).jwks}async function BZ(e,t){let n;try{n=gI(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid,i=typeof t.jwksFetch==`string`?PZ(jZ,t.jwksFetch):t.jwksCacheKey?PZ(MZ,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},a=Date.now()-i.fetchedAt<3e5?i.jwks:void 0;if(!a)return{jwks:await IZ(i,t.jwksFetch),kid:r};let o=e=>LZ(i,e,t.jwksFetch);return!r||a.keys.some(e=>e.kid===r)?{jwks:a,kid:r,refresh:o}:{jwks:await o(a)??a,kid:r}}async function VZ(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function HZ(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await VZ(t):!1}function UZ(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function WZ(e,t,n,r){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,n,r);let a=e.idToken;if(!a)return!1;if(`verify`in a)return await a.verify(t,n,r);if(t.split(`.`).length!==3)return a.allowOpaqueToken===!0;let{alg:o}=gI(t),{payload:s}=await nI(t,a.jwks,{issuer:a.issuer,audience:a.audience,algorithms:a.algorithms??(o?[o]:void 0),maxTokenAge:a.maxTokenAge,clockTolerance:30});return!(n&&!await HZ(s.nonce,n,a.nonceComparison)||a.verifyClaims&&!a.verifyClaims(s))}catch{return!1}}function GZ(e,t){return{linked:!1,error:{code:e,message:t}}}async function hfe(e,{link:t,userInfo:n,account:r,profile:i,scopes:a}){try{await YJ(e,{user:{...n,id:t.userId,email:n.email??void 0},source:{action:`link-account`,method:`oauth`,oauth:{providerId:r.providerId,profile:i}}})}catch(e){if(!Fq(e)||!e.body?.code)throw e;return GZ(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(r.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error(`Unable to link account - untrusted provider`),GZ(Sq.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return GZ(Sq.EMAIL_DOES_NOT_MATCH);let o=await e.context.internalAdapter.findAccountByKey(r);if(o){if(o.userId.toString()!==t.userId.toString())return GZ(Sq.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=KY(o.scope,a),i=Object.fromEntries(Object.entries({providerId:r.providerId,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:n||void 0}).filter(([e,t])=>t!==void 0));await e.context.internalAdapter.updateAccount(o.id,i)}else if(!await e.context.internalAdapter.createAccount({userId:t.userId,...r,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),scope:a?.join(`,`)??r.scope}))return GZ(Sq.UNABLE_TO_LINK_ACCOUNT);return await JZ(e,t.userId,n),{linked:!0}}async function KZ(e,t){let{userInfo:n,account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=t.source??{method:`oauth`,oauth:{providerId:r.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,l=null,u=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error(`Better auth was unable to query your database.
60
+ Error: `,t),Cq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)});if(u?.kind===`orphaned`)return e.context.logger.error(`OAuth account references a missing user. Repair the account before retrying authentication.`),{error:`unable to link account`,data:null,isRegister:!1};let d=await(async()=>{if(u?.kind===`owned`){if(t.selectedUser&&u.user.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`account_ownership_conflict`,message:`Account is already linked to another user`});return{user:u.user,linkedAccount:u.account,accounts:[u.account]}}if(t.selectedUser){let n=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!n)throw new E(`NOT_FOUND`,{code:`user_not_found`,message:`User not found`});return{user:n,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if(Fq(t))throw t;e.context.logger.error(`Better auth was unable to query your database.
61
+ Error: `,t),Cq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)}),f=d?.user,p=!f;if(d){let i=d.linkedAccount??d.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await YJ(e,{user:{...o,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`sign-in`}});let u=e.context.options.account?.updateAccountOnSignIn===!1?{}:Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>t!==void 0));if(e.context.options.account?.storeAccountCookie){let n={...i,...u};t.deferNonDatabaseWrites?l=n:await JK(e,n)}if(Object.keys(u).length>0){let n=await e.context.internalAdapter.updateAccount(i.id,u);if(!n)return{error:`unable to update account`,data:null};if(c&&(n.accountId!==r.accountId||n.providerId!==r.providerId||n.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});t.deferNonDatabaseWrites&&l&&(l=n)}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||t.trustProviderByName!==!1&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!d.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return S()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:`account not linked`,data:null};try{let{id:i,...a}=n;await YJ(e,{user:{...a,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`link-account`}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:d.user.id,accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:`unable to link account`,data:null};if(c&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==d.user.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=o:await JK(e,o))}catch(t){if(Fq(t))throw t;return e.context.logger.error(`Unable to link account`,t),{error:`unable to link account`,data:null}}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0}),t.selectedUser||(f=await JZ(e,d.user.id,n)??f)}if(t.selectedUser?t.selectedUser.profile===`update`:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...c}=n,l=oG(e.context.options,c,`update`),u=await e.context.internalAdapter.updateUser(d.user.id,{name:o,image:s,...l,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===d.user.email&&d.user.emailVerified||n.emailVerified});if(u??e.context.logger.warn(`Could not update user info during OAuth sign in; preserving existing user for session.`),t.selectedUser&&u&&u.id!==t.selectedUser.userId)throw new E(`CONFLICT`,{code:`user_hook_selection_conflict`,message:`User hook changed the selected user`});f=u??f}}else{if(a)return{error:`signup disabled`,data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:u,image:d,...p}=n,m=oG(e.context.options,p,`create`),h={accessToken:await LY(r.accessToken,e.context),refreshToken:await LY(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},{createdUser:g,createdAccount:_}=await wH(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:u,image:d,...m,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...h,userId:t.id})}});if(c&&(_.accountId!==r.accountId||_.providerId!==r.providerId||_.userId!==g.id))throw new E(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});f=g,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=_:await JK(e,_))}catch(t){if(Fq(t))throw t;return e.context.logger.error(`Unable to create OAuth user`,t),{error:`unable to create user`,data:null,isRegister:!1}}}if(!f)return{error:`unable to create user`,data:null,isRegister:!1};let m=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(p&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??m)&&await qZ(e,f,i,t.deferNonDatabaseWrites),m&&!f.emailVerified)return!p&&e.context.options.emailVerification?.sendOnSignIn&&await qZ(e,f,i,t.deferNonDatabaseWrites),{error:Sq.EMAIL_NOT_VERIFIED,data:null,isRegister:p};let h=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:t.deferNonDatabaseWrites===!0});if(!h)return{error:`unable to create session`,data:null,isRegister:!1};if(c&&h.userId!==(t.selectedUser?.userId??f.id))throw new E(`CONFLICT`,{code:`session_hook_user_conflict`,message:`Session hook changed the selected user`});return{data:{session:h,user:f},error:null,isRegister:p,accountCookie:l}}async function qZ(e,t,n,r){let i=e.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let a=async()=>{try{let r=await BY(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),a=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${encodeURIComponent(n||`/`)}`;await e.context.runInBackgroundOrAwait(i({user:t,url:a,token:r},e.request))}catch(t){e.context.logger.error(`Failed to send OAuth verification email`,t)}};r?await TH(a):await a()}async function JZ(e,t,n){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:r,emailVerified:i,name:a,image:o,...s}=n,c=oG(e.context.options,s,`update`);return await e.context.internalAdapter.updateUser(t,{name:a,image:o,...c})}catch(t){e.context.logger.warn(`Could not update user info on account link`,t);return}}const gfe=e=>{let t=`https://appleid.apple.com/auth/token`;return{id:`apple`,name:`Apple`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i,codeVerifier:a}){if(!qY(e.clientId)||!e.clientSecret)throw f.error(`Client ID and client secret are required for Apple. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`name`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`apple`,options:e,authorizationEndpoint:`https://appleid.apple.com/auth/authorize`,scopes:o,state:t,redirectURI:r,codeVerifier:a,responseMode:`form_post`,responseType:`code id_token`,additionalParams:i})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),idToken:{jwks:e=>_fe(e.kid),issuer:`https://appleid.apple.com`,audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:`1h`,nonceComparison:`exact-or-sha256`},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:e,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=_I(t.idToken);if(!n)return null;let r;r=t.user?.name?`${t.user.name.firstName||``} ${t.user.name.lastName||``}`.trim():n.name||``;let i=typeof n.email_verified==`boolean`?n.email_verified:n.email_verified===`true`,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},_fe=async e=>{let{data:t}=await BX(`https://appleid.apple.com/auth/keys`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await hI(n,n.alg)},vfe=e=>{let t=`https://auth.atlassian.com/oauth/token`;return{id:`atlassian`,name:`Atlassian`,accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Secret are required for Atlassian`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Atlassian`);let o=e.disableDefaultScope?[]:[`read:jira-user`,`offline_access`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`atlassian`,options:e,authorizationEndpoint:`https://auth.atlassian.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:{...a??{},audience:`api.atlassian.com`},prompt:e.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:n}=await BX(`https://api.atlassian.com/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}catch(e){return f.error(`Failed to fetch user info from Atlassian:`,e),null}},options:e}},YZ=`https://dash.cloudflare.com/oauth2/token`,XZ=e=>{let t=e.clientSecret?`client_secret_basic`:`none`;return{method:e.tokenEndpointAuthMethod??t}},yfe=e=>({id:`cloudflare`,name:`Cloudflare`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i}){let a=e.disableDefaultScope?[]:[`user-details.read`];return e.scope?.length&&a.push(...e.scope),n?.length&&a.push(...n),ZY({id:`cloudflare`,options:e,authorizationEndpoint:`https://dash.cloudflare.com/oauth2/auth`,scopes:a.length?[...new Set(a)]:void 0,state:t,codeVerifier:r,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:YZ,tokenEndpointAuth:XZ(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:YZ,tokenEndpointAuth:XZ(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.cloudflare.com/client/v4/user`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n?.success||!n.result)return f.error(`Failed to fetch user info from Cloudflare:`,r??n?.errors),null;let i=n.result,a=[i.first_name,i.last_name].filter(Boolean).join(` `)||i.email,o=await e.mapProfileToUser?.(i);return{user:{name:a,email:i.email,emailVerified:!1,...o},data:i}},options:e}),bfe=e=>{if(!e.domain||!e.region||!e.userPoolId)throw f.error(`Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options.`),new D(`DOMAIN_AND_REGION_REQUIRED`);let t=e.domain.replace(/^https?:\/\//,``),n=`https://${t}/oauth2/authorize`,r=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:`cognito`,name:`Cognito`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!qY(e.clientId))throw f.error(`ClientId is required for Amazon Cognito. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(e.requireClientSecret&&!e.clientSecret)throw f.error(`Client Secret is required when requireClientSecret is true. Make sure to provide it in the options.`),new D(`CLIENT_SECRET_REQUIRED`);let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];e.scope&&s.push(...e.scope),r&&s.push(...r);let c=await ZY({id:`cognito`,options:{...e},authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...o??{}}}),l=c.searchParams.get(`scope`);if(l){c.searchParams.delete(`scope`);let e=encodeURIComponent(l),t=c.toString(),n=t.includes(`?`)?`&`:`?`;return new URL(`${t}${n}scope=${e}`)}return c},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>AZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),idToken:{jwks:t=>xfe(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,maxTokenAge:`1h`},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let n=_I(t.idToken);if(!n)return null;let r=n.name||n.given_name||n.username||``,i={...n,name:r},a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:i}}catch(e){f.error(`Failed to decode ID token:`,e)}if(t.accessToken)try{let{data:n}=await BX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n){let t=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.given_name||n.username||``,email:n.email,image:n.picture,emailVerified:n.email_verified,...t},data:n}}}catch(e){f.error(`Failed to fetch user info from Cognito:`,e)}return null},options:e}},xfe=async(e,t,n)=>{let r=`https://cognito-idp.${t}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:t}=await BX(r);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await hI(n,n.alg)}catch(e){throw f.error(`Failed to fetch Cognito public key:`,e),e}},Sfe=e=>{let t=`https://discord.com/api/oauth2/token`;return{id:`discord`,name:`Discord`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identify`,`email`];n&&a.push(...n),e.scope&&a.push(...e.scope);let o=a.includes(`bot`);return ZY({id:`discord`,options:e,authorizationEndpoint:`https://discord.com/api/oauth2/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`none`,additionalParams:{...o&&e.permissions!==void 0?{permissions:String(e.permissions)}:{},...i??{}}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://discord.com/api/users/@me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;if(n.avatar===null)n.image_url=`https://cdn.discordapp.com/embed/avatars/${n.discriminator===`0`?Number(BigInt(n.id)>>BigInt(22))%6:parseInt(n.discriminator)%5}.png`;else{let e=n.avatar.startsWith(`a_`)?`gif`:`png`;n.image_url=`https://cdn.discordapp.com/avatars/${n.id}/${n.avatar}.${e}`}let i=await e.mapProfileToUser?.(n);return{user:{name:n.global_name||n.username||``,email:n.email,emailVerified:n.verified,image:n.image_url,...i},data:n}},options:e}},Cfe=e=>{let t=`https://api.dropboxapi.com/oauth2/token`;return{id:`dropbox`,name:`Dropbox`,accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`account_info.read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`dropbox`,options:e,authorizationEndpoint:`https://www.dropbox.com/oauth2/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>await AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.dropboxapi.com/2/users/get_current_account`,{method:`POST`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...i},data:n}},options:e}};async function wfe(e,t){let n=qY(t.clientId);if(!n||!t.clientSecret)return null;let r=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await BX(`https://graph.facebook.com/debug_token`,{query:{input_token:e,access_token:`${n}|${t.clientSecret}`}});if(a||!i?.data)return null;let{is_valid:o,app_id:s,user_id:c}=i.data;return o!==!0||!s||!r.includes(s)||!c?null:c}const Tfe=e=>({id:`facebook`,name:`Facebook`,accountSubject:({profile:e})=>`sub`in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a}){if(!qY(e.clientId)||!e.clientSecret)throw f.error(`Client ID and client secret are required for Facebook. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`public_profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`facebook`,options:e,authorizationEndpoint:`https://www.facebook.com/v24.0/dialog/oauth`,scopes:o,state:t,redirectURI:r,loginHint:i,additionalParams:{...e.configId?{config_id:e.configId}:{},...a??{}}})},validateAuthorizationCode:async({code:t,redirectURI:n})=>AZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),idToken:{jwks:Ide(new URL(`https://limited.facebook.com/.well-known/oauth/openid/jwks/`)),issuer:`https://www.facebook.com`,audience:e.clientId,algorithms:[`RS256`],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken&&t.idToken.split(`.`).length===3){let n=_I(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}let n=t.accessToken;if(!n)return null;let r=await wfe(n,e);if(!r)return null;let{data:i,error:a}=await BX(`https://graph.facebook.com/me?fields=`+[`id`,`name`,`email`,`picture`,...e?.fields||[]].join(`,`),{auth:{type:`Bearer`,token:n}});if(a||i.id!==r)return null;let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...o},data:i}},options:e}),Efe=e=>{let t=`https://api.figma.com/v1/oauth/token`;return{id:`figma`,name:`Figma`,accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret are required for Figma. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Figma`);let o=e.disableDefaultScope?[]:[`current_user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`figma`,options:e,authorizationEndpoint:`https://www.figma.com/oauth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await BX(`https://api.figma.com/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return f.error(`Failed to fetch user from Figma`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.handle,email:n.email,image:n.img_url,emailVerified:!1,...r},data:n}}catch(e){return f.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},Dfe=e=>{let t=`https://github.com/login/oauth/access_token`;return{id:`github`,name:`GitHub`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`read:user`,`user:email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),ZY({id:`github`,options:e,authorizationEndpoint:`https://github.com/login/oauth/authorize`,scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:r,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>{let{body:a,headers:o}=await OZ({code:n,codeVerifier:r,redirectURI:i,options:e}),{data:s,error:c}=await BX(t,{method:`POST`,body:a,headers:o});return c?(f.error(`GitHub OAuth token exchange failed:`,c),null):`error`in s?(f.error(`GitHub OAuth token exchange failed:`,s),null):GY(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.github.com/user`,{headers:{"User-Agent":`better-auth`,authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i}=await BX(`https://api.github.com/user/emails`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});!n.email&&i&&(n.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===n.email)?.verified??!1,o=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.login||``,email:n.email,image:n.avatar_url,emailVerified:a,...o},data:n}},options:e}},ZZ=(e=``)=>e.split(`://`).map(e=>e.replace(/\/{2,}/g,`/`)).join(`://`),Ofe=e=>{let t=e||`https://gitlab.com`;return{authorizationEndpoint:ZZ(`${t}/oauth/authorize`),tokenEndpoint:ZZ(`${t}/oauth/token`),userinfoEndpoint:ZZ(`${t}/api/v4/user`)}},kfe=e=>{let{authorizationEndpoint:t,tokenEndpoint:n,userinfoEndpoint:r}=Ofe(e.issuer),i=`gitlab`;return{id:i,name:`Gitlab`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:n,scopes:r,codeVerifier:a,loginHint:o,redirectURI:s,additionalParams:c})=>{let l=e.disableDefaultScope?[]:[`read_user`];return e.scope&&l.push(...e.scope),r&&l.push(...r),await ZY({id:i,options:e,authorizationEndpoint:t,scopes:l,state:n,redirectURI:s,codeVerifier:a,loginHint:o,additionalParams:c})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>AZ({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:i}=await BX(r,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||n.state!==`active`||n.locked)return null;let a=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.username??``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...a},data:n}},options:e}},QZ=(e,t)=>e?typeof t!=`string`||!t?!1:e===`*`||t===e:!0,Afe=e=>({id:`google`,name:`Google`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,display:o,additionalParams:s}){if(!qY(e.clientId)||!e.clientSecret)throw f.error(`Client Id and Client Secret is required for Google. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new D(`codeVerifier is required for Google`);let c=e.disableDefaultScope?[]:[`email`,`profile`,`openid`];return e.scope&&c.push(...e.scope),n&&c.push(...n),await ZY({id:`google`,options:e,authorizationEndpoint:`https://accounts.google.com/o/oauth2/v2/auth`,scopes:c,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{...e.includeGrantedScopes===!1?{}:{include_granted_scopes:`true`},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://oauth2.googleapis.com/token`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://oauth2.googleapis.com/token`}),idToken:{jwks:e=>jfe(e.kid),issuer:[`https://accounts.google.com`,`accounts.google.com`],audience:e.clientId,maxTokenAge:`1h`,verifyClaims:e.hd?t=>QZ(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=_I(t.idToken);if(!QZ(e.hd,n.hd))return f.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??`<missing>`}" does not satisfy the configured "hd" option "${e.hd}".`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...r},data:n}},options:e}),jfe=async e=>{let[t]=await Mfe(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},Mfe=async e=>{let{data:t}=await BX(`https://www.googleapis.com/oauth2/v3/certs`);if(!t?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let n=e?t.keys.filter(t=>t.kid===e):t.keys;if(!n.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(n.map(e=>hI(e,`RS256`)))},Nfe=e=>{let t=`https://huggingface.co/oauth/token`;return{id:`huggingface`,name:`Hugging Face`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`huggingface`,options:e,authorizationEndpoint:`https://huggingface.co/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://huggingface.co/oauth/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},Pfe=e=>{let t=`https://kauth.kakao.com/oauth/token`;return{id:`kakao`,name:`Kakao`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`account_email`,`profile_image`,`profile_nickname`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`kakao`,options:e,authorizationEndpoint:`https://kauth.kakao.com/oauth/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://kapi.kakao.com/v2/user/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n),a=n.kakao_account||{},o=a.profile||{};return{user:{name:o.nickname||a.name||``,email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:n}},options:e}},Ffe=e=>({id:`kick`,name:`Kick`,accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,codeVerifier:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`kick`,redirectURI:r,options:e,authorizationEndpoint:`https://id.kick.com/oauth/authorize`,scopes:o,codeVerifier:i,state:t,additionalParams:a})},async validateAuthorizationCode({code:t,redirectURI:n,codeVerifier:r}){return AZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://id.kick.com/oauth/token`,codeVerifier:r})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:`https://id.kick.com/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.kick.com/public/v1/users`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=n.data[0],a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),Ife=e=>{let t=`https://api.line.me/oauth2/v2.1/token`;return{id:`line`,name:`LINE`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),await ZY({id:`line`,options:e,authorizationEndpoint:`https://access.line.me/oauth2/v2.1/authorize`,scopes:s,state:t,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,n)=>{let r=new URLSearchParams;r.set(`id_token`,t),r.set(`client_id`,e.clientId),n&&r.set(`nonce`,n);let{data:i,error:a}=await BX(`https://api.line.me/oauth2/v2.1/verify`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:r});return!(a||!i||i.aud!==e.clientId||i.nonce&&i.nonce!==n)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=null;if(t.idToken)try{n=_I(t.idToken)}catch{}if(!n){let{data:e}=await BX(`https://api.line.me/oauth2/v2.1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});n=e||null}if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}},options:e}},Lfe=e=>{let t=`https://api.linear.app/oauth/token`;return{id:`linear`,name:`Linear`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`linear`,options:e,authorizationEndpoint:`https://linear.app/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.linear.app/graphql`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
62
+ query {
63
+ viewer {
64
+ id
65
+ name
66
+ email
67
+ avatarUrl
68
+ active
69
+ createdAt
70
+ updatedAt
71
+ }
72
+ }
73
+ `})});if(r||!n?.data?.viewer)return null;let i=n.data.viewer,a=await e.mapProfileToUser?.(i);return{user:{name:n.data.viewer.name,email:n.data.viewer.email,image:n.data.viewer.avatarUrl,emailVerified:!1,...a},data:i}},options:e}},Rfe=e=>{let t=`https://www.linkedin.com/oauth/v2/accessToken`;return{id:`linkedin`,name:`Linkedin`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL:async({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`profile`,`email`,`openid`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await ZY({id:`linkedin`,options:e,authorizationEndpoint:`https://www.linkedin.com/oauth/v2/authorization`,scopes:o,state:t,loginHint:i,redirectURI:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>await AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.linkedin.com/v2/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,emailVerified:n.email_verified??!1,image:n.picture,...i},data:n}},options:e}},$Z=`9188040d-6c67-4c5b-b112-36a304b66dad`,zfe=e=>{let t=e.tenantId||`common`,n=e.authority||`https://login.microsoftonline.com`;for(;n.endsWith(`/`);)n=n.slice(0,-1);let r=`${n}/${t}/oauth2/v2.0/authorize`,i=`${n}/${t}/oauth2/v2.0/token`;if(e.clientSecret&&e.clientAssertion)throw new D(`Microsoft Entra ID clientAssertion cannot be combined with clientSecret`);let a=e.clientAssertion?{method:`private_key_jwt`,getClientAssertion:e.clientAssertion}:void 0;return{id:`microsoft`,name:`Microsoft EntraID`,accountSubject:({profile:e})=>e.oid,createAuthorizationURL(t){if(!qY(e.clientId))throw f.error(`Client Id is required for Microsoft Entra ID. Make sure to provide it in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),ZY({id:`microsoft`,options:e,authorizationEndpoint:r,state:t.state,codeVerifier:t.codeVerifier,scopes:n,redirectURI:t.redirectURI,prompt:e.prompt,loginHint:t.loginHint,additionalParams:t.additionalParams})},validateAuthorizationCode({code:t,codeVerifier:n,redirectURI:r}){return AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:i,tokenEndpointAuth:a})},idToken:{jwks:e=>Bfe(e.kid,t,n),algorithms:[`RS256`],audience:e.clientId,maxTokenAge:`1h`,issuer:t!==`common`&&t!==`organizations`&&t!==`consumers`?`${n}/${t}/v2.0`:void 0,verifyClaims:e=>{let r=e.tid;return!(typeof r!=`string`||e.iss!==`${n}/${r}/v2.0`||t===`organizations`&&r===$Z||t===`consumers`&&r!==$Z)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=_I(t.idToken);if(typeof n.oid!=`string`||n.oid.trim().length===0)return f.error(`Microsoft Entra ID token did not include a valid oid claim; unable to resolve a stable account identifier.`),null;let r=e.profilePhotoSize||48;!e.disableProfilePhoto&&t.accessToken&&await BX(`https://graph.microsoft.com/v1.0/me/photos/${r}x${r}/$value`,{headers:{Authorization:`Bearer ${t.accessToken}`},async onResponse(e){if(e.response.ok)try{let t=await e.response.clone().arrayBuffer();n.picture=`data:image/jpeg;base64, ${ue.encode(t)}`}catch(e){f.error(e&&typeof e==`object`&&`name`in e?e.name:``,e)}}});let i=await e.mapProfileToUser?.(n),a=n.email_verified===void 0?!!(n.email&&(n.verified_primary_email?.includes(n.email)||n.verified_secondary_email?.includes(n.email))):n.email_verified;return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:a,...i},data:n}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let n=e.disableDefaultScope?[]:[`openid`,`profile`,`email`,`User.Read`,`offline_access`];return e.scope&&n.push(...e.scope),DZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:n.join(` `)},tokenEndpoint:i,tokenEndpointAuth:a})},options:e}},Bfe=async(e,t,n)=>{let{data:r}=await BX(`${n}/${t}/discovery/v2.0/keys`);if(!r?.keys)throw new E(`BAD_REQUEST`,{message:`Keys not found`});let i=r.keys.find(t=>t.kid===e);if(!i)throw Error(`JWK with kid ${e} not found`);return await hI(i,i.alg??`RS256`)},Vfe=e=>{let t=`https://nid.naver.com/oauth2.0/token`;return{id:`naver`,name:`Naver`,accountSubject:({profile:e})=>e.response.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`profile`,`email`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`naver`,options:e,authorizationEndpoint:`https://nid.naver.com/oauth2.0/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://openapi.naver.com/v1/nid/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n||n.resultcode!==`00`)return null;let i=await e.mapProfileToUser?.(n),a=n.response||{};return{user:{name:a.name||a.nickname||``,email:a.email,image:a.profile_image,emailVerified:!1,...i},data:n}},options:e}},Hfe=e=>{let t=`https://api.notion.com/v1/oauth/token`;return{id:`notion`,name:`Notion`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=(e.disableDefaultScope,[]);return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`notion`,options:e,authorizationEndpoint:`https://api.notion.com/v1/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:{...a??{},owner:`user`}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.notion.com/v1/users/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"Notion-Version":`2022-06-28`}});if(r||!n)return null;let i=n.bot?.owner?.user;if(!i)return null;let a=await e.mapProfileToUser?.(i);return{user:{name:i.name||``,email:i.person?.email||null,image:i.avatar_url,emailVerified:!1,...a},data:i}},options:e}},Ufe=e=>{let t=e.issuer||`https://idp.paybin.io`,n=`${t}/oauth2/authorize`,r=`${t}/oauth2/token`;return{id:`paybin`,name:`Paybin`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,loginHint:o,additionalParams:s}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret is required for Paybin. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new D(`codeVerifier is required for Paybin`);let c=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&c.push(...e.scope),r&&c.push(...r),await ZY({id:`paybin`,options:e,authorizationEndpoint:n,scopes:c,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,loginHint:o,additionalParams:s})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>AZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=_I(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified||!1,...r},data:n}},options:e}},Wfe=e=>{let t=(e.environment||`sandbox`)===`sandbox`,n=t?`https://www.sandbox.paypal.com/signin/authorize`:`https://www.paypal.com/signin/authorize`,r=t?`https://api-m.sandbox.paypal.com/v1/oauth2/token`:`https://api-m.paypal.com/v1/oauth2/token`,i=t?`https://api-m.sandbox.paypal.com/v1/identity/oauth2/userinfo`:`https://api-m.paypal.com/v1/identity/oauth2/userinfo`,a={clientId:e.clientId,clientSecret:e.clientSecret},o={method:`client_secret_basic`};return{id:`paypal`,name:`PayPal`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret is required for PayPal. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);return await ZY({id:`paypal`,options:e,authorizationEndpoint:n,scopes:[],state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>{try{return await AZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw f.error(`PayPal token exchange failed:`,e),new D(`FAILED_TO_GET_ACCESS_TOKEN`)}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await DZ({refreshToken:e,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw f.error(`PayPal token refresh failed:`,e),new D(`FAILED_TO_REFRESH_ACCESS_TOKEN`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return f.error(`Access token is required to fetch PayPal user info`),null;try{let n=await BX(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:`application/json`}});if(!n.data)return f.error(`Failed to fetch user info from PayPal`),null;let r=n.data;if(t.idToken){let e;try{e=_I(t.idToken).sub}catch(e){return f.error(`Failed to decode PayPal ID token:`,e),null}let n=r.sub??r.user_id;if(!e||n!==e)return f.error(`PayPal user info subject does not match ID token subject`),null}let a=await e.mapProfileToUser?.(r);return{user:{name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified,...a},data:r}}catch(e){return f.error(`Failed to fetch user info from PayPal:`,e),null}},options:e}},Gfe=e=>{let t=`https://api.polar.sh/v1/oauth2/token`;return{id:`polar`,name:`Polar`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`polar`,options:e,authorizationEndpoint:`https://polar.sh/oauth2/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.polar.sh/v1/oauth2/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.public_name||n.username||``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},eQ=`https://backboard.railway.com/oauth/token`,Kfe=e=>({id:`railway`,name:`Railway`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`railway`,options:e,authorizationEndpoint:`https://backboard.railway.com/oauth/auth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:eQ,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:eQ,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://backboard.railway.com/oauth/me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...i},data:n}},options:e});function tQ({identifier:e,namespace:t}){let n=Fe().safeParse(`${e}@${t}.placeholder.invalid`);if(!n.success)throw TypeError(`Invalid placeholder email`);return n.data}const nQ={apple:gfe,atlassian:vfe,cloudflare:yfe,cognito:bfe,discord:Sfe,facebook:Tfe,figma:Efe,github:Dfe,microsoft:zfe,google:Afe,huggingface:Nfe,slack:e=>{let t=`https://slack.com/api/openid.connect.token`;return{id:`slack`,name:`Slack`,accountSubject:({profile:e})=>e[`https://slack.com/user_id`],createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return n&&a.push(...n),e.scope&&a.push(...e.scope),ZY({id:`slack`,options:e,authorizationEndpoint:`https://slack.com/openid/connect/authorize`,scopes:a,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://slack.com/api/openid.connect.userInfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,emailVerified:n.email_verified,image:n.picture||n[`https://slack.com/user_image_512`],...i},data:n}},options:e}},spotify:e=>{let t=`https://accounts.spotify.com/api/token`;return{id:`spotify`,name:`Spotify`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user-read-email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`spotify`,options:e,authorizationEndpoint:`https://accounts.spotify.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.spotify.com/v1/me`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.display_name,email:n.email,image:n.images[0]?.url,emailVerified:!1,...i},data:n}},options:e}},twitch:e=>{let t=`https://id.twitch.tv/oauth2/token`;return{id:`twitch`,name:`Twitch`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user:read:email`,`openid`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`twitch`,redirectURI:r,options:e,authorizationEndpoint:`https://id.twitch.tv/oauth2/authorize`,scopes:a,state:t,claims:e.claims||[`email`,`email_verified`,`preferred_username`,`picture`],additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.idToken;if(!n)return f.error(`No idToken found in token`),null;let r=_I(n),i=await e.mapProfileToUser?.(r);return{user:{name:r.preferred_username,email:r.email,image:r.picture,emailVerified:r.email_verified,...i},data:r}},options:e}},twitter:e=>{let t=`https://api.x.com/2/oauth2/token`;return{id:`twitter`,name:`Twitter`,accountSubject:({profile:e})=>e.data.id,createAuthorizationURL(t){let n=e.disableDefaultScope?[]:[`users.read`,`tweet.read`,`offline.access`,`users.email`];return e.scope&&n.push(...e.scope),t.scopes&&n.push(...t.scopes),ZY({id:`twitter`,options:e,authorizationEndpoint:`https://x.com/i/oauth2/authorize`,scopes:n,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI,additionalParams:t.additionalParams})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>AZ({code:n,codeVerifier:r,authentication:`basic`,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},authentication:`basic`,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.x.com/2/users/me?user.fields=profile_image_url`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i,error:a}=await BX(`https://api.x.com/2/users/me?user.fields=confirmed_email`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}}),o=!1;!a&&i?.data?.confirmed_email&&(n.data.email=i.data.confirmed_email,o=!0);let s=await e.mapProfileToUser?.(n);return{user:{name:n.data.name,email:n.data.email||tQ({identifier:n.data.id,namespace:`twitter`}),image:n.data.profile_image_url,emailVerified:o,...s},data:n}},options:e}},dropbox:Cfe,kick:Ffe,linear:Lfe,linkedin:Rfe,gitlab:kfe,tiktok:e=>{let t=`https://open.tiktokapis.com/v2/oauth/token/`,n={method:`custom`,customizeRequest({body:t}){t.set(`client_key`,e.clientKey),t.set(`client_secret`,e.clientSecret)}};return{id:`tiktok`,name:`TikTok`,accountSubject:({profile:e})=>e.data.user.open_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`user.info.profile`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://www.tiktok.com/v2/auth/authorize`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`client_key`,e.clientKey),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),i)for(let[e,t]of Object.entries(i))XY.has(e)||e!==`client_key`&&o.searchParams.set(e,t);return o},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>AZ({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>DZ({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://open.tiktokapis.com/v2/user/info/?fields=${[`open_id`,`avatar_large_url`,`display_name`,`username`].join(`,`)}`,{headers:{authorization:`Bearer ${t.accessToken}`}});return r?null:{user:{email:n.data.user.email||tQ({identifier:n.data.user.open_id,namespace:`tiktok`}),name:n.data.user.display_name||n.data.user.username||``,image:n.data.user.avatar_large_url,emailVerified:!1},data:n}},options:e}},reddit:e=>{let t=`https://www.reddit.com/api/v1/access_token`,n={clientId:e.clientId,clientSecret:e.clientSecret},r={method:`client_secret_basic`};return{id:`reddit`,name:`Reddit`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identity`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`reddit`,options:e,authorizationEndpoint:`https://www.reddit.com/api/v1/authorize`,scopes:a,state:t,redirectURI:r,duration:e.duration,additionalParams:i})},validateAuthorizationCode:async({code:i,redirectURI:a})=>AZ({code:i,redirectURI:e.redirectURI||a,options:n,tokenEndpoint:t,tokenEndpointAuth:r,headers:{accept:`text/plain`,"user-agent":`better-auth`}}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>DZ({refreshToken:e,options:n,tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://oauth.reddit.com/api/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});if(r)return null;let i=await e.mapProfileToUser?.(n),a=i?.email||tQ({identifier:n.id,namespace:`reddit`});return{user:{name:n.name,image:n.icon_img?.split(`?`)[0],...i,email:a,emailVerified:i?.emailVerified??!1},data:n}},options:e}},roblox:e=>{let t=`https://apis.roblox.com/oauth/v1/token`;return{id:`roblox`,name:`Roblox`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`openid`,`profile`];return e.scope&&a.push(...e.scope),n&&a.push(...n),ZY({id:`roblox`,options:e,authorizationEndpoint:`https://apis.roblox.com/oauth/v1/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`select_account consent`,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>AZ({code:n,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t,authentication:`post`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://apis.roblox.com/oauth/v1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.nickname||n.preferred_username||``,image:n.picture,email:tQ({identifier:n.sub,namespace:`roblox`}),emailVerified:!1,...i},data:{...n}}},options:e}},salesforce:e=>{let t=(e.environment??`production`)===`sandbox`,n=e.loginUrl?`https://${e.loginUrl}/services/oauth2/authorize`:t?`https://test.salesforce.com/services/oauth2/authorize`:`https://login.salesforce.com/services/oauth2/authorize`,r=e.loginUrl?`https://${e.loginUrl}/services/oauth2/token`:t?`https://test.salesforce.com/services/oauth2/token`:`https://login.salesforce.com/services/oauth2/token`,i=e.loginUrl?`https://${e.loginUrl}/services/oauth2/userinfo`:t?`https://test.salesforce.com/services/oauth2/userinfo`:`https://login.salesforce.com/services/oauth2/userinfo`;return{id:`salesforce`,name:`Salesforce`,accountSubject:({profile:e})=>e.user_id,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!e.clientId||!e.clientSecret)throw f.error(`Client Id and Client Secret are required for Salesforce. Make sure to provide them in the options.`),new D(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!i)throw new D(`codeVerifier is required for Salesforce`);let s=e.disableDefaultScope?[]:[`openid`,`email`,`profile`];return e.scope&&s.push(...e.scope),r&&s.push(...r),ZY({id:`salesforce`,options:e,authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:e.redirectURI||a,additionalParams:o})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>AZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>DZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await BX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return f.error(`Failed to fetch user info from Salesforce`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.photos?.picture||n.photos?.thumbnail,emailVerified:n.email_verified??!1,...r},data:n}}catch(e){return f.error(`Failed to fetch user info from Salesforce:`,e),null}},options:e}},vk:e=>{let t=`https://id.vk.com/oauth2/auth`;return{id:`vk`,name:`VK`,accountSubject:({profile:e})=>e.user.user_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`email`,`phone`];return e.scope&&o.push(...e.scope),n&&o.push(...n),ZY({id:`vk`,options:e,authorizationEndpoint:`https://id.vk.com/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i,deviceId:a})=>AZ({code:n,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>DZ({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;let{data:n,error:r}=await BX(`https://id.vk.com/oauth2/user_info`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({access_token:t.accessToken,client_id:e.clientId}).toString()});if(r)return null;let i=await e.mapProfileToUser?.(n);return!n.user.email&&!i?.email?null:{user:{first_name:n.user.first_name,last_name:n.user.last_name,email:n.user.email,image:n.user.avatar,emailVerified:!1,birthday:n.user.birthday,sex:n.user.sex,name:`${n.user.first_name} ${n.user.last_name}`,...i},data:n}},options:e}},zoom:e=>{let t={pkce:!0,...e};return{id:`zoom`,name:`Zoom`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:e,redirectURI:n,codeVerifier:r,additionalParams:i})=>ZY({id:`zoom`,options:t,authorizationEndpoint:`https://zoom.us/oauth/authorize`,state:e,redirectURI:n,codeVerifier:t.pkce?r:void 0,additionalParams:i}),validateAuthorizationCode:async({code:e,redirectURI:n,codeVerifier:r})=>AZ({code:e,redirectURI:t.redirectURI||n,codeVerifier:r,options:t,tokenEndpoint:`https://zoom.us/oauth/token`,authentication:`post`}),refreshAccessToken:t.refreshAccessToken?t.refreshAccessToken:async e=>DZ({refreshToken:e,options:{clientId:t.clientId,clientKey:t.clientKey,clientSecret:t.clientSecret},tokenEndpoint:`https://zoom.us/oauth/token`}),async getUserInfo(e){if(t.getUserInfo)return t.getUserInfo(e);let{data:n,error:r}=await BX(`https://api.zoom.us/v2/users/me`,{headers:{authorization:`Bearer ${e.accessToken}`}});if(r)return null;let i=await t.mapProfileToUser?.(n);return{user:{name:n.display_name,image:n.pic_url,email:n.email,emailVerified:!!n.verified,...i},data:{...n}}}}},notion:Hfe,kakao:Pfe,naver:Vfe,line:Ife,paybin:Ufe,paypal:Wfe,polar:Gfe,railway:Kfe,vercel:e=>({id:`vercel`,name:`Vercel`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!r)throw new D(`codeVerifier is required for Vercel`);let o;return(e.scope!==void 0||n!==void 0)&&(o=[],e.scope&&o.push(...e.scope),n&&o.push(...n)),ZY({id:`vercel`,options:e,authorizationEndpoint:`https://vercel.com/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>AZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://api.vercel.com/login/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await BX(`https://api.vercel.com/login/oauth/userinfo`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.preferred_username??``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}),wechat:e=>({id:`wechat`,name:`WeChat`,accountSubject:({profile:e})=>e.unionid||e.openid,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`snsapi_login`];e.scope&&a.push(...e.scope),n&&a.push(...n);let o=new URL(`https://open.weixin.qq.com/connect/qrconnect`);if(o.searchParams.set(`scope`,a.join(`,`)),o.searchParams.set(`response_type`,`code`),o.searchParams.set(`appid`,e.clientId),o.searchParams.set(`redirect_uri`,e.redirectURI||r),o.searchParams.set(`state`,t),o.searchParams.set(`lang`,e.lang||`cn`),i)for(let[e,t]of Object.entries(i))XY.has(e)||e!==`appid`&&o.searchParams.set(e,t);return o.hash=`wechat_redirect`,o},validateAuthorizationCode:async({code:t})=>{let{data:n,error:r}=await BX(`https://api.weixin.qq.com/sns/oauth2/access_token?`+new URLSearchParams({appid:e.clientId,secret:e.clientSecret,code:t,grant_type:`authorization_code`}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to validate authorization code: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`),openid:n.openid,unionid:n.unionid}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>{let{data:n,error:r}=await BX(`https://api.weixin.qq.com/sns/oauth2/refresh_token?`+new URLSearchParams({appid:e.clientId,grant_type:`refresh_token`,refresh_token:t}).toString(),{method:`GET`});if(r||!n||n.errcode)throw Error(`Failed to refresh access token: ${n?.errmsg||r?.message||`Unknown error`}`);return{tokenType:`Bearer`,accessToken:n.access_token,refreshToken:n.refresh_token,accessTokenExpiresAt:new Date(Date.now()+n.expires_in*1e3),scopes:n.scope.split(`,`)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=t.openid;if(!n)return null;let{data:r,error:i}=await BX(`https://api.weixin.qq.com/sns/userinfo?`+new URLSearchParams({access_token:t.accessToken||``,openid:n,lang:`zh_CN`}).toString(),{method:`GET`});if(i||!r||r.errcode)return null;let a=await e.mapProfileToUser?.(r),o=r.unionid||r.openid||n;return{user:{name:r.nickname,email:r.email||tQ({identifier:o,namespace:`wechat`}),image:r.headimgurl,emailVerified:!1,...a},data:r}},options:e})},qfe=Object.keys(nQ),rQ=We(qfe).or(k());function iQ(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const Jfe=X(`/list-accounts`,{method:`GET`,use:[VJ],metadata:{openapi:{operationId:`listUserAccounts`,description:`List all accounts linked to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`array`,items:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},createdAt:{type:`string`,format:`date-time`},updatedAt:{type:`string`,format:`date-time`},accountId:{type:`string`},userId:{type:`string`},scopes:{type:`array`,items:{type:`string`}}},required:[`id`,`providerId`,`createdAt`,`updatedAt`,`accountId`,`userId`,`scopes`]}}}}}}}}},async e=>{let t=e.context.session,n=await e.context.internalAdapter.findAccounts(t.user.id);return e.json(n.map(t=>{let{scope:n,...r}=rG(e.context.options,t);return{...r,scopes:iQ(n)}}))}),Yfe=X(`/link-social`,{method:`POST`,requireHeaders:!0,body:A({callbackURL:k().meta({description:`The URL to redirect to after the user has signed in`}).optional(),provider:rQ,idToken:A({token:k(),nonce:k().optional(),accessToken:k().optional(),refreshToken:k().optional()}).optional(),requestSignUp:He().optional(),scopes:Pe(k()).meta({description:`Additional scopes to request from the provider`}).optional(),errorCallbackURL:k().meta({description:`The URL to redirect to if there is an error during the link process`}).optional(),disableRedirect:He().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),loginHint:k().meta({description:`The login hint to use for the authorization code request`}).optional(),additionalParams:QY,additionalData:Ne(k(),Ke()).optional()}),use:[VJ],metadata:{openapi:{description:`Link a social account to the user`,operationId:`linkSocialAccount`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{url:{type:`string`,description:`The authorization URL to redirect the user to`},redirect:{type:`boolean`,description:`Indicates if the user should be redirected to the authorization URL`},status:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=e.context.session,n=await AY(e.context.socialProviders,{value:e.body.provider});if(!n)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!UZ(n))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.ID_TOKEN_NOT_SUPPORTED);let{token:r,nonce:i}=e.body.idToken;if(!await WZ(n,r,i,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.INVALID_TOKEN);let a=await n.getUserInfo({idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken});if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(wq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await PY(n,{idToken:r,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken},a.data),s=await e.context.internalAdapter.findAccountByKey(o);if(s?.userId===t.user.id){let i=Object.fromEntries(Object.entries({providerId:n.id,accessToken:await LY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await LY(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>t!==void 0));return await e.context.internalAdapter.updateAccount(s.id,i),await JZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}if(s)throw E.from(`CONFLICT`,Y.SOCIAL_ACCOUNT_ALREADY_LINKED);if(!e.context.trustedProviders.includes(n.id)&&!a.user.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - linking not allowed`,code:`LINKING_NOT_ALLOWED`});if(a.user.email?.toLowerCase()!==t.user.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)throw E.from(`UNAUTHORIZED`,{message:`Account not linked - different emails not allowed`,code:`LINKING_DIFFERENT_EMAILS_NOT_ALLOWED`});try{await e.context.internalAdapter.createAccount({userId:t.user.id,...o,accessToken:await LY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await LY(e.body.idToken.refreshToken,e.context)})}catch{throw E.from(`EXPECTATION_FAILED`,{message:`Account not linked - unable to create account`,code:`LINKING_FAILED`})}return await JZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}let r=jq(n),i=await Mq(e,{link:{userId:t.user.id,email:t.user.email},additionalData:e.body.additionalData,idTokenNonce:r}),a=await n.createAuthorizationURL({state:i.state,codeVerifier:i.codeVerifier,idTokenNonce:r,redirectURI:`${e.context.baseURL}${RY(n)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),Xfe=X(`/unlink-account`,{method:`POST`,body:A({accountId:k().meta({description:`The Better Auth account ID to unlink`})}),use:[UJ],metadata:{openapi:{description:`Unlink an account`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let{accountId:t}=e.body,n=await e.context.internalAdapter.findAccounts(e.context.session.user.id);if(n.length===1&&!e.context.options.account?.accountLinking?.allowUnlinkingAll)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_UNLINK_LAST_ACCOUNT);let r=n.find(e=>e.id===t);if(!r)throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);return await e.context.internalAdapter.deleteAccount(r.id),e.json({status:!0})});async function aQ(e,t){let n=await zJ(e,{disableCookieCache:RJ(e)});if(!n&&(e.request||e.headers))throw e.error(`UNAUTHORIZED`);let r=n?.user?.id||t;if(!r)throw E.from(`BAD_REQUEST`,{message:`Either userId or session is required`,code:`USER_ID_OR_SESSION_REQUIRED`});return r}const oQ=Ee([Ye({accountId:k().meta({description:`The Better Auth account ID`}),userId:k().meta({description:`The user ID associated with the account`}).optional()}),Ye({useAccountCookie:Ue(!0).meta({description:`Select the current OAuth account from its signed cookie`}),userId:k().meta({description:`The user ID associated with the account`}).optional()})]);function sQ(e,t,{resolvedUserId:n,selection:r}){return(!WW(e.context.options)||t.userId===n)&&(`accountId`in r?t.id===r.accountId:!0)}async function cQ(e,{resolvedUserId:t,selection:n}){if(`accountId`in n){let r=(await e.context.internalAdapter.findAccounts(t)).find(e=>e.id===n.accountId);if(r)return{account:r,accountCookie:null}}else if(e.context.options.account?.storeAccountCookie){let r=await YK(e);if(r&&sQ(e,r,{resolvedUserId:t,selection:n}))return{account:r,accountCookie:r}}throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND)}async function lQ(e,{resolvedUserId:t,selection:n,account:r}){let i=r??(await cQ(e,{resolvedUserId:t,selection:n})).account;if(!sQ(e,i,{resolvedUserId:t,selection:n}))throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);let a=await AY(e.context.socialProviders,{value:i.providerId});if(!a)throw E.from(`BAD_REQUEST`,{message:`Provider ${i.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});try{let t=null,n=i.accessTokenExpiresAt&&new Date(i.accessTokenExpiresAt).getTime()-Date.now()<5e3;if(i.refreshToken&&n&&a.refreshAccessToken){let n=await IY(i.refreshToken,e.context);t=await a.refreshAccessToken(n,e);let r={accessToken:await LY(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await LY(t.refreshToken,e.context):i.refreshToken,refreshTokenExpiresAt:t?.refreshTokenExpiresAt??i.refreshTokenExpiresAt,idToken:t?.idToken||i.idToken},o=null;i.id&&(o=await e.context.internalAdapter.updateAccount(i.id,r)),e.context.options.account?.storeAccountCookie&&await JK(e,{...i,...o??r})}let r=(()=>{if(t?.accessTokenExpiresAt)return typeof t.accessTokenExpiresAt==`string`?new Date(t.accessTokenExpiresAt):t.accessTokenExpiresAt;if(i.accessTokenExpiresAt)return typeof i.accessTokenExpiresAt==`string`?new Date(i.accessTokenExpiresAt):i.accessTokenExpiresAt})();return{accessToken:t?.accessToken??await IY(i.accessToken??``,e.context),accessTokenExpiresAt:r,scopes:iQ(i.scope),idToken:t?.idToken??i.idToken??void 0}}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to get a valid access token`,code:`FAILED_TO_GET_ACCESS_TOKEN`})}}const Zfe=X(`/get-access-token`,{method:`POST`,body:oQ,metadata:{openapi:{description:`Get a valid access token, doing a refresh if needed`,responses:{200:{description:`A Valid access token`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,n=await lQ(e,{resolvedUserId:await aQ(e,t),selection:e.body});return e.json(n)}),Qfe=X(`/refresh-token`,{method:`POST`,body:oQ,metadata:{openapi:{description:`Refresh the access token using a refresh token`,responses:{200:{description:`Access token refreshed successfully`,content:{"application/json":{schema:{type:`object`,properties:{tokenType:{type:`string`},idToken:{type:`string`},accessToken:{type:`string`},refreshToken:{type:`string`},accessTokenExpiresAt:{type:`string`,format:`date-time`},refreshTokenExpiresAt:{type:`string`,format:`date-time`}}}}}},400:{description:`Invalid refresh token or provider configuration`}}}}},async e=>{let{userId:t}=e.body,{account:n,accountCookie:r}=await cQ(e,{resolvedUserId:await aQ(e,t),selection:e.body}),i=await AY(e.context.socialProviders,{value:n.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} is not supported.`,code:`PROVIDER_NOT_SUPPORTED`});if(!i.refreshAccessToken)throw E.from(`BAD_REQUEST`,{message:`Provider ${n.providerId} does not support token refreshing.`,code:`TOKEN_REFRESH_NOT_SUPPORTED`});let a=n.refreshToken??void 0;if(!a)throw E.from(`BAD_REQUEST`,{message:`Refresh token not found`,code:`REFRESH_TOKEN_NOT_FOUND`});try{let t=await IY(a,e.context),o=await i.refreshAccessToken(t,e),s=o.refreshToken?await LY(o.refreshToken,e.context):a,c=o.refreshTokenExpiresAt??n.refreshTokenExpiresAt,l={accessToken:await LY(o.accessToken,e.context),refreshToken:s,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,idToken:o.idToken||n.idToken},u=null;n.id&&(u=await e.context.internalAdapter.updateAccount(n.id,l)),r?.id===n.id&&e.context.options.account?.storeAccountCookie&&await JK(e,{...r,...u??l});let d=u?.scope??n.scope;return e.json({accessToken:o.accessToken,refreshToken:o.refreshToken??t,accessTokenExpiresAt:o.accessTokenExpiresAt,refreshTokenExpiresAt:c,scope:d,idToken:o.idToken||n.idToken,providerId:n.providerId,accountId:n.id})}catch{throw E.from(`BAD_REQUEST`,{message:`Failed to refresh access token`,code:`FAILED_TO_REFRESH_ACCESS_TOKEN`})}}),$fe=X(`/account-info`,{method:`GET`,metadata:{openapi:{description:`Get the account info provided by the provider`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,properties:{name:{type:`string`},email:{type:`string`,nullable:!0},image:{type:`string`},emailVerified:{type:`boolean`}},required:[`emailVerified`]},account:{type:`object`,properties:{id:{type:`string`},providerId:{type:`string`},accountId:{type:`string`}},required:[`id`,`providerId`,`accountId`],additionalProperties:!1},data:{type:`object`,properties:{},additionalProperties:!0}},required:[`user`,`data`,`account`],additionalProperties:!1}}}}}}},query:oQ},async e=>{let{userId:t}=e.query,n=await aQ(e,t),{account:r}=await cQ(e,{resolvedUserId:n,selection:e.query}),i=await AY(e.context.socialProviders,{value:r.providerId});if(!i)throw E.from(`BAD_REQUEST`,{message:`Account is not associated with a configured social provider.`,code:`PROVIDER_NOT_CONFIGURED`});let a=await lQ(e,{resolvedUserId:n,selection:e.query,account:r});if(!a.accessToken)throw E.from(`BAD_REQUEST`,{message:`Access token not found`,code:`ACCESS_TOKEN_NOT_FOUND`});let o=await i.getUserInfo({...a,accessToken:a.accessToken});if(!o)throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);return e.json({...o,account:{id:r.id,providerId:r.providerId,accountId:r.accountId}})}),uQ=A({code:k().optional(),error:k().optional(),device_id:k().optional(),error_description:k().optional(),state:k().optional(),user:k().optional(),iss:k().optional()}),epe=X(`/callback/:id`,{method:[`GET`,`POST`],operationId:`handleOAuthCallback`,body:uQ.optional(),query:uQ.optional(),metadata:{...Pq,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`]}},async e=>{let t,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`;if(e.method===`POST`){let t=e.body?uQ.parse(e.body):{},n=e.query?uQ.parse(e.query):{},r=uQ.parse({...t,...n}),i=new URLSearchParams;for(let[e,t]of Object.entries(r))t!=null&&i.set(e,String(t));let a=`${e.context.baseURL}/callback/${e.params.id}?${i.toString()}`;throw e.redirect(a)}try{if(e.method===`GET`)t=uQ.parse(e.query);else if(e.method===`POST`)t=uQ.parse(e.body);else throw Error(`Unsupported method`)}catch(t){e.context.logger.error(`INVALID_CALLBACK_REQUEST`,t);let r=bq(n,new URLSearchParams({error:`invalid_callback_request`}));throw e.redirect(r)}let{code:r,error:i,state:a,error_description:o,device_id:s,user:c,iss:l}=t;if(a===void 0&&r){let t=await AY(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let n=jq(t),{state:r,codeVerifier:i}=await Mq(e,{idTokenNonce:n}),a=await t.createAuthorizationURL({state:r,codeVerifier:i,idTokenNonce:n,redirectURI:`${e.context.baseURL}${RY(t)}`});throw e.redirect(a.toString())}}if(!a){e.context.logger.error(`State not found`,i);let t=bq(n,new URLSearchParams({error:`state_not_found`}));throw e.redirect(t)}let{codeVerifier:u,callbackURL:d,link:f,errorURL:p,newUserURL:m,requestSignUp:h,idTokenNonce:g}=await Nq(e);function _(t,r){let i=p??n,a=new URLSearchParams({error:t});r&&a.set(`error_description`,r);let o=bq(i,a);throw e.redirect(o)}if(i&&_(i,o),!r)throw e.context.logger.warn(`Code not found`),_(Sq.NO_CODE);let v=await AY(e.context.socialProviders,{value:e.params.id});if(!v)throw e.context.logger.warn(`OAuth provider not found`,{providerId:e.params.id}),_(Sq.PROVIDER_NOT_FOUND);if(l&&v.issuer&&l!==v.issuer)throw e.context.logger.error(`OAuth issuer mismatch`,{expected:v.issuer,received:l}),_(Sq.ISSUER_MISMATCH);if(v.requiresIdTokenNonce&&!g)throw e.context.logger.error(`OAuth id_token nonce binding required but no expected nonce was found in state`,{providerId:v.id}),_(Sq.NONCE_BINDING_MISSING);let y;try{y=await v.validateAuthorizationCode({code:r,codeVerifier:u,deviceId:s,redirectURI:`${e.context.baseURL}${RY(v)}`})}catch(t){throw e.context.logger.error(``,t),_(Sq.INVALID_CODE)}if(!y)throw _(Sq.INVALID_CODE);let b=c?le(c):null,x=await v.getUserInfo({...y,...g?{expectedIdTokenNonce:g}:{},user:b??void 0});if(!x?.user)return e.context.logger.error(`Unable to get user info`),_(Sq.UNABLE_TO_GET_USER_INFO);let S=x.user,ee=MY(x.data),C;try{C=await NY(v,y,x.data)}catch(t){return e.context.logger.error(`Unable to derive provider account identity`,{providerId:v.id,error:t}),_(Sq.UNABLE_TO_GET_USER_INFO)}let{accountId:te}=C;if(!d)throw e.context.logger.error(`No callback URL found`),_(Sq.NO_CALLBACK_URL);let ne={...C,...y,scope:y.scopes?.join(`,`)};if(f){let t=await hfe(e,{link:f,userInfo:S,account:ne,profile:ee,scopes:y.scopes});if(!t.linked)return _(t.error.code,t.error.message);throw e.redirect(d)}if(!S.email)return e.context.logger.error(wq(v.id)),_(Sq.EMAIL_NOT_FOUND);let w;try{w=await KZ(e,{userInfo:{...S,id:te,email:S.email,name:S.name||``},account:ne,callbackURL:d,disableSignUp:v.disableImplicitSignUp&&!h||v.options?.disableSignUp,overrideUserInfo:v.options?.overrideUserInfoOnSignIn,source:{method:`oauth`,oauth:{providerId:v.id,profile:ee}}})}catch(e){throw Fq(e)&&e.body?.code&&_(e.body.code,e.body.message),e}if(w.error)return e.context.logger.error(w.error.split(` `).join(`_`)),_(w.error.split(` `).join(`_`));let{session:T,user:re}=w.data;await aq(e,{session:T,user:re});let ie;try{ie=(w.isRegister&&m||d).toString()}catch{ie=w.isRegister&&m||d}throw e.redirect(ie)});function dQ(e){return e.replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`).replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,`&amp;`)}const tpe=(e,t=`Unknown`,n=null)=>{let r=e.onAPIError?.customizeDefaultErrorPage;return`<!DOCTYPE html>
74
+ <html lang="en">
75
+ <head>
76
+ <meta charset="UTF-8" />
77
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
78
+ <title>Error</title>
79
+ <style>
80
+ * {
81
+ box-sizing: border-box;
82
+ }
83
+ body {
84
+ font-family: ${r?.font?.defaultFamily||`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif`};
85
+ background: ${r?.colors?.background||`var(--background)`};
86
+ color: var(--foreground);
87
+ margin: 0;
88
+ }
89
+ :root,
90
+ :host {
91
+ --spacing: 0.25rem;
92
+ --container-md: 28rem;
93
+ --text-sm: ${r?.size?.textSm||`0.875rem`};
94
+ --text-sm--line-height: calc(1.25 / 0.875);
95
+ --text-2xl: ${r?.size?.text2xl||`1.5rem`};
96
+ --text-2xl--line-height: calc(2 / 1.5);
97
+ --text-4xl: ${r?.size?.text4xl||`2.25rem`};
98
+ --text-4xl--line-height: calc(2.5 / 2.25);
99
+ --text-6xl: ${r?.size?.text6xl||`3rem`};
100
+ --text-6xl--line-height: 1;
101
+ --font-weight-medium: 500;
102
+ --font-weight-semibold: 600;
103
+ --font-weight-bold: 700;
104
+ --default-transition-duration: 150ms;
105
+ --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
106
+ --radius: ${r?.size?.radiusSm||`0.625rem`};
107
+ --default-mono-font-family: ${r?.font?.monoFamily||`var(--font-geist-mono)`};
108
+ --primary: ${r?.colors?.primary||`black`};
109
+ --primary-foreground: ${r?.colors?.primaryForeground||`white`};
110
+ --background: ${r?.colors?.background||`white`};
111
+ --foreground: ${r?.colors?.foreground||`oklch(0.271 0 0)`};
112
+ --border: ${r?.colors?.border||`oklch(0.89 0 0)`};
113
+ --destructive: ${r?.colors?.destructive||`oklch(0.55 0.15 25.723)`};
114
+ --muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.545 0 0)`};
115
+ --corner-border: ${r?.colors?.cornerBorder||`#404040`};
116
+ }
117
+
118
+ button, .btn {
119
+ cursor: pointer;
120
+ background: none;
121
+ border: none;
122
+ color: inherit;
123
+ font: inherit;
124
+ transition: all var(--default-transition-duration)
125
+ var(--default-transition-timing-function);
126
+ }
127
+ button:hover, .btn:hover {
128
+ opacity: 0.8;
129
+ }
130
+
131
+ @media (prefers-color-scheme: dark) {
132
+ :root,
133
+ :host {
134
+ --primary: ${r?.colors?.primary||`white`};
135
+ --primary-foreground: ${r?.colors?.primaryForeground||`black`};
136
+ --background: ${r?.colors?.background||`oklch(0.15 0 0)`};
137
+ --foreground: ${r?.colors?.foreground||`oklch(0.98 0 0)`};
138
+ --border: ${r?.colors?.border||`oklch(0.27 0 0)`};
139
+ --destructive: ${r?.colors?.destructive||`oklch(0.65 0.15 25.723)`};
140
+ --muted-foreground: ${r?.colors?.mutedForeground||`oklch(0.65 0 0)`};
141
+ --corner-border: ${r?.colors?.cornerBorder||`#a0a0a0`};
142
+ }
143
+ }
144
+ @media (max-width: 640px) {
145
+ :root, :host {
146
+ --text-6xl: 2.5rem;
147
+ --text-2xl: 1.25rem;
148
+ --text-sm: 0.8125rem;
149
+ }
150
+ }
151
+ @media (max-width: 480px) {
152
+ :root, :host {
153
+ --text-6xl: 2rem;
154
+ --text-2xl: 1.125rem;
155
+ }
156
+ }
157
+ </style>
158
+ </head>
159
+ <body style="width: 100vw; min-height: 100vh; overflow-x: hidden; overflow-y: auto;">
160
+ <div
161
+ style="
162
+ display: flex;
163
+ flex-direction: column;
164
+ align-items: center;
165
+ justify-content: center;
166
+ gap: 1.5rem;
167
+ position: relative;
168
+ width: 100%;
169
+ min-height: 100vh;
170
+ padding: 1rem;
171
+ "
172
+ >
173
+ ${r?.disableBackgroundGrid?``:`
174
+ <div
175
+ style="
176
+ position: absolute;
177
+ inset: 0;
178
+ background-image: linear-gradient(to right, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px),
179
+ linear-gradient(to bottom, ${r?.colors?.gridColor||`var(--border)`} 1px, transparent 1px);
180
+ background-size: 40px 40px;
181
+ opacity: 0.6;
182
+ pointer-events: none;
183
+ width: 100vw;
184
+ height: 100vh;
185
+ "
186
+ ></div>
187
+ <div
188
+ style="
189
+ position: absolute;
190
+ inset: 0;
191
+ display: flex;
192
+ align-items: center;
193
+ justify-content: center;
194
+ background: ${r?.colors?.background||`var(--background)`};
195
+ mask-image: radial-gradient(ellipse at center, transparent 20%, black);
196
+ -webkit-mask-image: radial-gradient(ellipse at center, transparent 20%, black);
197
+ pointer-events: none;
198
+ "
199
+ ></div>
200
+ `}
201
+
202
+ <div
203
+ style="
204
+ position: relative;
205
+ z-index: 10;
206
+ border: 2px solid var(--border);
207
+ background: ${r?.colors?.cardBackground||`var(--background)`};
208
+ padding: 1.5rem;
209
+ max-width: 42rem;
210
+ width: 100%;
211
+ "
212
+ >
213
+ ${r?.disableCornerDecorations?``:`
214
+ <!-- Corner decorations -->
215
+ <div
216
+ style="
217
+ position: absolute;
218
+ top: -2px;
219
+ left: -2px;
220
+ width: 2rem;
221
+ height: 2rem;
222
+ border-top: 4px solid var(--corner-border);
223
+ border-left: 4px solid var(--corner-border);
224
+ "
225
+ ></div>
226
+ <div
227
+ style="
228
+ position: absolute;
229
+ top: -2px;
230
+ right: -2px;
231
+ width: 2rem;
232
+ height: 2rem;
233
+ border-top: 4px solid var(--corner-border);
234
+ border-right: 4px solid var(--corner-border);
235
+ "
236
+ ></div>
237
+
238
+ <div
239
+ style="
240
+ position: absolute;
241
+ bottom: -2px;
242
+ left: -2px;
243
+ width: 2rem;
244
+ height: 2rem;
245
+ border-bottom: 4px solid var(--corner-border);
246
+ border-left: 4px solid var(--corner-border);
247
+ "
248
+ ></div>
249
+ <div
250
+ style="
251
+ position: absolute;
252
+ bottom: -2px;
253
+ right: -2px;
254
+ width: 2rem;
255
+ height: 2rem;
256
+ border-bottom: 4px solid var(--corner-border);
257
+ border-right: 4px solid var(--corner-border);
258
+ "
259
+ ></div>`}
260
+
261
+ <div style="text-align: center; margin-bottom: 1.5rem;">
262
+ <div style="margin-bottom: 1.5rem;">
263
+ <div
264
+ style="
265
+ display: inline-block;
266
+ border: 2px solid ${r?.disableTitleBorder?`transparent`:r?.colors?.titleBorder||`var(--destructive)`};
267
+ padding: 0.375rem 1rem;
268
+ "
269
+ >
270
+ <h1
271
+ style="
272
+ font-size: var(--text-6xl);
273
+ font-weight: var(--font-weight-semibold);
274
+ color: ${r?.colors?.titleColor||`var(--foreground)`};
275
+ letter-spacing: -0.02em;
276
+ margin: 0;
277
+ "
278
+ >
279
+ ERROR
280
+ </h1>
281
+ </div>
282
+ <div
283
+ style="
284
+ height: 2px;
285
+ background-color: var(--border);
286
+ width: calc(100% + 3rem);
287
+ margin-left: -1.5rem;
288
+ margin-top: 1.5rem;
289
+ "
290
+ ></div>
291
+ </div>
292
+
293
+ <h2
294
+ style="
295
+ font-size: var(--text-2xl);
296
+ font-weight: var(--font-weight-semibold);
297
+ color: var(--foreground);
298
+ margin: 0 0 1rem;
299
+ "
300
+ >
301
+ Something went wrong
302
+ </h2>
303
+
304
+ <div
305
+ style="
306
+ display: inline-flex;
307
+ align-items: center;
308
+ gap: 0.5rem;
309
+ border: 2px solid var(--border);
310
+ background-color: var(--muted);
311
+ padding: 0.375rem 0.75rem;
312
+ margin: 0 0 1rem;
313
+ flex-wrap: wrap;
314
+ justify-content: center;
315
+ "
316
+ >
317
+ <span
318
+ style="
319
+ font-size: 0.75rem;
320
+ color: var(--muted-foreground);
321
+ font-weight: var(--font-weight-semibold);
322
+ "
323
+ >
324
+ CODE:
325
+ </span>
326
+ <span
327
+ style="
328
+ font-size: var(--text-sm);
329
+ font-family: var(--default-mono-font-family, monospace);
330
+ color: var(--foreground);
331
+ word-break: break-all;
332
+ "
333
+ >
334
+ ${dQ(t)}
335
+ </span>
336
+ </div>
337
+
338
+ <p
339
+ style="
340
+ color: var(--muted-foreground);
341
+ max-width: 28rem;
342
+ margin: 0 auto;
343
+ font-size: var(--text-sm);
344
+ line-height: 1.5;
345
+ text-wrap: pretty;
346
+ "
347
+ >
348
+ ${n||`We encountered an unexpected error. Please try again or return to the home page. If you're a developer, you can find <a href='https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}' target='_blank' rel="noopener noreferrer" style='color: var(--foreground); text-decoration: underline;'>more information about the error</a>.`}
349
+ </p>
350
+ </div>
351
+
352
+ <div
353
+ style="
354
+ display: flex;
355
+ gap: 0.75rem;
356
+ margin-top: 1.5rem;
357
+ justify-content: center;
358
+ flex-wrap: wrap;
359
+ "
360
+ >
361
+ <a
362
+ href="/"
363
+ style="
364
+ text-decoration: none;
365
+ "
366
+ >
367
+ <div
368
+ style="
369
+ border: 2px solid var(--border);
370
+ background: var(--primary);
371
+ color: var(--primary-foreground);
372
+ padding: 0.5rem 1rem;
373
+ border-radius: 0;
374
+ white-space: nowrap;
375
+ "
376
+ class="btn"
377
+ >
378
+ Go Home
379
+ </div>
380
+ </a>
381
+ <a
382
+ href="https://better-auth.com/docs/reference/errors/${encodeURIComponent(t)}?askai=${encodeURIComponent(`What does the error code ${t} mean?`)}"
383
+ target="_blank"
384
+ rel="noopener noreferrer"
385
+ style="
386
+ text-decoration: none;
387
+ "
388
+ >
389
+ <div
390
+ style="
391
+ border: 2px solid var(--border);
392
+ background: transparent;
393
+ color: var(--foreground);
394
+ padding: 0.5rem 1rem;
395
+ border-radius: 0;
396
+ white-space: nowrap;
397
+ "
398
+ class="btn"
399
+ >
400
+ Ask AI
401
+ </div>
402
+ </a>
403
+ </div>
404
+ </div>
405
+ </div>
406
+ </body>
407
+ </html>`},npe=X(`/error`,{method:`GET`,metadata:{...Pq,openapi:{description:`Displays an error page`,responses:{200:{description:`Success`,content:{"text/html":{schema:{type:`string`,description:`The HTML content of the error page`}}}}}}}},async e=>{let t=new URL(e.request?.url||``),n=t.searchParams.get(`error`)||`UNKNOWN`,r=t.searchParams.get(`error_description`)||null,i=/^[\'A-Za-z0-9_-]+$/.test(n||``)?n:`UNKNOWN`,a=r?dQ(r):null,o=new URLSearchParams;o.set(`error`,i),r&&o.set(`error_description`,r);let s=e.context.options,c=s.onAPIError?.errorURL;if(c){let e=bq(c,o);return new Response(null,{status:302,headers:{Location:e}})}return te&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(tpe(e.context.options,i,a),{headers:{"Content-Type":`text/html`}})}),rpe=X(`/ok`,{method:`GET`,metadata:{...Pq,openapi:{description:`Check if the API is working`,responses:{200:{description:`API is working`,content:{"application/json":{schema:{type:`object`,properties:{ok:{type:`boolean`,description:`Indicates if the API is working`}},required:[`ok`]}}}}}}}},async e=>e.json({ok:!0}));function fQ(e,t){if(t.length<e.context.password.config.minPasswordLength)throw e.context.logger.warn(`Password is too short`),E.from(`BAD_REQUEST`,Y.PASSWORD_TOO_SHORT)}function pQ(e,t){if(t.length>e.context.password.config.maxPasswordLength)throw e.context.logger.warn(`Password is too long`),E.from(`BAD_REQUEST`,Y.PASSWORD_TOO_LONG)}async function ipe(e,t,n,r){await wH(e.context.adapter,async()=>{await r?.(),e.context.options.emailAndPassword?.revokeSessionsOnPasswordReset&&await e.context.internalAdapter.deleteUserSessions(t),await e.context.internalAdapter.findCredentialAccount(t)?await e.context.internalAdapter.updatePassword(t,n):await e.context.internalAdapter.createAccount({userId:t,providerId:`credential`,accountId:t,password:n})})}async function ape(e,t){pQ(e,t.password);let n=await e.context.internalAdapter.findCredentialAccount(t.userId),r=n?.password;return!n||!r?!1:await e.context.password.verify({hash:r,password:t.password})}async function ope(e,t){let n=t.body.password;typeof n==`string`&&pQ(t,n);let r=await t.context.internalAdapter.findCredentialAccount(e),i=r?.password;if(!r||!i||!n)throw n&&await t.context.password.hash(n),E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);if(!await t.context.password.verify({hash:i,password:n}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return!0}function mQ(e,t,n){let r=t?new URL(t,e.baseURL):new URL(`${e.baseURL}/error`);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}function spe(e,t,n){let r=new URL(t,e.baseURL);return n&&Object.entries(n).forEach(([e,t])=>r.searchParams.set(e,t)),r.href}const cpe=X(`/request-password-reset`,{method:`POST`,body:A({email:Fe().meta({description:`The email address of the user to send a password reset email to`}),redirectTo:k().meta({description:"The URL to redirect the user to reset their password. If the token isn't valid or expired, it'll be redirected with a query parameter `?error=INVALID_TOKEN`. If the token is valid, it'll be redirected with a query parameter `?token=VALID_TOKEN"}).optional()}),metadata:{openapi:{operationId:`requestPasswordReset`,description:`Send a password reset email to the user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`},message:{type:`string`}}}}}}}}},use:[tJ(e=>e.body.redirectTo)]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error(`Reset password isn't enabled.Please pass an emailAndPassword.sendResetPassword function in your auth config!`),E.from(`BAD_REQUEST`,{message:`Reset password isn't enabled`,code:`RESET_PASSWORD_DISABLED`});let{email:t,redirectTo:n}=e.body,r=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!r)return pe(24),await e.context.internalAdapter.findVerificationValue(`dummy-verification-token`),e.context.logger.warn(`Reset Password: User not found`),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`});let i=uG(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,`sec`),a=pe(24);await e.context.internalAdapter.createVerificationValue({value:r.user.id,identifier:`reset-password:${a}`,expiresAt:i});let o=n?encodeURIComponent(n):``,s=`${e.context.baseURL}/reset-password/${a}?callbackURL=${o}`;return await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.sendResetPassword({user:r.user,url:s,token:a},e.request)),e.json({status:!0,message:`If this email exists in our system, check your email for the reset link`})}),lpe=X(`/reset-password/:token`,{method:`GET`,operationId:`resetPasswordCallback`,query:A({callbackURL:k().meta({description:`The URL to redirect the user to reset their password`})}),use:[tJ(e=>e.query.callbackURL)],metadata:{openapi:{operationId:`resetPasswordCallback`,description:`Redirects the user to the callback URL with the token`,parameters:[{name:`token`,in:`path`,required:!0,description:`The token to reset the password`,schema:{type:`string`}},{name:`callbackURL`,in:`query`,required:!0,description:`The URL to redirect the user to reset their password`,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async e=>{let{token:t}=e.params,{callbackURL:n}=e.query;if(!t||!n)throw e.redirect(mQ(e.context,n,{error:`INVALID_TOKEN`}));let r=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!r||r.expiresAt</* @__PURE__ */ new Date?e.redirect(mQ(e.context,n,{error:`INVALID_TOKEN`})):e.redirect(spe(e.context,n,{token:t}))}),upe=X(`/reset-password`,{method:`POST`,operationId:`resetPassword`,query:A({token:k().optional()}).optional(),body:A({newPassword:k().meta({description:`The new password to set`}),token:k().meta({description:`The token to reset the password`}).optional()}),metadata:{openapi:{operationId:`resetPassword`,description:`Reset the password for a user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}}},async e=>{let t=e.body.token||e.query?.token;if(!t)throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN);let{newPassword:n}=e.body;fQ(e,n),pQ(e,n);let r=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(r);if(!i||i.expiresAt</* @__PURE__ */ new Date)throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN);let a=i.value,o=await e.context.internalAdapter.findUserById(a);if(!o)throw E.from(`BAD_REQUEST`,Y.USER_NOT_FOUND);return await ipe(e,a,await e.context.password.hash(n),async()=>{if(!await e.context.internalAdapter.consumeVerificationValue(r))throw E.from(`BAD_REQUEST`,Y.INVALID_TOKEN)}),e.context.options.emailAndPassword?.onPasswordReset&&await e.context.options.emailAndPassword.onPasswordReset({user:o},e.request),e.json({status:!0})}),dpe=X(`/verify-password`,{method:`POST`,body:A({password:k().meta({description:`The password to verify`})}),metadata:{scope:`server`,openapi:{operationId:`verifyPassword`,description:`Verify the current user's password`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`}}}}}}}}},use:[HJ]},async e=>{let{password:t}=e.body,n=e.context.session;if(!await ape(e,{password:t,userId:n.user.id}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return e.json({status:!0})}),fpe=A({callbackURL:k().meta({description:`Callback URL to redirect to after the user has signed in`}).optional(),newUserCallbackURL:k().optional(),errorCallbackURL:k().meta({description:`Callback URL to redirect to if an error happens`}).optional(),provider:rQ,disableRedirect:He().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),idToken:Xe(A({token:k().meta({description:`ID token from the provider`}),nonce:k().meta({description:`Nonce used to generate the token`}).optional(),accessToken:k().meta({description:`Access token from the provider`}).optional(),refreshToken:k().meta({description:`Refresh token from the provider`}).optional(),expiresAt:Me().meta({description:`Expiry date of the token`}).optional(),user:A({name:A({firstName:k().optional(),lastName:k().optional()}).optional(),email:k().optional()}).meta({description:`The user object from the provider. Only available for some providers like Apple.`}).optional()})),scopes:Pe(k()).meta({description:`Array of scopes to request from the provider. This will override the default scopes passed.`}).optional(),requestSignUp:He().meta({description:`Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider`}).optional(),loginHint:k().meta({description:`The login hint to use for the authorization code request`}).optional(),additionalParams:QY,additionalData:Ne(k(),Ke()).optional().meta({description:`Additional data to be passed through the OAuth flow`})}),ppe=()=>X(`/sign-in/social`,{method:`POST`,operationId:`socialSignIn`,body:fpe,metadata:{$Infer:{body:{},returned:{}},openapi:{description:`Sign in with a social provider`,operationId:`socialSignIn`,responses:{200:{description:`Success - Returns session details (idToken branch) or an authorize URL (redirect branch)`,content:{"application/json":{schema:{type:`object`,description:`Returns session details when idToken is provided, or an authorize URL otherwise`,properties:{token:{type:`string`},user:{type:`object`,$ref:`#/components/schemas/User`},url:{type:`string`},redirect:{type:`boolean`}},required:[`redirect`]}}}}}}}},async e=>{let t=await AY(e.context.socialProviders,{value:e.body.provider});if(!t)throw e.context.logger.error(`Provider not found. Make sure to add the provider in your auth config`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.PROVIDER_NOT_FOUND);if(e.body.idToken){if(!UZ(t))throw e.context.logger.error(`Provider does not support id token verification`,{provider:e.body.provider}),E.from(`NOT_FOUND`,Y.ID_TOKEN_NOT_SUPPORTED);let{token:n,nonce:r}=e.body.idToken;if(!await WZ(t,n,r,e))throw e.context.logger.warn(`Invalid id token`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.INVALID_TOKEN);let i={idToken:n,accessToken:e.body.idToken.accessToken,refreshToken:e.body.idToken.refreshToken,user:e.body.idToken.user},a=await t.getUserInfo(i);if(!a||!a?.user)throw e.context.logger.error(`Failed to get user info`,{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO);if(!a.user.email)throw e.context.logger.error(wq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await PY(t,i,a.data),s=MY(a.data),c=await KZ(e,{userInfo:{...a.user,email:a.user.email,id:o.accountId,name:a.user.name||``,image:a.user.image,emailVerified:a.user.emailVerified||!1},account:{...o,accessToken:e.body.idToken.accessToken,idToken:n},callbackURL:e.body.callbackURL,disableSignUp:t.disableImplicitSignUp&&!e.body.requestSignUp||t.options?.disableSignUp||t.disableSignUp,source:{method:`oauth`,oauth:{providerId:t.id,profile:s}}});if(c.error)throw c.error===Sq.EMAIL_NOT_VERIFIED?E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED):E.from(`UNAUTHORIZED`,{message:c.error,code:`OAUTH_LINK_ERROR`});return await aq(e,c.data),e.json({redirect:!1,token:c.data.session.token,url:void 0,user:eG(e.context.options,c.data.user)})}let n=jq(t),{codeVerifier:r,state:i}=await Mq(e,{additionalData:e.body.additionalData,idTokenNonce:n}),a=await t.createAuthorizationURL({state:i,codeVerifier:r,idTokenNonce:n,redirectURI:`${e.context.baseURL}${RY(t)}`,scopes:e.body.scopes,loginHint:e.body.loginHint,additionalParams:e.body.additionalParams});return e.body.disableRedirect||e.setHeader(`Location`,a.toString()),e.json({url:a.toString(),redirect:!e.body.disableRedirect})}),mpe=()=>X(`/sign-in/email`,{method:`POST`,operationId:`signInEmail`,use:[rJ],cloneRequest:!0,body:A({email:k().meta({description:`Email of the user`}),password:k().meta({description:`Password of the user`}),callbackURL:k().meta({description:`Callback URL to use as a redirect for email verification`}).optional(),rememberMe:He().meta({description:"If this is false, the session will not be remembered. Default is `true`."}).default(!0).optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signInEmail`,description:`Sign in with email and password`,responses:{200:{description:`Success - Returns either session details or redirect URL`,content:{"application/json":{schema:{type:`object`,description:`Session response when idToken is provided`,properties:{redirect:{type:`boolean`,enum:[!1]},token:{type:`string`,description:`Session token`},url:{type:`string`,nullable:!0},user:{type:`object`,$ref:`#/components/schemas/User`}},required:[`redirect`,`token`,`user`]}}}}}}}},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),E.from(`BAD_REQUEST`,{code:`EMAIL_PASSWORD_DISABLED`,message:`Email and password is not enabled`});let{email:t,password:n}=e.body;if(!Fe().safeParse(t).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);pQ(e,n);let r=await e.context.internalAdapter.findUserByEmail(t.toLowerCase(),{includeAccounts:!0}),i=r?.accounts.find(e=>e.providerId===`credential`&&e.accountId===r.user.id);if(!r||!i)throw await e.context.password.hash(n),e.context.logger.warn(`User not found`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);let a=r.user,o=i.password;if(!o)throw await e.context.password.hash(n),e.context.logger.warn(`Password not found`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);if(!await e.context.password.verify({hash:o,password:n}))throw e.context.logger.warn(`Invalid password`),E.from(`UNAUTHORIZED`,Y.INVALID_EMAIL_OR_PASSWORD);if(e.context.options?.emailAndPassword?.requireEmailVerification&&!a.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED);if(e.context.options?.emailVerification?.sendOnSignIn){let t=await BY(e.context.secret,a.email,void 0,e.context.options.emailVerification?.expiresIn),n=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:a,url:r,token:t},zY(e.request)))}throw E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED)}let s=await e.context.internalAdapter.createSession(a.id,e.body.rememberMe===!1);if(!s)throw e.context.logger.error(`Failed to create session`),E.from(`UNAUTHORIZED`,Y.FAILED_TO_CREATE_SESSION);return await aq(e,{session:s,user:a},e.body.rememberMe===!1),e.body.callbackURL&&e.setHeader(`Location`,e.body.callbackURL),e.json({redirect:!!e.body.callbackURL,token:s.token,url:e.body.callbackURL,user:eG(e.context.options,a)})}),hpe=A({callbackURL:k().meta({description:`The URL to redirect to after provider logout`}).optional(),disableRedirect:He().meta({description:`Return the provider logout URL without redirecting`}).optional(),state:k().meta({description:`State to pass to the provider logout endpoint`}).optional()}).optional(),hQ=e=>({success:!0,url:e?.url,redirect:e?.redirect}),gpe=X(`/sign-out`,{method:`POST`,body:hpe,operationId:`signOut`,requireHeaders:!0,metadata:{openapi:{operationId:`signOut`,description:`Sign out the current user`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`},url:{type:`string`,description:`Provider logout URL when RP-initiated logout is available`},redirect:{type:`boolean`,description:`Whether the client should redirect to the provider logout URL`}}}}}}}}}},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret),n=null;if(t)try{n=await e.context.internalAdapter.findSession(t)}catch(t){e.context.logger.error(`Failed to read session from database`,t)}if(t)try{await e.context.internalAdapter.deleteSession(t)}catch(t){e.context.logger.error(`Failed to delete session from database`,t)}lq(e);let r=await(async()=>{try{if(!n)return null;let t=await e.context.internalAdapter.findAccounts(n.user.id),r=new Map(e.context.socialProviders.map(e=>[e.id,e])),i=t.filter(e=>!!r.get(e.providerId)?.createEndSessionURL).sort((e,t)=>t.updatedAt.getTime()-e.updatedAt.getTime());if(i.length===0)return null;let a=/* @__PURE__ */ new Set,o=e.body?.callbackURL?new URL(e.body.callbackURL,e.context.baseURL).toString():void 0;for(let t of i){if(a.has(t.providerId))continue;a.add(t.providerId);let n=r.get(t.providerId);try{let r=await n?.createEndSessionURL?.({idToken:t.idToken,postLogoutRedirectURI:o,state:e.body?.state});if(r)return r.toString()}catch(n){e.context.logger.error(`Failed to create logout URL for provider "${t.providerId}"`,n)}}return null}catch(t){return e.context.logger.error(`Failed to create provider logout URL`,t),null}})();if(r){let t=!e.body?.disableRedirect;return t&&e.setHeader(`Location`,r),e.json(hQ({url:r,redirect:t}))}return e.json(hQ())}),_pe=A({name:k(),email:Fe(),password:k().nonempty(),image:k().optional(),callbackURL:k().optional(),rememberMe:He().optional()}).and(Ne(k(),Ke())),gQ=()=>X(`/sign-up/email`,{method:`POST`,operationId:`signUpWithEmailAndPassword`,use:[rJ],body:_pe,cloneRequest:!0,metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},returned:{}},openapi:{operationId:`signUpWithEmailAndPassword`,description:`Sign up a user using email and password`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},email:{type:`string`,description:`The email of the user`},password:{type:`string`,description:`The password of the user`},image:{type:`string`,description:`The profile image URL of the user`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`},rememberMe:{type:`boolean`,description:"If this is false, the session will not be remembered. Default is `true`."}},required:[`name`,`email`,`password`]}}}},responses:{200:{description:`Successfully created user`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`Authentication token for the session`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}},422:{description:`Unprocessable Entity. User already exists or failed to create user.`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`}}}}}}}}}},async e=>wH(e.context.adapter,async()=>{if(!e.context.options.emailAndPassword?.enabled||e.context.options.emailAndPassword?.disableSignUp)throw E.from(`BAD_REQUEST`,{message:`Email and password sign up is not enabled`,code:`EMAIL_PASSWORD_SIGN_UP_DISABLED`});let t=e.body,{name:n,email:r,password:i,image:a,callbackURL:o,rememberMe:s,...c}=t;if(!Fe().safeParse(r).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);if(!i||typeof i!=`string`)throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);fQ(e,i),pQ(e,i);let l=e.context.options.emailAndPassword.requireEmailVerification||e.context.options.emailAndPassword.autoSignIn===!1,u=e.context.options.emailAndPassword.autoSignIn===!1||l,d=aG(e.context.options,c,`create`),f=r.toLowerCase(),p=()=>{let t=/* @__PURE__ */ new Date,r=e.context.generateId({model:`user`})||pe(),i={name:n,email:f,emailVerified:!1,image:a??null,createdAt:t,updatedAt:t},o=e.context.options.emailAndPassword?.customSyntheticUser,s;if(o){let t=Object.keys(e.context.options.user?.additionalFields??{}),n={};for(let e of t)e in d&&(n[e]=d[e]);let a=o({coreFields:i,additionalFields:n,id:r});s=tG(e.context.options,a)}else s=tG(e.context.options,{...i,...d,id:r});return e.json({token:null,user:eG(e.context.options,s)})},m=await e.context.internalAdapter.findUserByEmail(f);if(m?.user){if(e.context.logger.info(`Sign-up attempt for existing email: ${r}`),l)return await e.context.password.hash(i),e.context.options.emailAndPassword?.onExistingUserSignUp&&await e.context.runInBackgroundOrAwait(e.context.options.emailAndPassword.onExistingUserSignUp({user:m.user},zY(e.request))),p();throw E.from(`UNPROCESSABLE_ENTITY`,Y.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let h=await e.context.password.hash(i),g;try{if(g=await e.context.internalAdapter.createUser({email:f,name:n,image:a,...d,emailVerified:!1},{method:`email-password`}),!g)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_USER)}catch(t){if(Fq(t)){if(t.statusCode===403&&l)return p();throw t}throw S()&&e.context.logger.error(`Failed to create user`,t),e.context.logger?.error(`Failed to create user`,t),E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER)}if(!g)throw E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:g.id,providerId:`credential`,accountId:g.id,password:h}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await BY(e.context.secret,g.email,void 0,e.context.options.emailVerification?.expiresIn),r=t.callbackURL?encodeURIComponent(t.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:g,url:i,token:n},zY(e.request)))}if(u)return e.json({token:null,user:eG(e.context.options,g)});let _=await e.context.internalAdapter.createSession(g.id,s===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!_)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_SESSION);return await aq(e,{session:_,user:g},s===!1),e.json({token:_.token,user:eG(e.context.options,g)})})),vpe=Ne(k().meta({description:`Field name must be a string`}),Ke()),ype=()=>X(`/update-session`,{method:`POST`,operationId:`updateSession`,body:vpe,use:[VJ],metadata:{$Infer:{body:{}},openapi:{operationId:`updateSession`,description:`Update the current session`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{session:{type:`object`,$ref:`#/components/schemas/Session`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,Y.BODY_MUST_BE_AN_OBJECT);let n=e.context.session,r=sG(e.context.options,t,`update`);if(Object.keys(r).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let i=await e.context.internalAdapter.updateSession(n.session.token,{...r,updatedAt:/* @__PURE__ */ new Date});if(!i&&RJ(e))throw lq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let a=i??{...n.session,...r,updatedAt:/* @__PURE__ */ new Date};return await aq(e,{session:a,user:n.user}),e.json({session:nG(e.context.options,a)})}),bpe=Ne(k().meta({description:`Field name must be a string`}),Ke()),xpe=()=>X(`/update-user`,{method:`POST`,operationId:`updateUser`,body:bpe,use:[VJ],metadata:{$Infer:{body:{}},openapi:{operationId:`updateUser`,description:`Update the current user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{name:{type:`string`,description:`The name of the user`},image:{type:`string`,description:`The image of the user`,nullable:!0}}}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`}}}}}}}}}},async e=>{let t=e.body;if(typeof t!=`object`||Array.isArray(t))throw E.from(`BAD_REQUEST`,Y.BODY_MUST_BE_AN_OBJECT);if(t.email)throw E.from(`BAD_REQUEST`,Y.EMAIL_CAN_NOT_BE_UPDATED);let{name:n,image:r,...i}=t,a=e.context.session,o=aG(e.context.options,i,`update`);if(r===void 0&&n===void 0&&Object.keys(o).length===0)throw E.fromStatus(`BAD_REQUEST`,{message:`No fields to update`});let s=await e.context.internalAdapter.updateUser(a.user.id,{name:n,image:r,...o})??{...a.user,...n!==void 0&&{name:n},...r!==void 0&&{image:r},...o};return await aq(e,{session:a.session,user:s}),e.json({status:!0})}),Spe=X(`/change-password`,{method:`POST`,operationId:`changePassword`,body:A({newPassword:k().meta({description:`The new password to set`}),currentPassword:k().meta({description:`The current password is required`}),revokeOtherSessions:He().meta({description:`Must be a boolean value`}).optional()}),use:[HJ],metadata:{openapi:{operationId:`changePassword`,description:`Change the password of the user`,responses:{200:{description:`Password successfully changed`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`,nullable:!0,description:`New session token if other sessions were revoked`},user:{type:`object`,properties:{id:{type:`string`,description:`The unique identifier of the user`},email:{type:`string`,format:`email`,description:`The email address of the user`},name:{type:`string`,description:`The name of the user`},image:{type:`string`,format:`uri`,nullable:!0,description:`The profile image URL of the user`},emailVerified:{type:`boolean`,description:`Whether the email has been verified`},createdAt:{type:`string`,format:`date-time`,description:`When the user was created`},updatedAt:{type:`string`,format:`date-time`,description:`When the user was last updated`}},required:[`id`,`email`,`name`,`emailVerified`,`createdAt`,`updatedAt`]}},required:[`user`]}}}}}}}},async e=>{let{newPassword:t,currentPassword:n,revokeOtherSessions:r}=e.body,i=e.context.session;fQ(e,t),pQ(e,t),pQ(e,n);let a=await e.context.internalAdapter.findCredentialAccount(i.user.id);if(!a||!a.password)throw E.from(`BAD_REQUEST`,Y.CREDENTIAL_ACCOUNT_NOT_FOUND);let o=await e.context.password.hash(t);if(!await e.context.password.verify({hash:a.password,password:n}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);let s=await wH(e.context.adapter,async()=>{if(r&&await e.context.internalAdapter.deleteUserSessions(i.user.id),await e.context.internalAdapter.updateAccount(a.id,{password:o}),!r)return null;let t=await e.context.internalAdapter.createSession(i.user.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!t)throw E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION);return t}),c=null;return s&&(await aq(e,{session:s,user:i.user}),c=s.token),e.json({token:c,user:eG(e.context.options,i.user)})}),Cpe=X.serverOnly({method:`POST`,body:A({newPassword:k().meta({description:`The new password to set is required`})}),use:[HJ]},async e=>{let{newPassword:t}=e.body,n=e.context.session;fQ(e,t),pQ(e,t);let r=await e.context.internalAdapter.findCredentialAccount(n.user.id),i=await e.context.password.hash(t);if(!r)return await e.context.internalAdapter.linkAccount({userId:n.user.id,providerId:`credential`,accountId:n.user.id,password:i}),e.json({status:!0});if(!r.password)return await e.context.internalAdapter.updateAccount(r.id,{password:i}),e.json({status:!0});throw E.from(`BAD_REQUEST`,Y.PASSWORD_ALREADY_SET)}),wpe=X(`/delete-user`,{method:`POST`,use:[HJ],body:A({callbackURL:k().meta({description:`The callback URL to redirect to after the user is deleted`}).optional(),password:k().meta({description:`The password of the user is required to delete the user`}).optional(),token:k().meta({description:`The token to delete the user is required`}).optional()}),metadata:{openapi:{operationId:`deleteUser`,description:`Delete the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{callbackURL:{type:`string`,description:`The callback URL to redirect to after the user is deleted`},password:{type:`string`,description:`The user's password. Required if session is not fresh`},token:{type:`string`,description:`The deletion verification token`}}}}}},responses:{200:{description:`User deletion processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the operation was successful`},message:{type:`string`,enum:[`User deleted`,`Verification email sent`],description:`Status message of the deletion process`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.fromStatus(`NOT_FOUND`);let t=e.context.session;if(e.body.password){pQ(e,e.body.password);let n=await e.context.internalAdapter.findCredentialAccount(t.user.id);if(!n||!n.password)throw E.from(`BAD_REQUEST`,Y.CREDENTIAL_ACCOUNT_NOT_FOUND);if(!await e.context.password.verify({hash:n.password,password:e.body.password}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD)}if(e.body.token)return await _Q({...e,query:{token:e.body.token}}),e.json({success:!0,message:`User deleted`});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=JH(32,`0-9`,`a-z`);await e.context.internalAdapter.createVerificationValue({value:t.user.id,identifier:`delete-account-${n}`,expiresAt:new Date(Date.now()+(e.context.options.user.deleteUser?.deleteTokenExpiresIn||86400)*1e3)});let r=`${e.context.baseURL}/delete-user/callback?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(e.context.options.user.deleteUser.sendDeleteAccountVerification({user:t.user,url:r,token:n},e.request)),e.json({success:!0,message:`Verification email sent`})}if(!e.body.password&&e.context.sessionConfig.freshAge!==0){let n=new Date(t.session.createdAt).getTime(),r=e.context.sessionConfig.freshAge*1e3;if(Date.now()-n>=r)throw E.from(`BAD_REQUEST`,Y.SESSION_EXPIRED)}let n=e.context.options.user.deleteUser?.beforeDelete;n&&await n(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),lq(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(t.user,e.request),e.json({success:!0,message:`User deleted`})}),_Q=X(`/delete-user/callback`,{method:`GET`,query:A({token:k().meta({description:`The token to verify the deletion request`}),callbackURL:k().meta({description:`The URL to redirect to after deletion`}).optional()}),use:[tJ(e=>e.query.callbackURL)],metadata:{openapi:{description:`Callback to complete user deletion with verification token`,responses:{200:{description:`User successfully deleted`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the deletion was successful`},message:{type:`string`,enum:[`User deleted`],description:`Confirmation message`}},required:[`success`,`message`]}}}}}}}},async e=>{if(!e.context.options.user?.deleteUser?.enabled)throw e.context.logger.error(`Delete user is disabled. Enable it in the options`),E.from(`NOT_FOUND`,{message:`Not found`,code:`NOT_FOUND`});let t=await zJ(e,{disableCookieCache:RJ(e)});if(!t)throw E.from(`NOT_FOUND`,Y.FAILED_TO_GET_USER_INFO);let n=await e.context.internalAdapter.consumeVerificationValue(`delete-account-${e.query.token}`);if(!n||n.value!==t.user.id)throw E.from(`NOT_FOUND`,Y.INVALID_TOKEN);let r=e.context.options.user.deleteUser?.beforeDelete;r&&await r(t.user,e.request),await e.context.internalAdapter.deleteUser(t.user.id),await e.context.internalAdapter.deleteUserSessions(t.user.id),await e.context.internalAdapter.deleteAccounts(t.user.id),lq(e);let i=e.context.options.user.deleteUser?.afterDelete;if(i&&await i(t.user,e.request),e.query.callbackURL)throw e.redirect(e.query.callbackURL||`/`);return e.json({success:!0,message:`User deleted`})}),Tpe=X(`/change-email`,{method:`POST`,body:A({newEmail:Fe().meta({description:`The new email address to set must be a valid email address`}),callbackURL:k().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[HJ],metadata:{openapi:{operationId:`changeEmail`,responses:{200:{description:`Email change request processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the request was successful`},message:{type:`string`,enum:[`Email updated`,`Verification email sent`],description:`Status message of the email change process`,nullable:!0}},required:[`status`]}}}}}}}},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error(`Change email is disabled.`),E.from(`BAD_REQUEST`,Y.CHANGE_EMAIL_DISABLED);let t=e.body.newEmail.toLowerCase();if(t===e.context.session.user.email)throw e.context.logger.warn(`Email is the same`),E.fromStatus(`BAD_REQUEST`,{message:`Email is the same`});let n=e.context.session.user.emailVerified!==!0&&e.context.options.user.changeEmail.updateEmailWithoutVerification,r=e.context.options.emailVerification?.sendVerificationEmail,i=r&&e.context.session.user.emailVerified&&e.context.options.user.changeEmail.sendChangeEmailConfirmation;if(!n&&!i&&!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});if(await e.context.internalAdapter.findUserByEmail(t))return await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn),e.context.logger.info(`Change email attempt for existing email`),e.json({status:!0});if(n){if(await e.context.internalAdapter.updateUser(e.context.session.user.id,{email:t}),await aq(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),r){let n=await BY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn),i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:i,token:n},e.request))}return e.json({status:!0})}if(i){let n=await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-confirmation`}),r=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(i({user:e.context.session.user,newEmail:t,url:r,token:n},e.request)),e.json({status:!0})}if(!r)throw e.context.logger.error(`Verification email isn't enabled.`),E.fromStatus(`BAD_REQUEST`,{message:`Verification email isn't enabled`});let a=await BY(e.context.secret,e.context.session.user.email,t,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),o=`${e.context.baseURL}/verify-email?token=${a}&callbackURL=${encodeURIComponent(e.body.callbackURL||`/`)}`;return await e.context.runInBackgroundOrAwait(r({user:{...e.context.session.user,email:t},url:o,token:a},e.request)),e.json({status:!0})}),vQ=sY((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),yQ=/* @__PURE__ */ new WeakMap;function bQ(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function xQ(e,t){t&&t.forEach((t,n)=>{e.responseHeaders?n.toLowerCase()===`set-cookie`?e.responseHeaders.append(n,t):e.responseHeaders.set(n,t):e.responseHeaders=new Headers({[n]:t})})}function SQ(e){let t=e[je],n=e.headers&&e.headers!==t?new Headers(e.headers):null;if(!t&&!n)return null;let r=new Headers;return t?.forEach((e,t)=>{r.append(t,e)}),n?.forEach((e,t)=>{t.toLowerCase()===`set-cookie`?r.append(t,e):r.set(t,e)}),r}async function Epe(e,t,n,r){let i=oe(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=yQ.get(o.handler)??`unknown`;throw e.context.logger.error(`An error occurred during ${n} hook matcher execution:`,t),new E(`INTERNAL_SERVER_ERROR`,{message:`An error occurred during hook matcher execution. Check the logs for more details.`})}if(!t)continue;let s=yQ.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[eY]:`before`,[ge]:c,[tY]:s,[$J]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw Fq(t)&&me(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});xQ(e.context,l?.headers);let u=l?.response;if(u&&typeof u==`object`){if(`context`in u&&typeof u.context==`object`){let{headers:e,...t}=u.context;e instanceof Headers&&(a.headers?e.forEach((e,t)=>{a.headers?.set(t,e)}):a.headers=e),a=vQ(t,a);continue}return u}}return{context:a}}async function Dpe(e,t,n,r){let i=oe(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=yQ.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[eY]:`after`,[ge]:o,[tY]:t,[$J]:r},()=>a.handler(e)).catch(t=>{if(Fq(t))return me(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:SQ(t)};throw t});xQ(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function Ope(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(yQ.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(yQ.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(yQ.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(yQ.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function CQ(e,t){let n=oe(t.context.options),r=t.operationId??bQ(e),i=e.path??`/:virtual`,a=e.options?.method,o=Array.isArray(a)?a[0]:a,s=t.method??t.request?.method??o??`?`,c=t.asResponse??HH(t.request),l={...t,context:{...t.context,returned:void 0,responseHeaders:void 0,session:t.context.session??null},path:e.path,headers:t.headers?new Headers(t.headers):void 0};return n(`${s} ${i}`,{[ge]:i,[$J]:r},async()=>mH(l,async()=>{let{beforeHooks:a,afterHooks:o}=Ope(l.context),s=await Epe(l,a,e,r);if(`context`in s&&s.context&&typeof s.context==`object`){let{headers:e,...t}=s.context;if(e){l.headers||(l.headers=new Headers);let t=l.headers;e.forEach((e,n)=>{t.set(n,e)})}l=vQ(t,l)}else if(s){let e=l.context.responseHeaders;return c?nK(s,{headers:e}):t.returnHeaders?{headers:e,response:s}:s}l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let u=await mH(l,()=>n(`handler ${i}`,{[ge]:i,[$J]:r},()=>e(l))).catch(e=>{if(Fq(e))return{response:e,status:e.statusCode,headers:SQ(e)};throw e});if(u instanceof Response)return u;l.context.returned=u.response,l.context.responseHeaders=u.headers??void 0;let d=await Dpe(l,o,e,r);if(d.response!==void 0&&(u.response=d.response),u.headers=d.headers??u.headers,Fq(u.response)&&me(l.context.logger.level,`debug`)&&(u.response.stack=u.response.errorStack),Fq(u.response)&&!c)throw u.headers&&Object.defineProperty(u.response,je,{enumerable:!1,configurable:!0,writable:!1,value:u.headers}),u.response;return c?nK(u.response,{headers:u.headers??void 0,status:u.status}):t.returnHeaders?t.returnStatus?{headers:u.headers,response:u.response,status:u.status}:{headers:u.headers,response:u.response}:t.returnStatus?{response:u.response,status:u.status}:u.response}))}async function kpe(e,t){if(e.baseURL)return e;let n=DY(t),r=e.options.baseURL,i=VH(r)&&!!r.fallback;if(n===void 0&&!i)throw new E(`INTERNAL_SERVER_ERROR`,{message:"Dynamic baseURL could not be resolved for this direct auth.api call. Pass `headers: request.headers` (or `request`) to the call, or add `fallback` to your baseURL config."});try{return await kY(e,n,OY(e.options))}catch(e){throw e instanceof D?new E(`INTERNAL_SERVER_ERROR`,{message:e.message}):e}}function Ape(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=async e=>{let n=bQ(i,r),a=async()=>{let r=await t,a=r.checkSchema?.();a&&await a;let o=VH(r.options.baseURL)?await kpe(r,e):r;return CQ(i,{...e,context:o,operationId:n,asResponse:e?.asResponse??HH(e?.request)})};return await gH()?a():vH(/* @__PURE__ */ new WeakMap,a)},n[r].path=i.path,n[r].options=i.options;return n}function jpe(e,t){let n=/* @__PURE__ */ new Map;e.plugins?.forEach(e=>{if(e.endpoints){for(let[t,r]of Object.entries(e.endpoints))if(r&&`path`in r&&typeof r.path==`string`){let i=r.path,a=[];r.options&&`method`in r.options&&(Array.isArray(r.options.method)?a=r.options.method:typeof r.options.method==`string`&&(a=[r.options.method])),a.length===0&&(a=[`*`]),n.has(i)||n.set(i,[]),n.get(i).push({pluginId:e.id,endpointKey:t,methods:a})}}});let r=[];for(let[e,t]of n.entries())if(t.length>1){let n=/* @__PURE__ */ new Map,i=!1;for(let e of t)for(let r of e.methods)n.has(r)||n.set(r,[]),n.get(r).push(e.pluginId),n.get(r).length>1&&(i=!0),(r===`*`&&t.length>1||r!==`*`&&n.has(`*`))&&(i=!0);if(i){let i=[...new Set(t.map(e=>e.pluginId))],a=[];for(let[e,r]of n.entries())(r.length>1||e===`*`&&t.length>1||e!==`*`&&n.has(`*`))&&a.push(e);r.push({path:e,plugins:i,conflictingMethods:a})}}if(r.length>0){let e=r.map(e=>` - "${e.path}" [${e.conflictingMethods.join(`, `)}] used by plugins: ${e.plugins.join(`, `)}`).join(`
408
+ `);t.error(`Endpoint path conflicts detected! Multiple plugins are trying to use the same endpoint paths with conflicting HTTP methods:
409
+ ${e}
410
+
411
+ To resolve this, you can:
412
+ 1. Use only one of the conflicting plugins
413
+ 2. Configure the plugins to use different paths (if supported)
414
+ 3. Ensure plugins use different HTTP methods for the same path
415
+ `)}}function wQ(e,t){let n=oe(t),r=t.plugins?.reduce((e,t)=>({...e,...t.endpoints}),{})??{},i=t.plugins?.map(t=>t.middlewares?.map(r=>{let i=(async i=>{let a=await e;return n(`middleware ${r.path} ${t.id}`,{"better_auth.hook.type":`middleware`,"http.route":r.path,"better_auth.context":`plugin:${t.id}`},()=>r.middleware({...i,context:{...a,...i.context}}))});return i.options=r.middleware.options,{path:r.path,middleware:i}})).filter(e=>e!==void 0).flat()||[];return{api:Ape({signInSocial:ppe(),callbackOAuth:epe,getSession:LJ(),signOut:gpe,signUpEmail:gQ(),signInEmail:mpe(),resetPassword:upe,verifyPassword:dpe,verifyEmail:UY,sendVerificationEmail:HY,changeEmail:Tpe,changePassword:Spe,setPassword:Cpe,updateSession:ype(),updateUser:xpe(),deleteUser:wpe,requestPasswordReset:cpe,requestPasswordResetCallback:lpe,listSessions:WJ(),revokeSession:GJ,revokeSessions:KJ,revokeOtherSessions:qJ,linkSocialAccount:Yfe,listUserAccounts:Jfe,deleteUserCallback:_Q,unlinkAccount:Xfe,refreshToken:Qfe,getAccessToken:Zfe,accountInfo:$fe,...r,ok:rpe,error:npe},e),middlewares:i}}const Mpe=(e,t)=>{let n=oe(t),{api:r,middlewares:i}=wQ(e,t),a=new URL(e.baseURL).pathname;return LK(r,{routerContext:e,openapi:{disabled:!0},basePath:a,routerMiddleware:[{path:`/**`,middleware:eJ},...i],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],i=vq(t.url,a);if(r.includes(i))return new Response(`Not Found`,{status:404});let o=e.checkSchema?.();o&&await o;let s=t,c=await PJ(s,e);if(c)return c;for(let t of e.options.plugins||[])if(t.onRequest){let r=await n(`onRequest ${t.id}`,{[eY]:`onRequest`,[tY]:`plugin:${t.id}`},()=>t.onRequest(s,e));if(r&&`response`in r)return r.response;r&&`request`in r&&(s=r.request)}return s},async onResponse(t,r){for(let r of e.options.plugins||[])if(r.onResponse){let i=await n(`onResponse ${r.id}`,{[eY]:`onResponse`,[tY]:`plugin:${r.id}`,[ce]:t.status},()=>r.onResponse(t,e));if(i)return i.response}return t},async onError(n){if(Fq(n)&&n.status===`FOUND`)return;if(t.onAPIError?.throw)throw n;if(t.onAPIError?.onError){try{await t.onAPIError.onError(n,e)}catch(t){e.logger.error(`onAPIError.onError threw`,t)}return}let r=t.logger?.level,i=r===`error`||r===`warn`||r===`debug`?f:void 0;if(t.logger?.disabled!==!0){if(n&&typeof n==`object`&&`message`in n&&typeof n.message==`string`&&(n.message.includes(`no column`)||n.message.includes(`column`)||n.message.includes(`relation`)||n.message.includes(`table`)||n.message.includes(`does not exist`))){e.logger?.error(n.message);return}Fq(n)?(n.status===`INTERNAL_SERVER_ERROR`&&e.logger.error(n.status,n),i?.error(n.message)):e.logger?.error(n&&typeof n==`object`&&`name`in n?n.name:``,n)}}})};async function Npe(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=p(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./dist-Dse7wyrJ.mjs`);n=i(r)(e)}return n.transaction||(f.warn(`Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.`),n.transaction=async e=>e(n)),n}async function Ppe(e){return Npe(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./kysely-adapter-7Yeuf8Dd.mjs`),{kysely:r,databaseType:i,transaction:a}=await t(e);if(!r)throw new D(`Failed to initialize database adapter`);return n(r,{type:i||`sqlite`,debugLogs:e.database&&`debugLogs`in e.database?e.database.debugLogs:!1,transaction:a})(e)})}function Fpe(e){let{indexesByTable:t,tables:n}=re(e),r=/* @__PURE__ */ new Map,i={};for(let e in n){let t=n[e],a=t.fields,o={};Object.entries(a).forEach(([e,t])=>{let i=t.references,a=i?n[i.model]:void 0,s=i&&a?{...t,references:{...i,model:a.modelName}}:t;o[t.fieldName||e]=s,i&&r.set(s,{modelKey:i.model,fieldKey:i.field})}),i[t.modelName]?(i[t.modelName].fields={...i[t.modelName].fields,...o},t.disableMigrations&&(i[t.modelName].disableMigrations=!0)):i[t.modelName]={fields:o,order:t.order||1/0,disableMigrations:t.disableMigrations}}for(let[e,n]of t)i[e]&&(i[e].indexes=n);return{schema:i,tables:n,referenceKeys:r}}const Ipe={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`integer`,`bigint`,`smallint`,`numeric`,`real`,`double precision`],boolean:[`bool`,`boolean`],date:[`timestamptz`,`timestamp`,`date`],json:[`json`,`jsonb`]},mysql:{string:[`varchar`,`text`,`uuid`],number:[`integer`,`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`boolean`,`tinyint`],date:[`timestamp`,`datetime`,`date`],json:[`json`]},sqlite:{string:[`TEXT`],number:[`INTEGER`,`REAL`,`BIGINT`],boolean:[`INTEGER`,`BOOLEAN`],date:[`DATE`,`INTEGER`],json:[`TEXT`]},mssql:{string:[`varchar`,`nvarchar`,`uniqueidentifier`],number:[`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`bit`,`smallint`],date:[`datetime2`,`date`,`datetime`],json:[`varchar`,`nvarchar`]}};function TQ(e,t){return`${ie(e)}\u0000${ie(t)}`}function EQ(e,t){return`${e}\u0000${t}`}function DQ(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,n)=>e===t.columns[n])}function OQ(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function kQ(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[TQ(e.table,e.name),{columns:t.flatMap(e=>e.name===null?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>e.name!==null&&e.fullLength)}]}))}async function Lpe(e,n,r,i){if(i)return kQ(await i(r));let a;switch(n.type){case`sqlite`:a=(await t`
416
+ SELECT
417
+ tables.name AS "tableName",
418
+ index_list.name AS "indexName",
419
+ index_info.name AS "columnName",
420
+ index_list."unique" AS "isUnique",
421
+ index_list.partial AS "isPartial",
422
+ index_info.seqno AS "columnPosition"
423
+ FROM sqlite_master AS tables
424
+ INNER JOIN pragma_index_list(tables.name) AS index_list
425
+ INNER JOIN pragma_index_info(index_list.name) AS index_info
426
+ WHERE tables.type = 'table'
427
+ `.execute(e)).rows;break;case`postgres`:a=(await t`
428
+ SELECT
429
+ table_class.relname AS "tableName",
430
+ index_class.relname AS "indexName",
431
+ index_attribute.attname AS "columnName",
432
+ index_data.indisunique AS "isUnique",
433
+ index_data.indisvalid AS "isValid",
434
+ (index_data.indpred IS NOT NULL) AS "isPartial",
435
+ index_column.ordinality AS "columnPosition"
436
+ FROM pg_class AS table_class
437
+ INNER JOIN pg_namespace AS table_namespace
438
+ ON table_namespace.oid = table_class.relnamespace
439
+ INNER JOIN pg_index AS index_data
440
+ ON index_data.indrelid = table_class.oid
441
+ INNER JOIN pg_class AS index_class
442
+ ON index_class.oid = index_data.indexrelid
443
+ INNER JOIN LATERAL unnest(index_data.indkey)
444
+ WITH ORDINALITY AS index_column(attribute_number, ordinality)
445
+ ON TRUE
446
+ LEFT JOIN pg_attribute AS index_attribute
447
+ ON index_attribute.attrelid = table_class.oid
448
+ AND index_attribute.attnum = index_column.attribute_number
449
+ WHERE table_namespace.nspname = ${n.schema}
450
+ AND table_class.relkind = 'r'
451
+ AND index_column.ordinality <= index_data.indnkeyatts
452
+ `.execute(e)).rows;break;case`mysql`:a=(await t`
453
+ SELECT
454
+ table_name AS tableName,
455
+ index_name AS indexName,
456
+ column_name AS columnName,
457
+ non_unique AS nonUnique,
458
+ seq_in_index AS columnPosition,
459
+ sub_part AS prefixLength,
460
+ COALESCE(LOWER(comment) = 'disabled', FALSE) AS isDisabled
461
+ FROM information_schema.statistics
462
+ WHERE table_schema = DATABASE()
463
+ `.execute(e)).rows;break;case`mssql`:a=(await t`
464
+ SELECT
465
+ tables.name AS "tableName",
466
+ indexes.name AS "indexName",
467
+ columns.name AS "columnName",
468
+ indexes.is_unique AS "isUnique",
469
+ indexes.is_disabled AS "isDisabled",
470
+ indexes.is_hypothetical AS "isHypothetical",
471
+ indexes.has_filter AS "isPartial",
472
+ index_columns.key_ordinal AS "columnPosition"
473
+ FROM sys.indexes AS indexes
474
+ INNER JOIN sys.tables AS tables
475
+ ON indexes.object_id = tables.object_id
476
+ INNER JOIN sys.schemas AS table_schemas
477
+ ON table_schemas.schema_id = tables.schema_id
478
+ INNER JOIN sys.index_columns AS index_columns
479
+ ON index_columns.object_id = indexes.object_id
480
+ AND index_columns.index_id = indexes.index_id
481
+ INNER JOIN sys.columns AS columns
482
+ ON columns.object_id = index_columns.object_id
483
+ AND columns.column_id = index_columns.column_id
484
+ WHERE table_schemas.name = ${n.schema}
485
+ AND indexes.name IS NOT NULL
486
+ AND index_columns.key_ordinal > 0
487
+ `.execute(e)).rows}let o=/* @__PURE__ */ new Map;for(let e of a){let t=e.tableName??e.table_name??e.TABLE_NAME??e.tablename??e.tbl_name,n=e.indexName??e.index_name??e.INDEX_NAME??e.name,r=e.columnName??e.column_name??e.COLUMN_NAME;if(!t||!n)continue;let i=TQ(t,n),a=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=a===void 0?OQ(e.isUnique??e.is_unique):!OQ(a),c=Number(e.columnPosition??e.column_position??e.keyOrdinal??e.key_ordinal??e.ordinality??e.seqInIndex??e.seq_in_index??e.SEQ_IN_INDEX??e.seqno??0),l={fullLength:r!=null&&(e.prefixLength===void 0||e.prefixLength===null),name:r??null,position:c},u=OQ(e.isPartial),d=!OQ(e.isDisabled)&&!OQ(e.isHypothetical)&&(e.isValid===void 0||OQ(e.isValid)),f=o.get(i);o.set(i,f?{...f,columns:[...f.columns,l],partial:f.partial||u,valid:f.valid&&d}:{columns:[l],name:n,partial:u,table:t,unique:s,valid:d})}return kQ([...o.values()])}async function Rpe(e,n){let r;switch(n.type){case`postgres`:case`sqlite`:return/* @__PURE__ */ new Map;case`mysql`:r=(await t`
488
+ SELECT
489
+ table_name AS tableName,
490
+ column_name AS columnName,
491
+ character_octet_length AS maxIndexBytes
492
+ FROM information_schema.columns
493
+ WHERE table_schema = DATABASE()
494
+ `.execute(e)).rows;break;case`mssql`:r=(await t`
495
+ SELECT
496
+ tables.name AS "tableName",
497
+ columns.name AS "columnName",
498
+ columns.max_length AS "maxIndexBytes"
499
+ FROM sys.columns AS columns
500
+ INNER JOIN sys.tables AS tables
501
+ ON tables.object_id = columns.object_id
502
+ INNER JOIN sys.schemas AS table_schemas
503
+ ON table_schemas.schema_id = tables.schema_id
504
+ WHERE table_schemas.name = ${n.schema}
505
+ `.execute(e)).rows}let i=/* @__PURE__ */ new Map;for(let e of r){let t=e.tableName??e.TABLE_NAME,n=e.columnName??e.COLUMN_NAME;if(!t||!n)continue;let r=Number(e.maxIndexBytes??e.MAX_INDEX_BYTES??-1);i.set(EQ(t,n),{maxIndexBytes:r<0?null:r})}return i}function zpe({columnBounds:e,dbType:t,existingColumns:n,fields:r,indexes:i,index:a,table:o}){let s=t===`mysql`?3072:1700,c=0;for(let s of a.columns){let l=r[s];if(l){if(l.type===`string`||Array.isArray(l.type)){if(!n.has(s)){let e=T({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let l=e.get(EQ(o,s));if(!l?.maxIndexBytes)throw new D(`Cannot create database index "${a.name}" on existing table "${o}" because column "${s}" is not bounded for ${t===`mysql`?`MySQL`:`SQL Server`}. Change it to a bounded string column, resolve oversized values, then run the migration again.`);c+=l.maxIndexBytes}else c+=16}}if(c>s)throw new D(`Cannot create database index "${a.name}" on existing table "${o}" because its columns can exceed ${t===`mysql`?`MySQL`:`SQL Server`}'s ${s}-byte index-key limit. Bound the indexed string columns to the generated schema lengths, resolve oversized values, then run the migration again.`)}var Bpe=class extends D{};function Vpe(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function Hpe(e){return!(e.unique&&e.required===!1)&&(e.type===`string`||e.type===`number`||e.type===`boolean`)&&e.defaultValue!==void 0&&e.defaultValue!==null&&typeof e.defaultValue!=`function`}async function Upe(e,n,r){let i=e.selectFrom(r).select(t`1`.as(`present`));return(await(n===`mssql`?i.top(1):i.limit(1)).execute()).length>0}function Wpe(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=Ipe[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function AQ(e,{throwOnUnsafe:n=!0}={}){let{schema:r,tables:i,referenceKeys:o}=Fpe(e),d=he(e.logger),f=[],p=e=>{if(n)throw new Bpe(e);f.push(e)},{kysely:m,databaseType:h,introspectIndexes:g,schemaName:_}=await u(e);h||=(d.warn(`Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.`),`sqlite`),m||(d.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let v=await m.introspection.getTables(),b,x=v;switch(h){case`postgres`:{let e=_??await a(m);b={type:`postgres`,schema:e},d.debug(`PostgreSQL migration: Using schema '${e}' (${_?`from database.schemaName`:`from search_path`})`);try{(await m.introspection.getSchemas()).some(({name:t})=>t===e)||(_?d.debug(`Schema '${e}' does not exist yet. The migration creates it before creating tables.`):d.warn(`Schema '${e}' does not exist. Create it before running migrations or check your database configuration.`))}catch(e){d.debug(`Could not verify schema existence: ${e instanceof Error?e.message:String(e)}`)}x=v.filter(t=>t.schema===e&&!t.isView&&!(`isForeign`in t&&t.isForeign)),d.debug(`Found ${x.length} table(s) in schema '${e}': ${x.map(e=>e.name).join(`, `)||`(none)`}`);break}case`mssql`:{let e=await c(m);b={type:`mssql`,schema:e},d.debug(`SQL Server migration: Using schema '${e}' (from the current user's default schema)`),x=v.filter(t=>t.schema===e);break}case`mysql`:b={type:`mysql`};break;case`sqlite`:b={type:`sqlite`}}let S=await Lpe(m,b,v.map(e=>e.name),g),ee=await Rpe(m,b),C=lee(l(m,r),s(x)).filter(e=>e.kind===`unexpected-required-column`).map(e=>uee(e,`database`)),te=[],ne=[],w=[],re=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(r)){if(t.disableMigrations)continue;let n=x.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=TQ(e,i),o=S.get(a);if(o){if(!DQ(o,r))throw new D(`Database index "${i}" on table "${e}" does not match the configured fields and uniqueness. Rename or replace the existing index, then run the migration again.`);continue}if(h===`sqlite`||h===`postgres`){let t=[...S.values()].find(t=>ie(t.name)===ie(i)&&ie(t.table)!==ie(e));if(t)throw new D(`Database index name "${i}" is already used by table "${t.table}". Index names must be unique across the schema.`)}let s=re.get(a);if(s){if(!DQ({columns:s.columns,name:s.name,table:e,unique:s.unique??!1,validFullColumns:!0},r))throw new D(`Database index name "${i}" identifies more than one index on table "${e}".`)}else n&&(h===`mysql`||h===`mssql`)&&zpe({columnBounds:ee,dbType:h,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),re.set(a,r),w.push({table:e,index:r,name:i})}if(!n){let n=te.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=te.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?te.push(r):te[n].fields={...te[n].fields,...t.fields}:te.splice(i,0,r);continue}let r={};for(let[i,a]of Object.entries(t.fields)){let t=n.columns.find(e=>e.name===i);t?(a.required!==!1&&t.isNullable&&d.warn(`Column "${i}" on table "${e}" stays nullable while the schema declares the field required, so existing rows can still hold null. Backfill every row for this column and enforce NOT NULL to remove the drift.`),!Wpe(t.dataType,a.type,h)&&d.warn(`Field ${i} in table ${e} has a different type in the database. Expected ${a.type} but got ${t.dataType}.`)):r[i]=a}Object.keys(r).length>0&&ne.push({table:e,fields:r,order:t.order||1/0})}let ae=[];_&&te.length>0&&ae.push(m.schema.createSchema(_).ifNotExists());let oe=e.advanced?.database?.generateId===`uuid`,se=e.advanced?.database?.generateId===`serial`;function ce(e,n,r){let i=e.type,a=h||`sqlite`,o={string:{sqlite:`text`,postgres:`text`,mysql:r?`varchar(${r})`:e.unique?`varchar(255)`:e.references?`varchar(36)`:e.sortable||e.index?`varchar(255)`:`text`,mssql:r?`varchar(${r})`:e.unique||e.sortable?`varchar(255)`:e.references?`varchar(36)`:`varchar(8000)`},boolean:{sqlite:`integer`,postgres:`boolean`,mysql:`boolean`,mssql:`smallint`},number:{sqlite:e.bigint?`bigint`:`integer`,postgres:e.bigint?`bigint`:`integer`,mysql:e.bigint?`bigint`:`integer`,mssql:e.bigint?`bigint`:`integer`},date:{sqlite:`date`,postgres:`timestamptz`,mysql:`timestamp(3)`,mssql:t`datetime2(3)`},json:{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},id:{postgres:se?t`integer GENERATED BY DEFAULT AS IDENTITY`:oe?`uuid`:`text`,mysql:se?`integer`:`varchar(36)`,mssql:se?`integer`:`varchar(36)`,sqlite:se?`integer`:`text`},foreignKeyId:{postgres:se?`integer`:oe?`uuid`:`text`,mysql:se?`integer`:`varchar(36)`,mssql:se?`integer`:`varchar(36)`,sqlite:se?`integer`:`text`},"string[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`},"number[]":{sqlite:`text`,postgres:`jsonb`,mysql:`json`,mssql:`varchar(8000)`}};if(n===`id`||e.references?.field===`id`)return n===`id`?o.id[a]:o.foreignKeyId[a];if(Array.isArray(i))return`text`;if(!(i in o))throw Error(`Unsupported field type '${String(i)}' for field '${n}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return o[i][a]}let le=mee({schema:i,usePlural:!1}),ue=Qe({schema:i,usePlural:!1});function de(e){let t=e.references;if(!t)throw new D(`Cannot resolve a field without references.`);let n=o.get(e);if(!n)throw new D(`Missing migration reference metadata for "${t.model}.${t.field}".`);try{return`${le(n.modelKey)}.${ue({model:n.modelKey,field:n.fieldKey})}`}catch{return`${t.model}.${t.field}`}}let fe=[],pe=(e,t)=>{if(h!==`mysql`&&h!==`mssql`)return;let n=r[e];if(n)return T({columnName:t,dialect:h,fields:n.fields,indexes:n.indexes??[]})};if(ne.length){let e=/* @__PURE__ */ new Map;for(let n of ne)for(let[r,i]of Object.entries(n.fields)){let a=Vpe(i,h),o=Hpe(i);if(i.required!==!1&&!a&&!o){let t=e.get(n.table);if(t===void 0&&(t=await Upe(m,h,n.table),e.set(n.table,t)),t){let e=i.type===`string`?` For a text column, every existing row ends up with the same empty string.`:``;p(`Cannot add required column "${r}" to populated table "${n.table}": the schema declares no default value, so existing rows have no value to backfill. MySQL accepts this statement instead of rejecting it and fills every existing row with an implicit default for the column type, reporting a successful migration over corrupted data.${e} Add the column as nullable, backfill a correct value for every row, then make it NOT NULL.`)}}let s=ce(i,r,pe(n.table,r)),c=m.schema.alterTable(n.table);if(i.index||i.unique){let e=y(n.table,r,i.unique??!1),t=m.schema.createIndex(e).on(n.table).columns([r]);i.unique&&(t=t.unique(),i.required===!1&&h===`mssql`&&(t=t.where(r,`is not`,null)),i.required!==!1&&i.defaultValue!==void 0&&i.defaultValue!==null&&typeof i.defaultValue!=`function`&&d.warn(`Adding unique column "${r}" to existing table "${n.table}" backfills every existing row with its default value. If the table has more than one row, creating the unique index "${e}" will fail; backfill distinct values manually, then re-run the migration or create the index yourself.`)),fe.push(t)}let l=c.addColumn(r,s,e=>(e=i.required===!1?e:e.notNull(),i.references&&(e=e.references(de(i)).onDelete(i.references.onDelete||`cascade`)),a?e=h===`mysql`?e.defaultTo(t`CURRENT_TIMESTAMP(3)`):e.defaultTo(t`CURRENT_TIMESTAMP`):o&&(e=e.defaultTo(typeof i.defaultValue==`boolean`&&(h===`sqlite`||h===`mssql`)?+!!i.defaultValue:i.defaultValue)),e));ae.push(l)}}if(te.length)for(let e of te){let n=ce({type:se?`number`:`string`},`id`),r=m.schema.createTable(e.table).addColumn(`id`,n,e=>se?h===`postgres`||h===`sqlite`?e.primaryKey().notNull():h===`mssql`?e.identity().primaryKey().notNull():e.autoIncrement().primaryKey().notNull():oe&&h===`postgres`?e.primaryKey().defaultTo(t`pg_catalog.gen_random_uuid()`).notNull():e.primaryKey().notNull());for(let[n,i]of Object.entries(e.fields)){let a=ce(i,n,pe(e.table,n));if(r=r.addColumn(n,a,e=>(e=i.required===!1?e:e.notNull(),i.references&&(e=e.references(de(i)).onDelete(i.references.onDelete||`cascade`)),i.unique&&(e=e.unique()),i.type===`date`&&typeof i.defaultValue==`function`&&(h===`postgres`||h===`mysql`||h===`mssql`)&&(e=h===`mysql`?e.defaultTo(t`CURRENT_TIMESTAMP(3)`):e.defaultTo(t`CURRENT_TIMESTAMP`)),e)),i.index&&!i.unique){let t=m.schema.createIndex(y(e.table,n,!1)).on(e.table).columns([n]);fe.push(t)}}ae.push(r)}for(let{table:e,index:t,name:n}of w){let r=m.schema.createIndex(n).on(e).columns([...t.columns]);t.unique&&(r=r.unique()),fe.push(r)}for(let e of fe)ae.push(e);async function me(){try{for(let e of ae)await e.execute()}finally{ae.length&&e.database&&fee(e.database)}}async function ge(){return ae.map(e=>e.compile().sql).join(`;
506
+
507
+ `)+`;`}return{toBeCreated:te,toBeAdded:ne,toBeAddedIndexes:w,unsafeChanges:f,schemaProblems:C,runMigrations:me,compileMigrations:ge}}function Gpe(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function Kpe(e){return e?e.split(`,`).map(e=>{e=e.trim();let t=e.indexOf(`:`);if(t===-1)throw new D(`Invalid BETTER_AUTH_SECRETS entry: "${e}". Expected format: "<version>:<secret>"`);let n=parseInt(e.slice(0,t),10);if(!Number.isInteger(n)||n<0)throw new D(`Invalid version in BETTER_AUTH_SECRETS: "${e.slice(0,t)}". Version must be a non-negative integer.`);let r=e.slice(t+1).trim();if(!r)throw new D(`Empty secret value for version ${n} in BETTER_AUTH_SECRETS.`);return{version:n,value:r}}):null}function qpe(e,t){if(e.length===0)throw new D("`secrets` array must contain at least one entry.");let n=/* @__PURE__ */ new Set;for(let t of e){let e=parseInt(String(t.version),10);if(!Number.isInteger(e)||e<0||String(e)!==String(t.version).trim())throw new D(`Invalid version ${t.version} in \`secrets\`. Version must be a non-negative integer.`);if(!t.value)throw new D(`Empty secret value for version ${e} in \`secrets\`.`);if(n.has(e))throw new D(`Duplicate version ${e} in \`secrets\`. Each version must be unique.`);n.add(e)}let r=e[0];r.value.length<32&&t.warn(`[better-auth] Warning: the current secret (version ${r.version}) should be at least 32 characters long for adequate security.`),Gpe(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function Jpe(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(parseInt(String(t.version),10),t.value);return{keys:n,currentVersion:parseInt(String(e[0].version),10),legacySecret:t&&t!==`better-auth-secret-12345678901234567890`?t:void 0}}async function Ype(e,t){return{database:t?.database,adapter:t?.adapter,emailVerification:{sendVerificationEmail:!!e.emailVerification?.sendVerificationEmail,sendOnSignUp:!!e.emailVerification?.sendOnSignUp,sendOnSignIn:!!e.emailVerification?.sendOnSignIn,autoSignInAfterVerification:!!e.emailVerification?.autoSignInAfterVerification,expiresIn:e.emailVerification?.expiresIn,beforeEmailVerification:!!e.emailVerification?.beforeEmailVerification,afterEmailVerification:!!e.emailVerification?.afterEmailVerification},emailAndPassword:{enabled:!!e.emailAndPassword?.enabled,disableSignUp:!!e.emailAndPassword?.disableSignUp,requireEmailVerification:!!e.emailAndPassword?.requireEmailVerification,maxPasswordLength:e.emailAndPassword?.maxPasswordLength,minPasswordLength:e.emailAndPassword?.minPasswordLength,sendResetPassword:!!e.emailAndPassword?.sendResetPassword,resetPasswordTokenExpiresIn:e.emailAndPassword?.resetPasswordTokenExpiresIn,onPasswordReset:!!e.emailAndPassword?.onPasswordReset,password:{hash:!!e.emailAndPassword?.password?.hash,verify:!!e.emailAndPassword?.password?.verify},autoSignIn:!!e.emailAndPassword?.autoSignIn,revokeSessionsOnPasswordReset:!!e.emailAndPassword?.revokeSessionsOnPasswordReset},socialProviders:await Promise.all(Object.keys(e.socialProviders||{}).map(async t=>{let n=e.socialProviders?.[t];if(!n)return{};let r=typeof n==`function`?await n():n;return{id:t,mapProfileToUser:!!r.mapProfileToUser,disableDefaultScope:!!r.disableDefaultScope,disableIdTokenSignIn:!!r.disableIdTokenSignIn,disableImplicitSignUp:r.disableImplicitSignUp,disableSignUp:r.disableSignUp,getUserInfo:!!r.getUserInfo,overrideUserInfoOnSignIn:!!r.overrideUserInfoOnSignIn,prompt:r.prompt,verifyIdToken:!!r.verifyIdToken,scope:r.scope,refreshAccessToken:!!r.refreshAccessToken}})),plugins:e.plugins?.map(e=>e.id.toString()),user:{modelName:e.user?.modelName,fields:e.user?.fields,additionalFields:e.user?.additionalFields,changeEmail:{enabled:e.user?.changeEmail?.enabled,sendChangeEmailConfirmation:!!e.user?.changeEmail?.sendChangeEmailConfirmation}},verification:{modelName:e.verification?.modelName,disableCleanup:e.verification?.disableCleanup,fields:e.verification?.fields},session:{modelName:e.session?.modelName,additionalFields:e.session?.additionalFields,cookieCache:{enabled:e.session?.cookieCache?.enabled,maxAge:e.session?.cookieCache?.maxAge,strategy:e.session?.cookieCache?.strategy},disableSessionRefresh:e.session?.disableSessionRefresh,expiresIn:e.session?.expiresIn,fields:e.session?.fields,freshAge:e.session?.freshAge,preserveSessionInDatabase:e.session?.preserveSessionInDatabase,storeSessionInDatabase:e.session?.storeSessionInDatabase,updateAge:e.session?.updateAge},account:{modelName:e.account?.modelName,fields:e.account?.fields,encryptOAuthTokens:e.account?.encryptOAuthTokens,updateAccountOnSignIn:e.account?.updateAccountOnSignIn,accountLinking:{enabled:e.account?.accountLinking?.enabled,trustedProviders:e.account?.accountLinking?.trustedProviders,updateUserInfoOnLink:e.account?.accountLinking?.updateUserInfoOnLink,allowUnlinkingAll:e.account?.accountLinking?.allowUnlinkingAll}},hooks:{after:!!e.hooks?.after,before:!!e.hooks?.before},secondaryStorage:!!e.secondaryStorage,advanced:{cookiePrefix:!!e.advanced?.cookiePrefix,cookies:!!e.advanced?.cookies,crossSubDomainCookies:{domain:!!e.advanced?.crossSubDomainCookies?.domain,enabled:e.advanced?.crossSubDomainCookies?.enabled,additionalCookies:e.advanced?.crossSubDomainCookies?.additionalCookies},database:{generateId:e.advanced?.database?.generateId,defaultFindManyLimit:e.advanced?.database?.defaultFindManyLimit},useSecureCookies:e.advanced?.useSecureCookies,ipAddress:{disableIpTracking:e.advanced?.ipAddress?.disableIpTracking,ipAddressHeaders:e.advanced?.ipAddress?.ipAddressHeaders},disableCSRFCheck:e.advanced?.disableCSRFCheck,cookieAttributes:{expires:e.advanced?.defaultCookieAttributes?.expires,secure:e.advanced?.defaultCookieAttributes?.secure,sameSite:e.advanced?.defaultCookieAttributes?.sameSite,domain:!!e.advanced?.defaultCookieAttributes?.domain,path:e.advanced?.defaultCookieAttributes?.path,httpOnly:e.advanced?.defaultCookieAttributes?.httpOnly}},trustedOrigins:e.trustedOrigins?.length,rateLimit:{storage:e.rateLimit?.storage,modelName:e.rateLimit?.modelName,window:e.rateLimit?.window,customStorage:!!e.rateLimit?.customStorage,enabled:e.rateLimit?.enabled,max:e.rateLimit?.max},onAPIError:{errorURL:e.onAPIError?.errorURL,onError:!!e.onAPIError?.onError,throw:e.onAPIError?.throw},logger:{disabled:e.logger?.disabled,level:e.logger?.level,log:!!e.logger?.log},databaseHooks:{user:{create:{after:!!e.databaseHooks?.user?.create?.after,before:!!e.databaseHooks?.user?.create?.before},update:{after:!!e.databaseHooks?.user?.update?.after,before:!!e.databaseHooks?.user?.update?.before}},session:{create:{after:!!e.databaseHooks?.session?.create?.after,before:!!e.databaseHooks?.session?.create?.before},update:{after:!!e.databaseHooks?.session?.update?.after,before:!!e.databaseHooks?.session?.update?.before}},account:{create:{after:!!e.databaseHooks?.account?.create?.after,before:!!e.databaseHooks?.account?.create?.before},update:{after:!!e.databaseHooks?.account?.update?.after,before:!!e.databaseHooks?.account?.update?.before}},verification:{create:{after:!!e.databaseHooks?.verification?.create?.after,before:!!e.databaseHooks?.verification?.create?.before},update:{after:!!e.databaseHooks?.verification?.update?.after,before:!!e.databaseHooks?.verification?.update?.before}}}}}function Xpe(){let e=C.npm_config_user_agent;if(!e)return;let t=e.split(` `)[0],n=t.lastIndexOf(`/`),r=t.substring(0,n);return{name:r===`npminstall`?`cnpm`:r,version:t.substring(n+1)}}function Zpe(){return C.CI!==`false`&&(`BUILD_ID`in C||`BUILD_NUMBER`in C||`CI`in C||`CI_APP_ID`in C||`CI_BUILD_ID`in C||`CI_BUILD_NUMBER`in C||`CI_NAME`in C||`CONTINUOUS_INTEGRATION`in C||`RUN_ID`in C)}function Qpe(){return typeof Deno<`u`?{name:`deno`,version:Deno?.version?.deno??null}:typeof Bun<`u`?{name:`bun`,version:Bun?.version??null}:typeof process<`u`&&process?.versions?.node?{name:`node`,version:process.versions.node??null}:{name:`edge`,version:null}}function $pe(){return b(`NODE_ENV`)===`production`?`production`:Zpe()?`ci`:Te()?`test`:`development`}async function jQ(e){let t=await MU(`SHA-256`).digest(e);return ue.encode(t)}const eme=e=>h(`a-z`,`A-Z`,`0-9`)(e||32);let MQ;async function NQ(){if(MQ)return MQ;try{let e=process.cwd();if(!e)return;let t=await Dt.readFile(it.join(e,`package.json`),`utf-8`);return MQ=JSON.parse(t),MQ}catch{}}async function PQ(e){if(MQ)return MQ.dependencies?.[e]||MQ.devDependencies?.[e]||MQ.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error(`no-cwd`);let n=it.join(t,`node_modules`,e,`package.json`),r=await Dt.readFile(n,`utf-8`);return JSON.parse(r).version||await FQ(e)||void 0}catch{}return FQ(e)}async function FQ(e){let t=await NQ();if(t)return{...t.dependencies,...t.devDependencies,...t.peerDependencies}[e]}async function tme(){return(await NQ())?.name}async function nme(){try{let e=ut.cpus();return{deploymentVendor:rme(),systemPlatform:ut.platform(),systemRelease:ut.release(),systemArchitecture:ut.arch(),cpuCount:e.length,cpuModel:e.length?e[0].model:null,cpuSpeed:e.length?e[0].speed:null,memory:ut.totalmem(),isWSL:await cme(),isDocker:await LQ(),isTTY:process.stdout?process.stdout.isTTY:null}}catch{return{systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}function rme(){let e=process.env,t=(...t)=>t.some(t=>!!e[t]);return t(`CF_PAGES`,`CF_PAGES_URL`,`CF_ACCOUNT_ID`)||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`?`cloudflare`:t(`VERCEL`,`VERCEL_URL`,`VERCEL_ENV`)?`vercel`:t(`NETLIFY`,`NETLIFY_URL`)?`netlify`:t(`RENDER`,`RENDER_URL`,`RENDER_INTERNAL_HOSTNAME`,`RENDER_SERVICE_ID`)?`render`:t(`AWS_LAMBDA_FUNCTION_NAME`,`AWS_EXECUTION_ENV`,`LAMBDA_TASK_ROOT`)?`aws`:t(`GOOGLE_CLOUD_FUNCTION_NAME`,`GOOGLE_CLOUD_PROJECT`,`GCP_PROJECT`,`K_SERVICE`)?`gcp`:t(`AZURE_FUNCTION_NAME`,`FUNCTIONS_WORKER_RUNTIME`,`WEBSITE_INSTANCE_ID`,`WEBSITE_SITE_NAME`)?`azure`:t(`DENO_DEPLOYMENT_ID`,`DENO_REGION`)?`deno-deploy`:t(`FLY_APP_NAME`,`FLY_REGION`,`FLY_ALLOC_ID`)?`fly-io`:t(`RAILWAY_STATIC_URL`,`RAILWAY_ENVIRONMENT_NAME`)?`railway`:t(`DYNO`,`HEROKU_APP_NAME`)?`heroku`:t(`DO_DEPLOYMENT_ID`,`DO_APP_NAME`,`DIGITALOCEAN`)?`digitalocean`:t(`KOYEB`,`KOYEB_DEPLOYMENT_ID`,`KOYEB_APP_NAME`)?`koyeb`:null}let IQ;async function ime(){try{return yt.statSync(`/.dockerenv`),!0}catch{return!1}}async function ame(){try{return yt.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}async function LQ(){return IQ===void 0&&(IQ=await ime()||await ame()),IQ}let RQ;const ome=async()=>{try{return yt.statSync(`/run/.containerenv`),!0}catch{return!1}};async function sme(){return RQ===void 0&&(RQ=await ome()||await LQ()),RQ}async function cme(){try{return process.platform===`linux`&&(ut.release().toLowerCase().includes(`microsoft`)||yt.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`))?!await sme():!1}catch{return!1}}let zQ=null;async function BQ(e){if(zQ)return zQ;let t=await tme();return t?(zQ=await jQ(e?e+t:t),zQ):e?(zQ=await jQ(e),zQ):(zQ=eme(32),zQ)}async function lme(){for(let[e,t]of Object.entries({pg:`postgresql`,mysql:`mysql`,mariadb:`mariadb`,sqlite3:`sqlite`,"better-sqlite3":`sqlite`,"@prisma/client":`prisma`,mongoose:`mongodb`,mongodb:`mongodb`,"drizzle-orm":`drizzle`})){let n=await PQ(e);if(n)return{name:t,version:n}}}async function ume(){for(let[e,t]of Object.entries({next:`next`,nuxt:`nuxt`,"react-router":`react-router`,astro:`astro`,"@sveltejs/kit":`sveltekit`,"solid-start":`solid-start`,"tanstack-start":`tanstack-start`,hono:`hono`,express:`express`,elysia:`elysia`,expo:`expo`})){let n=await PQ(e);if(n)return{name:t,version:n}}}const dme=async function(){};async function fme(e,t){let n=e.telemetry?.debug||_(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=ee.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:dme};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(f.error):r&&(n?f.info(`telemetry event`,JSON.stringify(e,null,2)):await BX(r,{method:`POST`,body:e}).catch(f.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(_(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!Te())})(),o;return a&&(o=await BQ(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await Ype(e,t),runtime:Qpe(),database:await lme(),framework:await ume(),environment:$pe(),systemInfo:await nme(),packageManager:Xpe()},anonymousId:o})),{publish:async t=>{a&&(o||=await BQ(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function pme(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function mme(e,t){let n=e===`better-auth-secret-12345678901234567890`;if(!Te()){if(n&&te)throw new D("You are using the default secret. Please set `BETTER_AUTH_SECRET` in your environment variables or pass `secret` in your auth config.");if(!e)throw new D("BETTER_AUTH_SECRET is missing. Set it in your environment or pass `secret` to betterAuth({ secret }).");e.length<32&&t.warn("[better-auth] Warning: your BETTER_AUTH_SECRET should be at least 32 characters long for adequate security. Generate one with `npx auth secret` or `openssl rand -base64 32`."),pme(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function hme(e,t,n){let r=HW(t);r||(t=cY(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=cY(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=TY(t),o=he(t.logger),s=VH(t.baseURL);if(VH(t.baseURL)){let{allowedHosts:e}=t.baseURL;if(!e||e.length===0)throw new D(`baseURL.allowedHosts cannot be empty. Provide at least one allowed host pattern (e.g., ["myapp.com", "*.vercel.app"]).`)}let c=s?void 0:LH(typeof t.baseURL==`string`?t.baseURL:void 0,t.basePath);!c&&!s&&o.warn(`[better-auth] Base URL is not set. Set the baseURL option or BETTER_AUTH_URL env, or use a dynamic baseURL with allowedHosts for multi-host setups. Without it the origin is derived from the incoming request, and callbacks and redirects may not work correctly.`),e.id===`memory`&&t.advanced?.database?.generateId===!1&&o.error(`[better-auth] Misconfiguration detected.
508
+ You are using the memory DB with generateId: false.
509
+ This will cause no id to be generated for any model.
510
+ Most of the features of Better Auth will not work correctly.`);let l=t.secrets??Kpe(C.BETTER_AUTH_SECRETS),u=t.secret||C.BETTER_AUTH_SECRET||C.AUTH_SECRET||``,d,f;l?(qpe(l,o),d=l[0].value,f=Jpe(l,u)):(d=u||`better-auth-secret-12345678901234567890`,mme(d,o),f=d),t={...t,secret:d,baseURL:s?t.baseURL:c?new URL(c).origin:``,basePath:t.basePath||`/api/auth`,plugins:i.concat(a)},jpe(t,o);let m=t.advanced?.ipAddress?.trustedProxies;if(m&&m.length>0){let e=vJ(m);e.length>0&&o.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(`, `)}. Each entry must be an IP address or CIDR range.`)}let h=nq(t),g=p(t),_=(await Promise.all(Object.entries(t.socialProviders||{}).map(async([e,t])=>{let n=typeof t==`function`?await t():t;if(n==null||n.enabled===!1)return null;n.clientId||o.warn(`Social provider ${e} is missing clientId or clientSecret`);let r=nQ[e](n);return r.disableImplicitSignUp=n.disableImplicitSignUp,r}))).filter(e=>e!==null),v=({model:e,size:n})=>{if(typeof t.advanced?.generateId==`function`)return t.advanced.generateId({model:e,size:n});let r=t?.advanced?.database?.generateId;return typeof r==`function`?r({model:e,size:n}):r===`uuid`?crypto.randomUUID():r===`serial`||r===!1?!1:pe(n)},{publish:y}=await fme(t,{adapter:e.id,database:typeof t.database==`function`?`adapter`:n(t.database)}),b=new Set(t.plugins.map(e=>e.id)),x=e=>t.plugins.find(t=>t.id===e)??null,S=e=>b.has(e),ee=await EY(t),ne=await jY(t),w={appName:t.appName||`Better Auth`,baseURL:c||``,version:be(),socialProviders:_,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:g,trustedOrigins:ee,trustedProviders:ne,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>Yq(e,n,t))},sessionConfig:{updateAge:t.session?.updateAge===void 0?86400:t.session.updateAge,expiresIn:t.session?.expiresIn||604800,freshAge:t.session?.freshAge===void 0?86400:t.session.freshAge,cookieRefreshCache:(()=>{let e=t.session?.cookieCache?.refreshCache,n=t.session?.cookieCache?.maxAge||300;return r&&e?(o.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):e===!1||e===void 0?!1:e===!0?{enabled:!0,updateAge:Math.floor(n*.2)}:{enabled:!0,updateAge:e.updateAge===void 0?Math.floor(n*.2):e.updateAge}})()},secret:d,secretConfig:f,rateLimit:{...t.rateLimit,enabled:t.rateLimit?.enabled??te,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?`secondary-storage`:`memory`)},authCookies:h,logger:o,generateId:v,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||kU,verify:t.emailAndPassword?.password?.verify||AU,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:ope},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:iY(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:v}),createAuthCookie:tq(t),async runMigrations(){throw new D(`runMigrations will be set by the specific init implementation`)},publishTelemetry:y,skipCSRFCheck:!!t.advanced?.disableCSRFCheck,skipOriginCheck:t.advanced?.disableOriginCheck===void 0?!!Te():t.advanced.disableOriginCheck,runInBackground:t.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{t.advanced?.backgroundTasks?.handler?e instanceof Promise&&t.advanced.backgroundTasks.handler(e.catch(e=>{o.error(`Failed to run background task:`,e)})):await e}catch(e){o.error(`Failed to run background task:`,e)}},getPlugin:x,hasPlugin:S},T=wY(w);return dG(T)&&await T,w.checkSchema=Ze(w.adapter),w.explicitSchemaCheck=dee(w.adapter),w}const gme=async e=>{let t=await hme(await Ppe(e),e,e=>o(e)||`unknown`);return t.runMigrations=async function(){if(!e.database||`updateMany`in e.database)throw new D(`Database is not provided or it's an adapter. Migrations are only supported with a database instance.`);let{runMigrations:t}=await AQ(e);await t()},t},_me=(e,t)=>{let n=t(e).then(e=>{let t=e.options.advanced?.database?.validateSchema;if(!e.checkSchema&&t!==!1){let n=t===!0?`warn`:`debug`;e.logger[n](`Schema validation is not available for adapter "${e.adapter.id}". Skipping schema validation. Database operations will proceed normally.`)}let n=e.checkSchema?.();return n&&n.catch(t=>{e.logger.error(t instanceof pee?t.message:`Could not validate the database schema. Check your database connection.`)}),e}),{api:r}=wQ(n,e),i=e.plugins?.reduce((e,t)=>t.$ERROR_CODES?{...e,...t.$ERROR_CODES}:e,{}),a=async t=>{let r=await n,i=r.options.basePath||`/api/auth`,a;if(VH(e.baseURL))a=await kY(r,t,OY(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=LH(void 0,i,t,void 0,r.options.advanced?.trustedProxyHeaders);if(!n)throw new D(`Could not get base URL from request. Please provide a valid base URL.`);a.baseURL=n,a.options={...r.options,baseURL:RH(n)||void 0},e=a.options}a.trustedOrigins=await EY(e,t),a.trustedProviders=await jY(e,t)}let{handler:o}=Mpe(a,e);return CH(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...Y}}},vme=e=>_me(e,gme),VQ=bH({INVALID_METADATA_TYPE:`metadata must be an object or undefined`,REFILL_AMOUNT_AND_INTERVAL_REQUIRED:`refillAmount is required when refillInterval is provided`,REFILL_INTERVAL_AND_AMOUNT_REQUIRED:`refillInterval is required when refillAmount is provided`,USER_BANNED:`User is banned`,UNAUTHORIZED_SESSION:`Unauthorized or invalid session`,KEY_NOT_FOUND:`API Key not found`,KEY_DISABLED:`API Key is disabled`,KEY_EXPIRED:`API Key has expired`,USAGE_EXCEEDED:`API Key has reached its usage limit`,KEY_NOT_RECOVERABLE:`API Key is not recoverable`,EXPIRES_IN_IS_TOO_SMALL:`The expiresIn is smaller than the predefined minimum value.`,EXPIRES_IN_IS_TOO_LARGE:`The expiresIn is larger than the predefined maximum value.`,INVALID_REMAINING:`The remaining count is either too large or too small.`,INVALID_PREFIX_LENGTH:`The prefix length is either too large or too small.`,INVALID_NAME_LENGTH:`The name length is either too large or too small.`,METADATA_DISABLED:`Metadata is disabled.`,RATE_LIMIT_EXCEEDED:`Rate limit exceeded.`,NO_VALUES_TO_UPDATE:`No values to update.`,KEY_DISABLED_EXPIRATION:`Custom key expiration values are disabled.`,INVALID_API_KEY:`Invalid API key.`,INVALID_USER_ID_FROM_API_KEY:`The user id from the API key is invalid.`,INVALID_REFERENCE_ID_FROM_API_KEY:`The reference id from the API key is invalid.`,INVALID_API_KEY_GETTER_RETURN_TYPE:`API Key getter returned an invalid key type. Expected string.`,SERVER_ONLY_PROPERTY:`The property you're trying to set can only be set from the server auth instance only.`,FAILED_TO_UPDATE_API_KEY:`Failed to update API key`,NAME_REQUIRED:`API Key name is required.`,ORGANIZATION_ID_REQUIRED:`Organization ID is required for organization-owned API keys.`,USER_NOT_MEMBER_OF_ORGANIZATION:`You are not a member of the organization that owns this API key.`,INSUFFICIENT_API_KEY_PERMISSIONS:`You do not have permission to perform this action on organization API keys.`,NO_DEFAULT_API_KEY_CONFIGURATION_FOUND:`No default api-key configuration found.`,ORGANIZATION_PLUGIN_REQUIRED:`Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin.`});async function HQ(e,t,n){let r=e.length;if(r===0)return[];let{signal:i}=n;if(i?.aborted)throw i.reason;let a=Math.floor(n.concurrency),o=Math.min(r,a>=1?a:1),s=Array(r),c=0,l=!1;return await Promise.all(Array.from({length:o},async()=>{for(;!l&&c<r;){if(i?.aborted)throw i.reason;let n=c++;try{s[n]=await t(e[n],n)}catch(e){throw l=!0,e}}})),s}const yme={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},bme=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,UQ={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},xme=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Sme(e){return e instanceof Date&&!isNaN(e.getTime())}function Cme(e){let t=xme.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return Sme(f)?f:null}function wme(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in UQ)return UQ[s];if(!bme.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(yme).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t)r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);else{if(a&&typeof t==`string`){let e=Cme(t);if(e)return e}return i?i(e,t):t}})}catch(t){if(n)throw t;return e}}function Tme(e,t={strict:!0}){return wme(e,t)}function WQ(e){return e==null?null:typeof e==`object`?e:le(e)}function GQ(e){return e!=null&&typeof e==`string`}async function Eme(e,t,n){if(n.storage!==`database`&&!n.fallbackToDatabase)return;let r=t.filter(e=>GQ(e.metadata));if(r.length===0)return;let i=r.map(async t=>{let n=WQ(t.metadata);try{await e.context.adapter.update({model:`apikey`,where:[{field:`id`,value:t.id}],update:{metadata:n}})}catch(n){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,n)}});await Promise.all(i)}async function KQ(e,t,n){let r=WQ(t.metadata);if(GQ(t.metadata)&&(n.storage===`database`||n.fallbackToDatabase))try{await e.context.adapter.update({model:`apikey`,where:[{field:`id`,value:t.id}],update:{metadata:r}})}catch(n){e.context.logger.warn(`Failed to migrate double-stringified metadata for API key ${t.id}:`,n)}return r}function qQ(e){return`api-key:${e}`}function JQ(e){return`api-key:by-id:${e}`}function YQ(e){return`api-key:by-ref:${e}`}function Dme(e){return JSON.stringify({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),expiresAt:e.expiresAt?.toISOString()??null,lastRefillAt:e.lastRefillAt?.toISOString()??null,lastRequest:e.lastRequest?.toISOString()??null})}function XQ(e){if(!e||typeof e!=`string`)return null;try{let t=JSON.parse(e);return{...t,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),expiresAt:t.expiresAt?new Date(t.expiresAt):null,lastRefillAt:t.lastRefillAt?new Date(t.lastRefillAt):null,lastRequest:t.lastRequest?new Date(t.lastRequest):null}}catch{return null}}function ZQ(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function QQ(e){if(e.expiresAt){let t=Date.now(),n=new Date(e.expiresAt).getTime(),r=Math.floor((n-t)/1e3);if(r>0)return r}}async function $Q(e,t,n){let r=qQ(t);return XQ(await n.get(r))}async function e$(e,t,n){let r=JQ(t);return XQ(await n.get(r))}const t$=/* @__PURE__ */ new Map;function Ome(e,t){let n=(t$.get(e)??Promise.resolve()).then(t,t).finally(()=>{t$.get(e)===n&&t$.delete(e)});return t$.set(e,n),n}async function n$(e,t,n){await Ome(t,async()=>{let r=await e.get(t),i=[];if(r&&typeof r==`string`)try{i=JSON.parse(r)}catch{i=[]}else Array.isArray(r)&&(i=r);let a=n(i);a.length===0?await e.delete(t):await e.set(t,JSON.stringify(a))})}async function r$(e,t,n,r,i){let a=Dme(t),o=YQ(t.referenceId);i.fallbackToDatabase?await Promise.all([n.set(qQ(t.key),a,r),n.set(JQ(t.id),a,r),n.delete(o)]):(await Promise.all([n.set(qQ(t.key),a,r),n.set(JQ(t.id),a,r)]),await n$(n,o,e=>e.includes(t.id)?e:[...e,t.id]))}async function kme(e,t,n,r){let i=YQ(t.referenceId);r.fallbackToDatabase?await Promise.all([n.delete(qQ(t.key)),n.delete(JQ(t.id)),n.delete(i)]):await Promise.all([n.delete(qQ(t.key)),n.delete(JQ(t.id)),n$(n,i,e=>e.filter(e=>e!==t.id))])}async function i$(e,t,n){let r=ZQ(e,n);if(n.storage===`database`)return await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]});if(n.storage===`secondary-storage`&&n.fallbackToDatabase){if(r){let n=await $Q(e,t,r);if(n)return n}let i=await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]});return i&&r&&await r$(e,i,r,QQ(i),n),i}return n.storage===`secondary-storage`?r?await $Q(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]})}async function a$(e,t,n){let r=ZQ(e,n);if(n.storage===`database`)return await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]});if(n.storage===`secondary-storage`&&n.fallbackToDatabase){if(r){let n=await e$(e,t,r);if(n)return n}let i=await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]});return i&&r&&await r$(e,i,r,QQ(i),n),i}return n.storage===`secondary-storage`?r?await e$(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]})}async function o$(e,t,n){let r=ZQ(e,n),i=QQ(t);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await r$(e,t,r,i,n)}}async function s$(e,t,n){let r=ZQ(e,n);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await kme(e,t,r,n)}}function c$(e,t,n,r,i){let a=[...e];if(t){let e=n||`asc`;a.sort((n,r)=>{let i=n[t],a=r[t];return i==null&&a==null?0:i==null?e===`asc`?-1:1:a==null?e===`asc`?1:-1:i<a?e===`asc`?-1:1:i>a?e===`asc`?1:-1:0})}return i!==void 0&&(a=a.slice(i)),r!==void 0&&(a=a.slice(0,r)),a}async function l$(e,t,n,r){let i=ZQ(e,n),{limit:a,offset:o,sortBy:s,sortDirection:c}=r||{};if(n.storage===`database`){let[n,r]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);return{apiKeys:n,total:r}}if(n.storage===`secondary-storage`&&n.fallbackToDatabase){let r=YQ(t);if(i){let t=await i.get(r),n=[];if(t&&typeof t==`string`)try{n=JSON.parse(t)}catch{n=[]}else Array.isArray(t)&&(n=t);if(n.length>0){let t=(await HQ(n,t=>e$(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:c$(t,s,c,a,o),total:t.length}}}let[l,u]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);if(i&&l.length>0){await HQ(l,t=>r$(e,t,i,QQ(t),n),{concurrency:10});let t=l.map(e=>e.id);await i.set(r,JSON.stringify(t))}return{apiKeys:l,total:u}}if(n.storage===`secondary-storage`){if(!i)return{apiKeys:[],total:0};let n=YQ(t),r=await i.get(n),l=[];if(r&&typeof r==`string`)try{l=JSON.parse(r)}catch{return{apiKeys:[],total:0}}else if(Array.isArray(r))l=r;else return{apiKeys:[],total:0};let u=(await HQ(l,t=>e$(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:c$(u,s,c,a,o),total:u.length}}let[l,u]=await Promise.all([e.context.adapter.findMany({model:`apikey`,where:[{field:`referenceId`,value:t}],limit:a,offset:o,sortBy:s?{field:s,direction:c||`asc`}:void 0}),e.context.adapter.count({model:`apikey`,where:[{field:`referenceId`,value:t}]})]);return{apiKeys:l,total:u}}function Ame(e){let t=e.context;if(`orgOptions`in t&&t.orgOptions)return t.orgOptions;let n=t.getPlugin?.(`organization`);return n&&`options`in n?n.options:null}async function u$(e,t,n,r){let i=Ame(e);if(!i){let e=VQ.ORGANIZATION_PLUGIN_REQUIRED;throw E.from(`INTERNAL_SERVER_ERROR`,e)}let a=await e.context.adapter.findOne({model:`member`,where:[{field:`userId`,value:t},{field:`organizationId`,value:n}]});if(!a){let e=VQ.USER_NOT_MEMBER_OF_ORGANIZATION;throw E.from(`FORBIDDEN`,e)}if(!await jme(e,a.role,n,r,i)){let e=VQ.INSUFFICIENT_API_KEY_PERMISSIONS;throw E.from(`FORBIDDEN`,e)}return a}async function jme(e,t,n,r,i){let{hasPermission:a}=await import(`./organization-FxrB4RLj.mjs`);try{return await a({role:t,options:i,permissions:{apiKey:[r]},organizationId:n,allowCreatorAllPermissions:!0},e)}catch{return!1}}const d$=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Mme(e){return e instanceof E||e instanceof E||e?.name===`APIError`}const Nme=A({configId:k().meta({description:`The configuration ID to use for the API key. If not provided, the default configuration will be used.`}).optional(),name:k().meta({description:`Name of the Api Key`}).optional(),expiresIn:Me().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable().default(null),prefix:k().meta({description:`Prefix of the Api Key`}).regex(/^[a-zA-Z0-9_-]+$/,{message:`Invalid prefix format, must be alphanumeric and contain only underscores and hyphens.`}).optional(),remaining:Me().meta({description:`Remaining number of requests. Server side only`}).min(0).optional().nullable().default(null),metadata:Ke().optional(),refillAmount:Me().meta({description:`Amount to refill the remaining count of the Api Key. server-only. Eg: 100`}).min(1).optional(),refillInterval:Me().meta({description:`Interval to refill the Api Key in milliseconds. server-only. Eg: 1000`}).optional(),rateLimitTimeWindow:Me().meta({description:"The duration in milliseconds where each request is counted. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 1000"}).optional(),rateLimitMax:Me().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),rateLimitEnabled:He().meta({description:`Whether the key has rate limiting enabled. server-only. Eg: true`}).optional(),permissions:Ne(k(),Pe(k())).meta({description:`Permissions of the Api Key.`}).optional(),userId:GW().meta({description:`User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"`}).optional(),organizationId:GW().meta({description:`Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'`}).optional()});function Pme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:r}){return X(`/api-key/create`,{method:`POST`,body:Nme,metadata:{openapi:{description:`Create a new API key for a user`,responses:{200:{description:`API key created successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`Unique identifier of the API key`},createdAt:{type:`string`,format:`date-time`,description:`Creation timestamp`},updatedAt:{type:`string`,format:`date-time`,description:`Last update timestamp`},name:{type:`string`,nullable:!0,description:`Name of the API key`},prefix:{type:`string`,nullable:!0,description:`Prefix of the API key`},start:{type:`string`,nullable:!0,description:`Starting characters of the key (if configured)`},key:{type:`string`,description:`The full API key (only returned on creation)`},enabled:{type:`boolean`,description:`Whether the key is enabled`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiration timestamp`},referenceId:{type:`string`,description:`ID of the reference owning the key`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`Last refill timestamp`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`Last request timestamp`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Metadata associated with the key`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum requests in time window`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`Rate limit time window in milliseconds`},remaining:{type:`number`,nullable:!0,description:`Remaining requests`},refillAmount:{type:`number`,nullable:!0,description:`Amount to refill`},refillInterval:{type:`number`,nullable:!0,description:`Refill interval in milliseconds`},rateLimitEnabled:{type:`boolean`,description:`Whether rate limiting is enabled`},requestCount:{type:`number`,description:`Current request count in window`},permissions:{type:`object`,nullable:!0,additionalProperties:{type:`array`,items:{type:`string`}},description:`Permissions associated with the key`}},required:[`id`,`createdAt`,`updatedAt`,`key`,`enabled`,`referenceId`,`rateLimitEnabled`,`requestCount`]}}}}}}}},async n=>{let{configId:i,name:a,expiresIn:o,prefix:s,remaining:c,metadata:l,refillAmount:u,refillInterval:d,permissions:f,rateLimitMax:p,rateLimitTimeWindow:m,rateLimitEnabled:h}=n.body,g=h$(n.context,t,i),_=g.customKeyGenerator||e,v=await zJ(n,{disableCookieCache:!0}),y=n.request||n.headers;if(y&&(u!==void 0||d!==void 0||p!==void 0||m!==void 0||h!==void 0||f!==void 0||c!==null))throw E.from(`BAD_REQUEST`,VQ.SERVER_ONLY_PROPERTY);if(n.request&&n.body.userId!==void 0)throw E.from(`UNAUTHORIZED`,VQ.UNAUTHORIZED_SESSION);let b=g.references??`user`,x;if(b===`organization`){let e=n.body.organizationId;if(!e){let e=VQ.ORGANIZATION_ID_REQUIRED;throw E.from(`BAD_REQUEST`,e)}let t=v?.user.id||n.body.userId;if(!t)throw E.from(`UNAUTHORIZED`,VQ.UNAUTHORIZED_SESSION);await u$(n,t,e,`create`),x=e}else if(y){if(!v?.user.id){let e=VQ.UNAUTHORIZED_SESSION;throw E.from(`UNAUTHORIZED`,e)}x=v.user.id}else{let e=n.body.userId,t=v?.user.id;if(!t&&!e||v&&e&&t!==e){let e=VQ.UNAUTHORIZED_SESSION;throw E.from(`UNAUTHORIZED`,e)}x=t||e}if(l){if(g.enableMetadata===!1)throw E.from(`BAD_REQUEST`,VQ.METADATA_DISABLED);if(typeof l!=`object`)throw E.from(`BAD_REQUEST`,VQ.INVALID_METADATA_TYPE)}if(u&&!d){let e=VQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(d&&!u){let e=VQ.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(o){if(g.keyExpiration.disableCustomExpiresTime===!0){let e=VQ.KEY_DISABLED_EXPIRATION;throw E.from(`BAD_REQUEST`,e)}let e=o/86400;if(g.keyExpiration.minExpiresIn>e){let e=VQ.EXPIRES_IN_IS_TOO_SMALL;throw E.from(`BAD_REQUEST`,e)}if(g.keyExpiration.maxExpiresIn<e){let e=VQ.EXPIRES_IN_IS_TOO_LARGE;throw E.from(`BAD_REQUEST`,e)}}if(s&&(s.length<g.minimumPrefixLength||s.length>g.maximumPrefixLength))throw E.from(`BAD_REQUEST`,VQ.INVALID_PREFIX_LENGTH);if(a){if(a.length<g.minimumNameLength||a.length>g.maximumNameLength)throw E.from(`BAD_REQUEST`,VQ.INVALID_NAME_LENGTH)}else if(g.requireName)throw E.from(`BAD_REQUEST`,VQ.NAME_REQUIRED);r(n.context);let S=await _({length:g.defaultKeyLength,prefix:s||g.defaultPrefix}),ee=g.disableKeyHashing?S:await b$(S),C=null;g.startingCharactersConfig.shouldStore&&(C=S.substring(0,g.startingCharactersConfig.charactersLength));let te=g.permissions?.defaultPermissions?typeof g.permissions.defaultPermissions==`function`?await g.permissions.defaultPermissions(x,n):g.permissions.defaultPermissions:void 0,ne=f?JSON.stringify(f):te?JSON.stringify(te):void 0,w={configId:g.configId??`default`,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,name:a??null,prefix:s??g.defaultPrefix??null,start:C,key:ee,enabled:!0,expiresAt:o?d$(o,`sec`):g.keyExpiration.defaultExpiresIn?d$(g.keyExpiration.defaultExpiresIn,`sec`):null,referenceId:x,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:p??g.rateLimit.maxRequests??null,rateLimitTimeWindow:m??g.rateLimit.timeWindow??null,remaining:c===null?c:c??u??null,refillAmount:u??null,refillInterval:d??null,rateLimitEnabled:h===void 0?g.rateLimit.enabled??!0:h,requestCount:0,permissions:ne};l&&(w.metadata=l);let T;if(g.storage===`secondary-storage`&&g.fallbackToDatabase)T=await n.context.adapter.create({model:x$,data:w}),await o$(n,T,g);else if(g.storage===`secondary-storage`){let e=n.context.generateId({model:`apikey`})||pe();T={...w,id:e},await o$(n,T,g)}else T=await n.context.adapter.create({model:x$,data:w});return n.json({...T,key:S,metadata:l??null,permissions:T.permissions?le(T.permissions):null})})}function Fme({deleteAllExpiredApiKeys:e}){return X.serverOnly({method:`POST`},async t=>{try{await e(t.context,!0)}catch(e){return t.context.logger.error(`[API KEY PLUGIN] Failed to delete expired API keys:`,e),t.json({success:!1,error:e})}return t.json({success:!0,error:null})})}const Ime=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:k().meta({description:`The id of the Api Key`})});function Lme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/delete`,{method:`POST`,body:Ime,use:[VJ],metadata:{openapi:{description:`Delete an existing API key`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{keyId:{type:`string`,description:`The id of the API key to delete`}},required:[`keyId`]}}}},responses:{200:{description:`API key deleted successfully`,content:{"application/json":{schema:{type:`object`,properties:{success:{type:`boolean`,description:`Indicates if the API key was successfully deleted`}},required:[`success`]}}}}}}}},async t=>{let{configId:r,keyId:i}=t.body,a=t.context.session;if(a.user.banned===!0)throw E.from(`UNAUTHORIZED`,VQ.USER_BANNED);let o=h$(t.context,e,r),s=null;if(s=await a$(t,i,o),!s||!_$(s.configId,o.configId))throw E.from(`NOT_FOUND`,VQ.KEY_NOT_FOUND);let c=h$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await u$(t,a.user.id,s.referenceId,`delete`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,VQ.KEY_NOT_FOUND);try{c.storage===`secondary-storage`&&c.fallbackToDatabase?(await s$(t,s,c),await t.context.adapter.delete({model:x$,where:[{field:`id`,value:s.id}]})):c.storage===`database`?await t.context.adapter.delete({model:x$,where:[{field:`id`,value:s.id}]}):await s$(t,s,c)}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}return n(t.context),t.json({success:!0})})}const Rme=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),id:k().meta({description:`The id of the Api Key`})});function zme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/get`,{method:`GET`,query:Rme,use:[VJ],metadata:{openapi:{description:`Retrieve an existing API key by ID`,responses:{200:{description:`API key retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}}}}}}}},async t=>{let{configId:r,id:i}=t.query,a=t.context.session,o=h$(t.context,e,r),s=null;if(s=await a$(t,i,o),!s||!_$(s.configId,o.configId))throw E.from(`NOT_FOUND`,VQ.KEY_NOT_FOUND);let c=h$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await u$(t,a.user.id,s.referenceId,`read`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,VQ.KEY_NOT_FOUND);n(t.context);let l=await KQ(t,s,c),{key:u,...d}=s;return t.json({...d,metadata:l,permissions:d.permissions?le(d.permissions):null})})}function Bme(e){return e.storage===`database`?`database`:e.customStorage?`custom:${e.configId??`default`}`:e.fallbackToDatabase?`secondary-storage-with-fallback`:`secondary-storage`}const Vme=A({configId:k().meta({description:`Filter by configuration ID. If not provided, returns keys from all configurations.`}).optional(),organizationId:k().meta({description:`Organization ID to list keys for. If provided, returns organization-owned keys. If not provided, returns user-owned keys.`}).optional(),limit:KW().int().nonnegative().meta({description:`The number of API keys to return`}).optional(),offset:KW().int().nonnegative().meta({description:`The offset to start from`}).optional(),sortBy:k().meta({description:`The field to sort by (e.g., createdAt, name, expiresAt)`}).optional(),sortDirection:We([`asc`,`desc`]).meta({description:`The direction to sort by`}).optional()}).optional();function Hme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/list`,{method:`GET`,use:[VJ],query:Vme,metadata:{openapi:{description:`List all API keys for the authenticated user or for a specific organization`,responses:{200:{description:`API keys retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{apiKeys:{type:`array`,items:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}},total:{type:`number`,description:`Total number of API keys`},limit:{type:`number`,nullable:!0,description:`The limit used for pagination`},offset:{type:`number`,nullable:!0,description:`The offset used for pagination`}},required:[`apiKeys`,`total`]}}}}}}}},async t=>{let r=t.context.session,i=t.query?.configId,a=t.query?.organizationId,o=t.query?.limit==null?void 0:Number(t.query.limit),s=t.query?.offset==null?void 0:Number(t.query.offset);a&&await u$(t,r.user.id,a,`read`);let c=a??r.user.id,l=a?`organization`:`user`,u=[];if(i){let{apiKeys:n}=await l$(t,c,h$(t.context,e,i),{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection});u=n}else{let n=/* @__PURE__ */ new Map;for(let t of e){let e=Bme(t);n.has(e)||n.set(e,t)}let r=await Promise.all([...n.values()].map(e=>l$(t,c,e,{limit:void 0,offset:void 0,sortBy:t.query?.sortBy,sortDirection:t.query?.sortDirection}))),i=/* @__PURE__ */ new Set;for(let{apiKeys:e}of r)for(let t of e)i.has(t.id)||(i.add(t.id),u.push(t))}let d=u.filter(t=>(e.find(e=>g$(t.configId)?g$(e.configId):e.configId===t.configId)?.references??`user`)===l&&t.referenceId===c);i&&(d=d.filter(e=>_$(e.configId,i)));let f=d.length,p=d;s!==void 0&&(p=p.slice(s)),o!==void 0&&(p=p.slice(0,o)),n(t.context);let m=p.map(e=>{let{key:t,...n}=e;return{...n,metadata:WQ(e.metadata),permissions:n.permissions?le(n.permissions):null}}),h=e.find(e=>e.storage===`database`||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(Eme(t,p,h)),t.json({apiKeys:m,total:f,limit:o,offset:s})})}const Ume=A({configId:k().meta({description:`The configuration ID to use for the API key lookup. If not provided, the default configuration will be used.`}).optional(),keyId:k().meta({description:`The id of the Api Key`}),userId:GW().meta({description:`The id of the user which the api key belongs to. server-only. Eg: "some-user-id"`}).optional(),name:k().meta({description:`The name of the key`}).optional(),enabled:He().meta({description:`Whether the Api Key is enabled or not`}).optional(),remaining:Me().meta({description:`The number of remaining requests`}).min(1).optional(),refillAmount:Me().meta({description:`The refill amount`}).optional(),refillInterval:Me().meta({description:`The refill interval`}).optional(),metadata:Ke().optional(),expiresIn:Me().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable(),rateLimitEnabled:He().meta({description:`Whether the key has rate limiting enabled.`}).optional(),rateLimitTimeWindow:Me().meta({description:`The duration in milliseconds where each request is counted. server-only. Eg: 1000`}).optional(),rateLimitMax:Me().meta({description:"Maximum amount of requests allowed within a window. Once the `maxRequests` is reached, the request will be rejected until the `timeWindow` has passed, at which point the `timeWindow` will be reset. server-only. Eg: 100"}).optional(),permissions:Ne(k(),Pe(k())).meta({description:`Update the permissions on the API Key. server-only.`}).optional().nullable()});function Wme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/update`,{method:`POST`,body:Ume,metadata:{openapi:{description:`Update an existing API key by ID`,responses:{200:{description:`API key updated successfully`,content:{"application/json":{schema:{type:`object`,properties:{id:{type:`string`,description:`ID`},name:{type:`string`,nullable:!0,description:`The name of the key`},start:{type:`string`,nullable:!0,description:`Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key.`},prefix:{type:`string`,nullable:!0,description:`The API Key prefix. Stored as plain text.`},userId:{type:`string`,description:`The owner of the user id`},refillInterval:{type:`number`,nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:`number`,nullable:!0,description:`The amount to refill`},lastRefillAt:{type:`string`,format:`date-time`,nullable:!0,description:`The last refill date`},enabled:{type:`boolean`,description:`Sets if key is enabled or disabled`,default:!0},rateLimitEnabled:{type:`boolean`,description:`Whether the key has rate limiting enabled`},rateLimitTimeWindow:{type:`number`,nullable:!0,description:`The duration in milliseconds`},rateLimitMax:{type:`number`,nullable:!0,description:`Maximum amount of requests allowed within a window`},requestCount:{type:`number`,description:`The number of requests made within the rate limit time window`},remaining:{type:`number`,nullable:!0,description:`Remaining requests (every time api key is used this should updated and should be updated on refill as well)`},lastRequest:{type:`string`,format:`date-time`,nullable:!0,description:`When last request occurred`},expiresAt:{type:`string`,format:`date-time`,nullable:!0,description:`Expiry date of a key`},createdAt:{type:`string`,format:`date-time`,description:`created at`},updatedAt:{type:`string`,format:`date-time`,description:`updated at`},metadata:{type:`object`,nullable:!0,additionalProperties:!0,description:`Extra metadata about the apiKey`},permissions:{type:`string`,nullable:!0,description:`Permissions for the api key (stored as JSON string)`}},required:[`id`,`userId`,`enabled`,`rateLimitEnabled`,`requestCount`,`createdAt`,`updatedAt`]}}}}}}}},async t=>{let{configId:r,keyId:i,expiresIn:a,enabled:o,metadata:s,refillAmount:c,refillInterval:l,remaining:u,name:d,permissions:f,rateLimitEnabled:p,rateLimitTimeWindow:m,rateLimitMax:h}=t.body,g=await zJ(t,{disableCookieCache:!0}),_=t.request||t.headers,v=_&&!g?null:g?.user||{id:t.body.userId};if(!v?.id||g&&t.body.userId&&g?.user.id!==t.body.userId)throw E.from(`UNAUTHORIZED`,VQ.UNAUTHORIZED_SESSION);if(_&&(c!==void 0||l!==void 0||h!==void 0||m!==void 0||p!==void 0||u!==void 0||f!==void 0))throw E.from(`BAD_REQUEST`,VQ.SERVER_ONLY_PROPERTY);let y=h$(t.context,e,r),b=null;if(b=await a$(t,i,y),!b||!_$(b.configId,y.configId))throw E.from(`NOT_FOUND`,VQ.KEY_NOT_FOUND);let x=h$(t.context,e,b.configId);if((x.references??`user`)===`organization`)await u$(t,v.id,b.referenceId,`update`);else if(b.referenceId!==v.id)throw E.from(`NOT_FOUND`,VQ.KEY_NOT_FOUND);let S={};if(d!==void 0){if(d.length<x.minimumNameLength||d.length>x.maximumNameLength)throw E.from(`BAD_REQUEST`,VQ.INVALID_NAME_LENGTH);S.name=d}if(o!==void 0&&(S.enabled=o),a!==void 0){if(x.keyExpiration.disableCustomExpiresTime===!0)throw E.from(`BAD_REQUEST`,VQ.KEY_DISABLED_EXPIRATION);if(a!==null){let e=a/86400;if(e<x.keyExpiration.minExpiresIn)throw E.from(`BAD_REQUEST`,VQ.EXPIRES_IN_IS_TOO_SMALL);if(e>x.keyExpiration.maxExpiresIn)throw E.from(`BAD_REQUEST`,VQ.EXPIRES_IN_IS_TOO_LARGE)}S.expiresAt=a?d$(a,`sec`):null}if(s!==void 0&&x.enableMetadata===!0){if(typeof s!=`object`)throw E.from(`BAD_REQUEST`,VQ.INVALID_METADATA_TYPE);S.metadata=s}if(u!==void 0&&(S.remaining=u),c!==void 0||l!==void 0){if(c!==void 0&&l===void 0)throw E.from(`BAD_REQUEST`,VQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(l!==void 0&&c===void 0)throw E.from(`BAD_REQUEST`,VQ.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);S.refillAmount=c,S.refillInterval=l}if(p!==void 0&&(S.rateLimitEnabled=p),m!==void 0&&(S.rateLimitTimeWindow=m),h!==void 0&&(S.rateLimitMax=h),f!==void 0&&(S.permissions=JSON.stringify(f)),Object.keys(S).length===0)throw E.from(`BAD_REQUEST`,VQ.NO_VALUES_TO_UPDATE);let ee=b;try{if(x.storage===`secondary-storage`&&x.fallbackToDatabase){let e=await t.context.adapter.update({model:x$,where:[{field:`id`,value:b.id}],update:S});e&&(await o$(t,e,x),ee=e)}else if(x.storage===`database`){let e=await t.context.adapter.update({model:x$,where:[{field:`id`,value:b.id}],update:S});e&&(ee=e)}else{let e={...b,...S,updatedAt:/* @__PURE__ */ new Date};await o$(t,e,x),ee=e}}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}n(t.context);let C=await KQ(t,ee,x),{key:te,...ne}=ee;return t.json({...ne,metadata:C,permissions:ne.permissions?le(ne.permissions):null})})}function f$(e,t){let n=/* @__PURE__ */ new Date,r=e.lastRequest,i=e.rateLimitTimeWindow,a=e.rateLimitMax;if(t.rateLimit.enabled===!1||e.rateLimitEnabled===!1)return{type:`skip`,lastRequest:n};if(i===null||a===null)return{type:`skip`,lastRequest:null};if(r===null)return{type:`start`,now:n};let o=n.getTime()-new Date(r).getTime();return o>i?{type:`reset`,now:n,windowStart:new Date(n.getTime()-i)}:e.requestCount>=a?{type:`deny`,message:VQ.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(i-o)}:{type:`increment`,now:n,max:a,windowStart:new Date(n.getTime()-i)}}async function p$({key:e,ctx:t,lookupOpts:n,configurations:r,schema:i,permissions:a,expectedConfigId:o,runCustomValidator:s}){let c=n.disableKeyHashing?e:await b$(e),l=await i$(t,c,n);if(!l||o!==void 0&&!_$(l.configId,o))throw E.from(`UNAUTHORIZED`,VQ.INVALID_API_KEY);let u=h$(t.context,r,l.configId);if(s&&u.customAPIKeyValidator&&!await u.customAPIKeyValidator({ctx:t,key:e}))throw E.from(`UNAUTHORIZED`,VQ.KEY_NOT_FOUND);if(l.enabled===!1)throw E.from(`UNAUTHORIZED`,VQ.KEY_DISABLED);if(l.expiresAt&&Date.now()>new Date(l.expiresAt).getTime()){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await s$(t,l,u),await t.context.adapter.delete({model:x$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await s$(t,l,u):await t.context.adapter.delete({model:x$,where:[{field:`id`,value:l.id}]})};throw u.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),E.from(`UNAUTHORIZED`,VQ.KEY_EXPIRED)}if(a){let e=l.permissions?le(l.permissions):null;if(!e||!$e(e).authorize(a).success)throw E.from(`UNAUTHORIZED`,VQ.KEY_NOT_FOUND)}if(l.remaining===0&&l.refillAmount===null){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await s$(t,l,u),await t.context.adapter.delete({model:x$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await s$(t,l,u):await t.context.adapter.delete({model:x$,where:[{field:`id`,value:l.id}]})};throw u.deferUpdates?t.context.runInBackground(e().catch(e=>{t.context.logger.error(`Deferred update failed:`,e)})):await e(),E.from(`TOO_MANY_REQUESTS`,VQ.USAGE_EXCEEDED)}return{apiKey:u.storage===`database`||u.storage===`secondary-storage`&&u.fallbackToDatabase?await Gme({ctx:t,apiKey:l,opts:u,hashedKey:c}):await qme({ctx:t,apiKey:l,opts:u,hashedKey:c}),opts:u}}async function Gme({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t;t.remaining!==null&&(i=await Kme(e,t)),i=await m$(e,i,n);let a=await e.context.adapter.update({model:x$,where:[{field:`id`,value:i.id}],update:{updatedAt:/* @__PURE__ */ new Date}});if(!a)throw E.from(`UNAUTHORIZED`,VQ.INVALID_API_KEY);return n.storage===`secondary-storage`&&n.fallbackToDatabase&&await o$(e,a,n),a}async function Kme(e,t){let n=/* @__PURE__ */ new Date,{refillInterval:r,refillAmount:i}=t;if(r&&i){let a=new Date(t.lastRefillAt??t.createdAt).getTime();if(n.getTime()-a>r){let r=await e.context.adapter.incrementOne({model:x$,where:[{field:`id`,value:t.id},{field:`lastRefillAt`,value:t.lastRefillAt}],increment:{},set:{remaining:i-1,lastRefillAt:n}});if(r)return r}}let a=await e.context.adapter.incrementOne({model:x$,where:[{field:`id`,value:t.id},{field:`remaining`,operator:`gt`,value:0}],increment:{remaining:-1}});if(!a)throw E.from(`TOO_MANY_REQUESTS`,VQ.USAGE_EXCEEDED);return a}async function m$(e,t,n){let r=f$(t,n);if(r.type===`deny`)throw new E(`TOO_MANY_REQUESTS`,{message:r.message,code:`RATE_LIMITED`,details:{tryAgainIn:r.tryAgainIn}});if(r.type===`skip`)return r.lastRequest===null?t:await e.context.adapter.update({model:`apikey`,where:[{field:`id`,value:t.id}],update:{lastRequest:r.lastRequest}})??t;if(r.type===`increment`){let i=await e.context.adapter.incrementOne({model:x$,where:[{field:`id`,value:t.id},{field:`lastRequest`,operator:`gt`,value:r.windowStart},{field:`requestCount`,operator:`lt`,value:r.max}],increment:{requestCount:1},set:{lastRequest:r.now}});if(i)return i;let a=await e.context.adapter.findOne({model:x$,where:[{field:`id`,value:t.id}]});if(!a)throw E.from(`UNAUTHORIZED`,VQ.INVALID_API_KEY);return m$(e,a,n)}let i=r.type===`reset`?{field:`lastRequest`,operator:`lte`,value:r.windowStart}:{field:`lastRequest`,operator:`eq`,value:null},a=await e.context.adapter.incrementOne({model:x$,where:[{field:`id`,value:t.id},i],increment:{},set:{requestCount:1,lastRequest:r.now}});if(a)return a;let o=await e.context.adapter.findOne({model:x$,where:[{field:`id`,value:t.id}]});if(!o)throw E.from(`UNAUTHORIZED`,VQ.INVALID_API_KEY);return m$(e,o,n)}async function qme({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t.remaining,a=t.lastRefillAt;if(i!==null){let e=Date.now(),{refillInterval:n,refillAmount:r}=t,o=new Date(a??t.createdAt).getTime();if(n&&r&&e-o>n&&(i=r,a=/* @__PURE__ */ new Date),i===0)throw E.from(`TOO_MANY_REQUESTS`,VQ.USAGE_EXCEEDED);i--}let o={...Jme(t,n),remaining:i,lastRefillAt:a,updatedAt:/* @__PURE__ */ new Date},s=async()=>{let t=await i$(e,r,n);if(!t)return null;let i={...t,...o};return await o$(e,i,n),i};if(n.deferUpdates)return e.context.runInBackground(s().catch(t=>{e.context.logger.error(`Failed to update API key:`,t)})),{...t,...o};let c=await s();if(!c)throw E.from(`INTERNAL_SERVER_ERROR`,VQ.FAILED_TO_UPDATE_API_KEY);return c}function Jme(e,t){let n=f$(e,t);switch(n.type){case`deny`:throw new E(`TOO_MANY_REQUESTS`,{message:n.message,code:`RATE_LIMITED`,details:{tryAgainIn:n.tryAgainIn}});case`skip`:return n.lastRequest===null?{}:{lastRequest:n.lastRequest};case`start`:case`reset`:return{lastRequest:n.now,requestCount:1};case`increment`:return{lastRequest:n.now,requestCount:e.requestCount+1}}}const Yme=A({configId:k().meta({description:`Configuration ID to scope verification to. When omitted, the key is validated against its own configuration.`}).optional(),key:k().meta({description:`The key to verify`}),permissions:Ne(k(),Pe(k())).meta({description:`The permissions to verify.`}).optional()});function Xme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X.serverOnly({method:`POST`,body:Yme},async r=>{let{configId:i,key:a}=r.body,o=h$(r.context,e,i);if(i!==void 0&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:VQ.INVALID_API_KEY,code:`KEY_NOT_FOUND`},key:null});let s=null,c;try{let l=await p$({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:o,configurations:e,schema:t,expectedConfigId:i,runCustomValidator:i===void 0});s=l.apiKey,c=l.opts,c.deferUpdates&&r.context.runInBackground(n(r.context).catch(e=>{r.context.logger.error(`Failed to delete expired API keys:`,e)}))}catch(e){return r.context.logger.error(`Failed to validate API key:`,e),Mme(e)?r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null}):r.json({valid:!1,error:{message:VQ.INVALID_API_KEY,code:`INVALID_API_KEY`},key:null})}let{key:l,...u}=s??{key:1,permissions:void 0},d=null;return s&&(d=await KQ(r,s,c)),u.permissions=u.permissions?le(u.permissions):null,r.json({valid:!0,error:null,key:s===null?null:{...u,metadata:d}})})}function h$(e,t,n){let r=()=>{let n=t.find(e=>!e.configId||e.configId==="default");if(!n){e.logger.error("No default api-key configuration found. Either provide an api-key configuration with configId 'default' or provide a configuration with no `configId` set.");let t=VQ.NO_DEFAULT_API_KEY_CONFIGURATION_FOUND;throw E.from(`BAD_REQUEST`,t)}return{...n,configId:`default`}};return n?t.find(e=>e.configId===n)??r():r()}function g$(e){return!e||e==="default"}function _$(e,t){return g$(e)&&g$(t)?!0:e===t}let v$=null;async function y$(e,t=!1){v$&&!t&&(/* @__PURE__ */ new Date()).getTime()-v$.getTime()<1e4||(v$=/* @__PURE__ */ new Date,await e.adapter.deleteMany({model:x$,where:[{field:`expiresAt`,operator:`lt`,value:/* @__PURE__ */ new Date},{field:`expiresAt`,operator:`ne`,value:null}]}).catch(t=>{e.logger.error(`Failed to delete expired API keys:`,t)}))}function Zme({defaultKeyGenerator:e,configurations:t,schema:n}){return{createApiKey:Pme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:y$}),verifyApiKey:Xme({configurations:t,schema:n,deleteAllExpiredApiKeys:y$}),getApiKey:zme({configurations:t,schema:n,deleteAllExpiredApiKeys:y$}),updateApiKey:Wme({configurations:t,schema:n,deleteAllExpiredApiKeys:y$}),deleteApiKey:Lme({configurations:t,schema:n,deleteAllExpiredApiKeys:y$}),listApiKeys:Hme({configurations:t,schema:n,deleteAllExpiredApiKeys:y$}),deleteAllExpiredApiKeys:Fme({deleteAllExpiredApiKeys:y$})}}const Qme=({defaultRateLimitMax:e,defaultTimeWindow:t})=>({apikey:{fields:{configId:{type:`string`,required:!0,defaultValue:`default`,input:!1,index:!0},name:{type:`string`,required:!1,input:!1},start:{type:`string`,required:!1,input:!1},referenceId:{type:`string`,required:!0,input:!1,index:!0},prefix:{type:`string`,required:!1,input:!1},key:{type:`string`,required:!0,input:!1,index:!0},refillInterval:{type:`number`,required:!1,input:!1},refillAmount:{type:`number`,required:!1,input:!1},lastRefillAt:{type:`date`,required:!1,input:!1},enabled:{type:`boolean`,required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:`boolean`,required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:`number`,required:!1,input:!1,defaultValue:t},rateLimitMax:{type:`number`,required:!1,input:!1,defaultValue:e},requestCount:{type:`number`,required:!1,input:!1,defaultValue:0},remaining:{type:`number`,required:!1,input:!1},lastRequest:{type:`date`,required:!1,input:!1},expiresAt:{type:`date`,required:!1,input:!1},createdAt:{type:`date`,required:!0,input:!1},updatedAt:{type:`date`,required:!0,input:!1},permissions:{type:`string`,required:!1,input:!1},metadata:{type:`string`,required:!1,input:!0,transform:{input(e){return JSON.stringify(e)},output(e){return e?Tme(e):null}}}}}}),b$=async e=>{let t=await MU(`SHA-256`).digest(new TextEncoder().encode(e));return ye.encode(new Uint8Array(t),{padding:!1})},x$=`apikey`;function $me(e,t){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new D(`configId is required for each API key configuration in the api-key plugin.`);let t=e.map(e=>e.configId);if(new Set(t).size!==t.length)throw new D(`configId must be unique for each API key configuration in the api-key plugin.`)}let n=t??{schema:Array.isArray(e)?void 0:e?.schema},r=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??`x-api-key`,defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??`database`,rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],i=lG(Qme({defaultRateLimitMax:(r.length===1?r[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(r.length===1?r[0]?.rateLimit.timeWindow:void 0)??864e5}),n.schema),a=async e=>{let t=JH(e.length,`a-z`,`A-Z`);return`${e.prefix||``}${t}`};function o(e,t){if(t.customAPIKeyGetter)return t.customAPIKeyGetter(e);if(Array.isArray(t.apiKeyHeaders)){for(let n of t.apiKeyHeaders){let t=e.headers?.get(n);if(t)return t}return null}return e.headers?.get(t.apiKeyHeaders)??null}function s(e){for(let t of r){if(!t.enableSessionForAPIKeys)continue;let n=o(e,t);if(n)return{key:n,config:t}}return null}let c=Zme({defaultKeyGenerator:a,configurations:r,schema:i});return{id:`api-key`,version:`1.7.10`,$ERROR_CODES:VQ,hooks:{before:[{matcher:e=>!!s(e),handler:zq(async e=>{let{key:t,config:n}=s(e);if(typeof t!=`string`)throw E.from(`BAD_REQUEST`,VQ.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:t}))throw E.from(`FORBIDDEN`,VQ.INVALID_API_KEY);let{apiKey:a}=await p$({key:t,ctx:e,lookupOpts:n,configurations:r,schema:i,expectedConfigId:n.configId}),o=y$(e.context).catch(t=>{e.context.logger.error(`Failed to delete expired API keys:`,t)});if(n.deferUpdates&&e.context.runInBackground(o),(n.references??`user`)!==`user`){let e=VQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let c=await e.context.internalAdapter.findUserById(a.referenceId);if(!c){let e=VQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let l={user:c,session:{id:a.id,token:t,userId:a.referenceId,userAgent:e.request?.headers.get(`user-agent`)??null,ipAddress:e.request?xJ(e.request,e.context.options):null,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,expiresAt:a.expiresAt||d$(e.context.options.session?.expiresIn||604800,`ms`)}};return e.context.session=l,e.path===`/get-session`?l:{context:e}})}]},endpoints:{createApiKey:c.createApiKey,verifyApiKey:c.verifyApiKey,getApiKey:c.getApiKey,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,listApiKeys:c.listApiKeys,deleteAllExpiredApiKeys:c.deleteAllExpiredApiKeys},schema:i}}const S$=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await SH(e)).findMany({model:`jwks`}),getLatestKey:async n=>{let r=/* @__PURE__ */ new Date,i=e=>!e.expiresAt||e.expiresAt>r;return t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]:(await(await SH(e)).findMany({model:`jwks`}))?.filter(i).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},getKeyById:async(n,r)=>t?.adapter?.getJwks?(await t.adapter.getJwks(n))?.find(e=>e.id===r):await(await SH(e)).findOne({model:`jwks`,where:[{field:`id`,value:r}]})??void 0,getLatestKeyByAlg:async(n,r)=>{let i=t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await SH(e)).findMany({model:`jwks`});if(!i)return;let a=t?.jwks?.keyPairConfig?.alg??`EdDSA`,o=/* @__PURE__ */ new Date;return i.filter(e=>e.alg===r||e.alg==null&&a===r).filter(e=>!e.expiresAt||e.expiresAt>o).sort((e,t)=>t.createdAt.getTime()-e.createdAt.getTime())[0]},createJwk:async(n,r)=>t?.adapter?.createJwk?await t.adapter.createJwk(r,n):await(await SH(e)).create({model:`jwks`,data:{...r,createdAt:/* @__PURE__ */ new Date}})});function C$(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+mG(e)}async function ehe(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await Rde(t,{...n,extractable:!0});return{publicWebKey:await sI(r),privateWebKey:await sI(i),alg:t,cfg:n}}async function w$(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await ehe(t),o=a&&`crv`in a?a.crv:void 0,s=typeof n.crv==`string`?n.crv:void 0,c=o??s,l=JSON.stringify(r),u=!t?.jwks?.disablePrivateKeyEncryption,d={alg:i,...c?{crv:c}:{},publicKey:JSON.stringify(n),privateKey:u?JSON.stringify(await RW({key:e.context.secretConfig,data:l})):l,createdAt:/* @__PURE__ */ new Date,...t?.jwks?.rotationInterval?{expiresAt:new Date(Date.now()+t.jwks.rotationInterval*1e3)}:{}};return await S$(e.context.adapter,t).createJwk(e,d)}async function T$(e,t,n){if(t?.jwt?.sign)return null;let r=S$(e.context.adapter,t),i;if(n?.signingKeyId!==void 0){if(i=await r.getKeyById(e,n.signingKeyId),!i)throw new D(`signJWT: signingKeyId "${n.signingKeyId}" not found in JWKS. The key must be provisioned before it can be referenced.`);if(n.signingAlgorithm!==void 0){let e=t?.jwks?.keyPairConfig?.alg??`EdDSA`;if((i.alg??e)!==n.signingAlgorithm)throw new D(`signJWT: signingKeyId "${n.signingKeyId}" has alg "${i.alg??`unset (inherits keyPairConfig.alg "${e}")`}" but signingAlgorithm was set to "${n.signingAlgorithm}".`)}}else if(n?.signingAlgorithm!==void 0){if(i=await r.getLatestKeyByAlg(e,n.signingAlgorithm),!i){let r=t?.jwks?.keyPairConfig?.alg??`EdDSA`,a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await w$(e,{...t,jwks:{...t?.jwks,keyPairConfig:a??t?.jwks?.keyPairConfig}});else{let e=t?.jwks?.keyPairConfigs?.map(e=>e.alg).join(`, `)||`none`;throw new D(`signJWT: no key with alg "${n.signingAlgorithm}" found in JWKS. The plugin auto-mints only one key matching keyPairConfig.alg="${r}"; additional algs configured via keyPairConfigs: ${e}. Add "${n.signingAlgorithm}" to jwks.keyPairConfigs so the plugin provisions it on first use, or mint the key explicitly via createJwk().`)}}}else{let n=t?.jwks?.keyPairConfig?.alg??`EdDSA`;i=await r.getLatestKeyByAlg(e,n)??await r.getLatestKey(e)}if(!i||i.expiresAt&&i.expiresAt</* @__PURE__ */ new Date){if(n?.signingKeyId!==void 0||n?.signingAlgorithm!==void 0)throw new D(`signJWT: requested signing key is expired and an explicit kid/alg was provided; not auto-minting a replacement. Rotate the key explicitly.`);i=await w$(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await zW({key:e.context.secretConfig,data:JSON.parse(i.privateKey)}).catch(()=>{throw new D(`Failed to decrypt private key. Make sure the secret currently in use is the same as the one used to encrypt the private key. If you are using a different secret, either clean up your JWKS or disable private key encryption.`)}),o=i.alg??t?.jwks?.keyPairConfig?.alg??`EdDSA`,s=await hI(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function E$(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=C$(n?.jwt?.expirationTime??`15m`,a??i);o??=s;let c=r.nbf,l=typeof e.context.options.baseURL==`string`?e.context.options.baseURL:``,u=r.iss,d=n?.jwt?.issuer??l,f=r.aud,p=n?.jwt?.audience??l;if(n?.jwt?.sign){let e={...r,iat:a,exp:o,nbf:c,iss:u??d,aud:f??p};return n.jwt.sign(e,t.header,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm})}let{alg:m,kid:h,privateKey:g}=t.resolvedKey??await T$(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new iI(r).setProtectedHeader({...t.header,alg:m,kid:h}).setExpirationTime(o).setIssuer(u??d).setAudience(f??p);return a&&_.setIssuedAt(a),r.sub&&_.setSubject(r.sub),r.nbf&&_.setNotBefore(r.nbf),r.jti&&_.setJti(r.jti),await _.sign(g)}async function D$(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await E$(e,{options:t,payload:{iat:Math.floor(Date.now()/1e3),...n,sub:await t?.jwt?.getSubject?.(e.context.session)??e.context.session.user.id}})}function O$(e){let t=e.context.options.baseURL;return typeof t==`string`?t||`better-auth:session-cache`:e.context.baseURL||`better-auth:session-cache`}async function the(e,t,n){let r=gI(t),i=r.kid;if(!i)return e.context.logger.debug(`Cookie-cache JWT missing kid in header`),null;let a=await S$(e.context.adapter,n).getAllKeys(e);if(!a?.length)return e.context.logger.debug(`No JWKS keys available for cookie-cache JWT`),null;let o=a.find(e=>e.id===i);if(!o)return e.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${i}`),null;let s=o.alg??n?.jwks?.keyPairConfig?.alg??r.alg;return s?{alg:s,publicKey:await hI(JSON.parse(o.publicKey),s)}:(e.context.logger.debug(`No JWT algorithm available for cookie-cache JWT kid: ${i}`),null)}async function nhe(e,t,n,r){let i=await T$(e,r);if(!i)throw new D("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new iI({...t,sid:t.session.token}).setProtectedHeader({alg:i.alg,kid:i.kid,typ:`better-auth.session-cache+jwt`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).setIssuer(O$(e)).setAudience(`better-auth:session-cache`).setSubject(t.user.id).sign(i.privateKey)}async function rhe(e,t,n){try{if(gI(t).typ!==`better-auth.session-cache+jwt`)return null;let r=await the(e,t,n);if(!r)return null;let{payload:i}=await nI(t,r.publicKey,{...DG({issuer:O$(e)}),algorithms:[r.alg]}),a=OG(i);return a?{payload:a,expiresAt:a.exp?a.exp*1e3:Date.now()}:null}catch(t){return e.context.logger.debug(`Cookie-cache JWT verification failed`,t),null}}function ihe(e){return{sign:(t,n,r)=>nhe(t,n,r,e),verify:(t,n)=>rhe(t,n,e)}}const ahe={jwks:{fields:{publicKey:{type:`string`,required:!0},privateKey:{type:`string`,required:!0},createdAt:{type:`date`,required:!0},expiresAt:{type:`date`,required:!1},alg:{type:`string`,required:!1},crv:{type:`string`,required:!1}}}};async function ohe(e,t){let n=pH();try{let r=e.split(`.`);if(r.length!==3)return null;let i=new TextDecoder().decode(ue.decode(r[0])),a=JSON.parse(i).kid;if(!a)return n.context.logger.debug(`JWT missing kid in header`),null;let o=await S$(n.context.adapter,t).getAllKeys(n);if(!o||o.length===0)return n.context.logger.debug(`No JWKS keys available`),null;let s=o.find(e=>e.id===a);if(!s)return n.context.logger.debug(`No JWKS key found for kid: ${a}`),null;let c=await hI(JSON.parse(s.publicKey),s.alg??t?.jwks?.keyPairConfig?.alg??`EdDSA`),l=typeof n.context.options.baseURL==`string`?n.context.options.baseURL:void 0,{payload:u}=await nI(e,c,{issuer:t?.jwt?.issuer??l,audience:t?.jwt?.audience??l});return!u.sub||!u.aud?null:u}catch(e){return n.context.logger.debug(`JWT verification failed`,e),null}}const she=A({payload:Ne(k(),Ke()),overrideOptions:Ne(k(),Ke()).optional()}),che=A({token:k(),issuer:k().optional()}),lhe=e=>{if(e?.jwt?.sign&&!e.jwks?.remoteUrl)throw new D(`options.jwks.remoteUrl must be set when using options.jwt.sign`);if(e?.jwks?.remoteUrl&&!e.jwks?.keyPairConfig?.alg)throw new D(`options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata`);let t=e?.jwks?.jwksPath??`/jwks`;if(typeof t!=`string`||t.length===0||!t.startsWith(`/`)||t.includes(`..`))throw new D(`options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'`);return{id:`jwt`,version:`1.7.10`,options:e,init(t){if(!e?.sessionCookieCache)return;if(t.options.session?.cookieCache?.strategy!==`jwt`)throw new D('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(e.jwt?.sign)throw new D("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let n=e.jwks?.gracePeriod,r=t.options.session.cookieCache.maxAge||300;return n!==void 0&&r>n&&t.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${r}s) exceeds the JWT plugin JWKS grace period (${n}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...t.sessionConfig,cookieCacheSigner:ihe(e)}}}},endpoints:{getJwks:X(t,{method:`GET`,metadata:{openapi:{operationId:`getJSONWebKeySet`,description:`Get the JSON Web Key Set`,responses:{200:{description:`JSON Web Key Set retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{keys:{type:`array`,description:`Array of public JSON Web Keys`,items:{type:`object`,properties:{kid:{type:`string`,description:`Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk`},kty:{type:`string`,description:`Key type (e.g., 'RSA', 'EC', 'OKP')`},alg:{type:`string`,description:`Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')`},use:{type:`string`,description:`Intended use of the public key (e.g., 'sig' for signature)`,enum:[`sig`],nullable:!0},n:{type:`string`,description:`Modulus for RSA keys (base64url-encoded)`,nullable:!0},e:{type:`string`,description:`Exponent for RSA keys (base64url-encoded)`,nullable:!0},crv:{type:`string`,description:`Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')`,nullable:!0},x:{type:`string`,description:`X coordinate for elliptic curve keys (base64url-encoded)`,nullable:!0},y:{type:`string`,description:`Y coordinate for elliptic curve keys (base64url-encoded)`,nullable:!0}},required:[`kid`,`kty`,`alg`]}}},required:[`keys`]}}}}}}}},async t=>{if(e?.jwks?.remoteUrl)throw new E(`NOT_FOUND`);let n=S$(t.context.adapter,e),r=await n.getAllKeys(t);if((!r||r?.length===0)&&(await w$(t,e),r=await n.getAllKeys(t)),!r?.length)throw new D(`No key sets found. Make sure you have a key in your database.`);let i=Date.now(),a=(e?.jwks?.gracePeriod??2592e3)*1e3,o=r.filter(e=>!e.expiresAt||e.expiresAt.getTime()+a>i),s=e?.jwks?.keyPairConfig,c=s&&`crv`in s?s.crv:void 0;return t.json({keys:o.map(t=>({alg:t.alg??e?.jwks?.keyPairConfig?.alg??`EdDSA`,crv:t.crv??c,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:X(`/token`,{method:`GET`,requireHeaders:!0,use:[VJ],metadata:{openapi:{operationId:`getJSONWebToken`,description:`Get a JWT token`,responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{token:{type:`string`}}}}}}}}}},async t=>{let n=await D$(t,e);return t.json({token:n})}),signJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{}}},body:she},async t=>{let n=await E$(t,{options:{...e,...t.body.overrideOptions},payload:t.body.payload});return t.json({token:n})}),verifyJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{},response:{}}},body:che},async t=>{let n=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,r=await ohe(t.body.token,n);return t.json({payload:r})})},hooks:{after:[{matcher(e){return e.path===`/get-session`},handler:zq(async t=>{if(e?.disableSettingJwtHeader)return;let n=t.context.session||t.context.newSession;if(n&&n.session){let n=await D$(t,e),r=t.context.responseHeaders?.get(`access-control-expose-headers`)||``,i=new Set(r.split(`,`).map(e=>e.trim()).filter(Boolean));i.add(`set-auth-jwt`),t.setHeader(`set-auth-jwt`,n),t.setHeader(`Access-Control-Expose-Headers`,Array.from(i).join(`, `))}})}]},schema:lG(ahe,e?.schema)}};var k$=Object.defineProperty,A$=(e,t)=>{let n={};for(var r in e)k$(n,r,{get:e[r],enumerable:!0});return t||k$(n,Symbol.toStringTag,{value:`Module`}),n};const j$=`ba_iat`,M$=`ba_pl`,N$=`ba_param`;function P$(e){let t=new URLSearchParams,n=[...e.entries()].sort(([e,t],[n,r])=>e<n?-1:e>n?1:t<r?-1:+(t>r));for(let[e,r]of n)t.append(e,r);return t}function uhe(e){e.delete(N$);let t=[.../* @__PURE__ */ new Set([...e.keys(),N$])].sort();for(let n of t)e.append(N$,n)}function dhe(e){let t=new URLSearchParams(e).get(j$);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}const fhe=[`authorization_code`,`client_credentials`,`refresh_token`],F$=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],phe=[`none`,...F$],mhe=new Set(phe);function I$(e,t){if(!(t.trim().length>0))throw new D(`OAuth Provider extension ${e} cannot be empty`)}function L$(e,t){I$(e,t);let n;try{n=new URL(t)}catch{n=void 0}if(!n?.protocol)throw new D(`OAuth Provider extension ${e} must be an absolute URI: ${t}`)}function hhe(e){L$(`grant type`,e)}function ghe(e){if(I$(`token_endpoint_auth_method`,e),mhe.has(e))throw new D(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function _he(e){if(L$(`client_assertion_type`,e),e===`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new D(`OAuth Provider extension client_assertion_type is reserved: ${e}`)}function vhe(e){let t=Object.keys(e.grants??{});for(let e of t)hhe(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){ghe(t),n.push(t);let e=i.assertionTypes??[t];if(e.length===0)throw new D(`OAuth Provider extension client_assertion_type list cannot be empty for ${t}`);for(let t of e)_he(t),r.push(t)}let i=(e.clientDiscovery?Array.isArray(e.clientDiscovery)?e.clientDiscovery:[e.clientDiscovery]:[]).map(e=>e.id);for(let e of i)I$(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function R$(e,t){let n=/* @__PURE__ */ new Set;for(let r of t){if(n.has(r))throw new D(`OAuth Provider extensions register ${e} "${r}" more than once. Extension contributions must be disjoint.`);n.add(r)}}function z$(e){let t=(e??[]).map(vhe);R$(`grant type`,t.flatMap(e=>e.grantTypes)),R$(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),R$(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),R$(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function B$(e){return e.extensions??[]}function V$(e){return B$(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function yhe(e,t){let n=e.getPlugin(`oauth-provider`);if(!n)throw new D(`extendOAuthProvider requires the oauth-provider plugin.`);let r=n.options.extensions??[];if(r.includes(t))return;let i=[...r,t];z$(i),n.options.extensions=i}function bhe(e){return B$(e).flatMap(e=>Object.keys(e.grants??{}))}function H$(e){return Array.from(/* @__PURE__ */ new Set([...e.grantTypes??fhe,...bhe(e)]))}function xhe(e,t){for(let n of B$(e)){let e=n.grants?.[t];if(e)return e}}function U$(e){return B$(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function W$(e,t){return Array.from(/* @__PURE__ */ new Set([...t?.includeNone?[`none`]:[],...F$,...U$(e)]))}function G$(e,t){return t?U$(e).includes(t):!1}function She(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of B$(e)){let e=n.clientAuthentication??{};for(let[n,r]of Object.entries(e))if((r.assertionTypes??[n]).includes(t))return{method:n,strategy:r}}}function K$(e,t,n,r){let i={...r};for(let a of B$(t)){let o=a.metadata?.({ctx:e,opts:t,type:n,document:r});for(let[e,t]of Object.entries(o??{}))e in i||(i[e]=t)}return i}async function q$(e,t){let n={};for(let r of B$(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?f.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function Che(e,t){return q$(e,e=>e.claims?.accessToken?.(t))}function whe(e,t){return q$(e,e=>e.claims?.idToken?.(t))}function The(e,t){return q$(e,e=>e.claims?.userInfo?.(t))}function Ehe(e){return B$(e).some(e=>e.claims?.userInfo)}function Dhe(e){if(!e)return;let[t,n,...r]=e.trim().split(/\s+/);if(t?.toLowerCase()===`bearer`){if(!n||r.length>0)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Malformed Bearer Authorization header`});return n}}function Ohe(){let e=/* @__PURE__ */ new Map;return{get(t){let n=e.get(t);if(n){if(n.expiresAt&&n.expiresAt</* @__PURE__ */ new Date)e.delete(t);else return n}},set(t,n){e.set(t,n)}}}const J$=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new D(`jwt_config`);return t},khe=/* @__PURE__ */ new Set([hP.code,fP.code,mP.code]);function Y$(e){return e instanceof nP&&!khe.has(e.code)}function X$(e){if(e!=null){if(e instanceof Date)return Number.isFinite(e.getTime())?e:void 0;if(typeof e==`number`){if(!Number.isFinite(e))return;let t=new Date(e);return Number.isFinite(t.getTime())?t:void 0}if(typeof e==`string`){let t=e.trim();if(!t.length)return;let n=Number(t);if(Number.isFinite(n)){let e=new Date(n);return Number.isFinite(e.getTime())?e:void 0}let r=new Date(t);return Number.isFinite(r.getTime())?r:void 0}}}function Ahe(e){if(e instanceof Date||!e||typeof e!=`object`)return X$(e);let t=X$(e.createdAt)??X$(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return X$(n.createdAt)??X$(n.created_at)}function Z$(e){if(typeof e==`string`)return[e];if(e?.length)return e}function Q$(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}const $$=/* @__PURE__ */ new WeakMap;function jhe(e){let t=$$.get(e);if(t)return t;let n=Ohe();return $$.set(e,n),n}async function e1(e,t){let n=new URLSearchParams(e),r=n.get(`sig`),i=n.getAll(`sig`),a=Number(n.get(`exp`));n.delete(`sig`);let o=await VW(P$(n).toString(),t);return i.length===1&&!!r&&wU(r,o)&&/* @__PURE__ */ new Date(a*1e3)>=/* @__PURE__ */ new Date}function t1(e,t){if(e.cachedTrustedClients?.has(t))throw new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:`trusted clients must be updated manually`})}async function n1(e,t,n){let r=jhe(t),i=r.get(n);if(i&&!i.clientDiscoveryId)return Object.assign({},i);let a=await e.context.adapter.findOne({model:t.schema?.oauthClient?.modelName??`oauthClient`,where:[{field:`clientId`,value:n}]}),o=V$(t);if(a?.clientDiscoveryId){let t=a.clientDiscoveryId,r=o.find(e=>e.id===t);if(!r?.matches(n)||(a=await r.resolve(e,n,a),!a))return null}else if(a)return t.cachedTrustedClients?.has(n)&&r.set(n,Object.assign({},a)),a;else for(let t of o){if(!t.matches(n))continue;let r=await t.resolve(e,n,null);if(r){a=r;break}}return a}function r1(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}const i1=async e=>{let t=await MU(`SHA-256`).digest(new TextEncoder().encode(e));return ye.encode(new Uint8Array(t),{padding:!1})};async function a1(e,t,n){if(t===`encrypted`)return await zW({key:e.context.secretConfig,data:n});if(typeof t==`object`&&`decrypt`in t)return await t.decrypt(n);throw new D(`Unsupported decryption storageMethod type '${t}'`)}async function Mhe(e,t,n,r){let i=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r&&t.prefix?.clientSecret){if(r.startsWith(t.prefix?.clientSecret))r=r.replace(t.prefix.clientSecret,``);else throw new O(`UNAUTHORIZED`,{error_description:`invalid client_secret`,error:`invalid_client`})}if(i===`hashed`){let e=r?await i1(r):void 0;return!!e&&wU(e,n)}if(typeof i==`object`&&`hash`in i){if(i.verify)return!!r&&await i.verify(r,n);{let e=r?await i.hash(r):void 0;return!!e&&wU(e,n)}}if(i===`encrypted`)try{let t=await a1(e,i,n);return!!r&&wU(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await a1(e,i,n);return!!r&&wU(t,r)}throw new D(`Unsupported verify storageMethod type '${i}'`)}async function o1(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await RW({key:e.context.secretConfig,data:n});if(r===`hashed`)return await i1(n);if(typeof r==`object`&&`hash`in r)return await r.hash(n);if(typeof r==`object`&&`encrypt`in r)return await r.encrypt(n);throw new D(`Unsupported storeClientSecret type '${r}'`)}async function s1(e=`hashed`,t,n){if(e===`hashed`)return await i1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`storeToken: unsupported storageMethod type '${e}'`)}async function c1(e=`hashed`,t,n){if(e===`hashed`)return await i1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`getStoredToken: unsupported storageMethod type '${e}'`)}const l1=/^Basic +/i,Nhe=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Phe(e){return e.match(Nhe)?.[1]}const u1=[`client_secret`,`client_assertion`,`client_assertion_type`];function d1(e){throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function Fhe(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&d1(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&d1(`${e} must be a string`),r[e]=t)};for(let e of u1)Object.hasOwn(t,e)&&i(e,t[e]);let a=!!e?.headers.get(`authorization`);if(e&&(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`)){let t=new URLSearchParams(await e.clone().text()),r=t.getAll(`client_id`).filter(e=>e.length>0);r.length>1&&d1(`client_id must not be repeated`),n=r[0];for(let e of u1){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&d1(`${e} must not be repeated`),n.length===1&&i(e,n[0])}}let o=r.client_secret!==void 0,s=r.client_assertion!==void 0||r.client_assertion_type!==void 0;(a&&(o||s)||o&&s)&&d1(`A request must use only one client authentication method`),t.client_id=n;for(let e of u1)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function Ihe(e){if(l1.test(e))try{let{clientId:t,clientSecret:n}=rX(e);return{client_id:t,client_secret:n}}catch{throw new O(`UNAUTHORIZED`,{error_description:`invalid authorization header format`,error:`invalid_client`},{"WWW-Authenticate":`Basic`})}}function f1(e,t){let n=e.grantTypes&&e.grantTypes.length>0?e.grantTypes:[`authorization_code`];return t===`refresh_token`&&n.includes(`authorization_code`)?!0:n.includes(t)}function p1(e,t){if(!t||!e.scopes)return;let n=new Set(e.scopes);for(let e of t)if(!n.has(e))throw new O(`BAD_REQUEST`,{error_description:`client does not allow scope ${e}`,error:`invalid_scope`})}function m1(e,t){let n=t?.method===`client_secret_basic`,r=t?.scheme??(n?`Basic`:void 0);throw new O(r?`UNAUTHORIZED`:`BAD_REQUEST`,{error_description:e,error:`invalid_client`},r?{"WWW-Authenticate":r}:void 0)}async function h1(e,t,n,r,i,a,o,s){let c=await n1(e,t,n);c||m1(`client not found`,{method:s}),c.disabled&&m1(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&m1(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||G$(t,c.tokenEndpointAuthMethod))&&!a)throw new O(`BAD_REQUEST`,{error_description:`client registered for ${c.tokenEndpointAuthMethod} must use client_assertion`,error:`invalid_client`});if(a||(c.tokenEndpointAuthMethod!==`none`&&!r&&m1(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&m1(`public client, client secret should not be received`,{method:s}),r&&!await Mhe(e,t,c.clientSecret,r)&&m1(`invalid client_secret`,{method:s})),p1(c,i),o&&!f1(c,o))throw new O(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function g1(e){if(e)return typeof e==`string`?JSON.parse(e):e}function _1(e){return{clientId:e?.clientId,clientSecret:e?.kind===`client_secret`?e.clientSecret:void 0,preVerified:e?.kind===`pre_verified`,authMethod:e?.method,confirmation:e?.kind===`pre_verified`?e.confirmation:void 0}}async function v1(e,t,n){let r={...e.body??{}};await Fhe(e.request,r);let i=e.request?.headers.get(`authorization`)??void 0;if(r.client_assertion_type||r.client_assertion){if(!r.client_assertion||!r.client_assertion_type)throw new O(`BAD_REQUEST`,{error_description:`client_assertion and client_assertion_type must both be provided`,error:`invalid_client`});let i=r.client_assertion,a=r.client_assertion_type,o=She(t,a);if(o){let s=await o.strategy.authenticate({ctx:e,opts:t,assertion:i,assertionType:a,clientId:r.client_id,expectedAudience:n});return{kind:`pre_verified`,method:o.method,clientId:s.clientId,confirmation:s.confirmation}}let{verifyClientAssertion:s}=await Promise.resolve().then(()=>a_e).then(e=>e.o);return{kind:`pre_verified`,method:`private_key_jwt`,clientId:(await s(e,t,i,a,r.client_id,n)).clientId}}if(i&&!l1.test(i)){let e=Phe(i);if(!e)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});m1(`unsupported authorization scheme`,{scheme:e})}if(i&&l1.test(i)){let e=Ihe(i);if(e)return{kind:`client_secret`,method:`client_secret_basic`,clientId:e.client_id,clientSecret:e.client_secret}}return r.client_id&&r.client_secret?{kind:`client_secret`,method:`client_secret_post`,clientId:r.client_id,clientSecret:r.client_secret}:r.client_id?{kind:`public`,method:`none`,clientId:r.client_id}:null}function y1(e){let t=e.split(` `).map(e=>e.trim()),n=/* @__PURE__ */ new Set;for(let e of t)(e===`login`||e===`consent`||e===`create`||e===`select_account`||e===`none`)&&n.add(e);return new Set(n)}function Lhe(e){let t=e.redirectUris?.[0];if(!t)throw new D(`Client has no redirect URIs for sector identifier`);return new URL(t).host}async function Rhe(e,t,n){return VW(`${Lhe(t)}.${e}`,n)}async function b1(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?Rhe(e,t,n.pairwiseSecret):e}async function x1(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function S1(e,t,n,r){let i=[{field:`clientId`,value:t},{field:`userId`,value:n}];if(r)return e.context.adapter.findOne({model:`oauthConsent`,where:[...i,{field:`referenceId`,value:r}]});for(let t=0;;t+=100){let n=await e.context.adapter.findMany({model:`oauthConsent`,where:i,limit:100,offset:t,sortBy:{field:`id`,direction:`asc`}}),r=n.find(e=>!e.referenceId);if(r||n.length<100)return r??null}}function C1(e){let t=Object.create(null);for(let n of new Set(e.keys())){let r=e.getAll(n);t[n]=r.length===1?r[0]:r}return t}function w1(e,t){if(!t)return!1;let n=X$(e);return n?n.getTime()>=t.getTime():!1}function T1(e,t){let n=new URLSearchParams(e),r=n.get(`prompt`)?.split(` `),i=r?.findIndex(e=>e===t)??-1;return i>=0&&(r?.splice(i,1),r?.length?n.set(`prompt`,r.join(` `)):n.delete(`prompt`)),n}function E1(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function D1(e,t){if(e.tokenEndpointAuthMethod===`none`)return`pkce is required for public clients`;let n=t?.scopes??[],r=n.includes(`openid`),i=typeof t?.nonce==`string`&&t.nonce.length>0,a=r&&i;return n.includes(`offline_access`)&&!a?`pkce or OIDC nonce is required when requesting offline_access scope`:e.requirePKCE??!0?`pkce is required for this client`:!1}const zhe=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,Bhe=/* @__PURE__ */ new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function O1(e){let t=e.protocol.slice(0,-1),n=e.href.slice(e.protocol.length);return e.protocol!==`http:`&&e.protocol!==`https:`&&e.host.length===0&&n.startsWith(`/`)&&!n.startsWith(`//`)&&zhe.test(t)}function Vhe(e){return Bhe.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function k1(e){return O1(e)||Vhe(e)}const A1=iee().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),Be}xq.includes(n.protocol)?t.addIssue({code:`custom`,message:`URL cannot use javascript:, data:, or vbscript: scheme`}):(e.includes(`#`)&&t.addIssue({code:`custom`,message:`Redirect URI must not contain a fragment component`}),n.protocol===`http:`&&!SY(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))}),Hhe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function j1(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))Hhe.has(r)?t.push(r):n[r]=i;return t.length>0&&f.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}const M1=Ne(k(),Je()).nullable(),Uhe=Re({essential:He().optional(),value:k().optional(),values:Pe(k()).optional()}).nullable(),Whe=A({acr:Uhe.optional()}).catchall(M1),Ghe=Re({userinfo:Ne(k(),M1).optional(),id_token:Whe.optional()});function Khe(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function N1(e){let t=Khe(e),n=Ghe.safeParse(t);return n.success?n.data:void 0}const P1=Ee([k(),Ne(k(),Je())]),qhe=P1,F1=P1.refine(e=>N1(e)!==void 0,{error:`claims must be a valid Claims request object`});function Jhe(e){return e===void 0||N1(e)!==void 0}function I1(e,t){let n=N1(e)?.userinfo;if(!n)return[];let r=Object.keys(n);if(!t)return r;let i=new Set(t);return r.filter(e=>i.has(e))}function Yhe(e,t){let n=N1(e);if(!n)return e===void 0;let r=n.id_token?.acr;if(!r||r.essential!==!0)return!0;let i=r.value===void 0||r.value===t,a=r.values===void 0||r.values.includes(t);return i&&a}function Xhe(e,t){let n=N1(e);if(!n)return;let r=new Set(t),i=Object.fromEntries(Object.entries(n.userinfo??{}).filter(([e])=>r.has(e))),a=Object.keys(i).length?{...n,userinfo:i}:Object.fromEntries(Object.entries(n).filter(([e])=>e!==`userinfo`));return Object.keys(a).length?a:void 0}function L1(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}const R1={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>L1(e.name).given},family_name:{scope:`profile`,resolve:e=>L1(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},z1=Object.keys(R1);function B1(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}const Zhe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function Qhe(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))Zhe.has(r)?t.push(r):n[r]=i;return t.length>0&&f.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function V1(e){let{ctx:t,opts:n,user:r,client:i,scopes:a,resources:o,referenceId:s,metadata:c,grantType:l,sessionId:u,perRequestClaims:d,resourcePolicyClaims:f}=e,p=await Che(n,{ctx:t,opts:n,user:r,client:i,scopes:a,grantType:l,referenceId:s,sessionId:u,resources:o,metadata:c}),m=n.customAccessTokenClaims?await n.customAccessTokenClaims({user:r,scopes:a,resources:o,referenceId:s,metadata:c}):{};return Qhe({...p,...d??{},...m,...f})}const $he=[`javascript:`,`data:`,`vbscript:`],H1=k().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),Be;e.includes(`#`)?t.addIssue({code:`custom`,message:`resource must not contain a fragment`}):$he.includes(new URL(e).protocol)&&t.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),ege=We([`none`,`consent`,`login`,`create`,`select_account`]),tge=k().superRefine((e,t)=>{let n=e.split(` `).map(e=>e.trim()).filter(Boolean),r=/* @__PURE__ */ new Set;if(!n.length)t.addIssue({code:`custom`,message:`prompt must include at least one value`});else{for(let e of n){let n=ege.safeParse(e);n.success?r.add(n.data):t.addIssue({code:`custom`,message:`unsupported prompt value: ${e}`})}r.has(`none`)&&r.size>1&&t.addIssue({code:`custom`,message:`prompt=none cannot be combined with other prompt values`})}}),U1=A({keys:Pe(Ne(k(),Je())).min(1)}),nge=Ee([Me(),k().trim().min(1)]).transform((e,t)=>{let n=typeof e==`number`?e:Number(e);return!Number.isInteger(n)||n<0?(t.addIssue({code:`custom`,message:`max_age must be a non-negative integer`}),Be):n}),rge=k().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),W1=A({response_type:k().pipe(We([`code`])).optional(),request:k().optional(),request_uri:k().optional(),redirect_uri:A1.optional(),scope:k().optional(),state:k().optional(),client_id:k().min(1,`client_id is required`),prompt:tge.optional(),display:k().optional(),ui_locales:k().optional(),max_age:nge.optional(),acr_values:k().optional(),login_hint:k().optional(),id_token_hint:k().optional(),code_challenge:k().optional(),code_challenge_method:k().pipe(We([`S256`])).optional(),nonce:k().optional(),claims:qhe.optional(),dpop_jkt:rge.optional(),resource:Ee([H1,Pe(H1).min(1)]).optional()}).passthrough(),ige=W1.extend({redirect_uri:A1.optional(),claims:F1.optional()}),age=A({type:Ue(`authorization_code`),query:ige,sessionId:k(),userId:k(),referenceId:k().optional(),authTime:Me().optional(),resource:Pe(k()).optional()}).passthrough(),G1=A({redirect_uris:Pe(A1).min(1).optional(),scope:k().optional(),client_name:k().refine(e=>e.trim().length>0,`client_name cannot be empty`).optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Pe(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Pe(A1).min(1).optional(),backchannel_logout_uri:A1.optional(),backchannel_logout_session_required:He().optional(),token_endpoint_auth_method:k().trim().min(1).optional(),jwks:U1.optional(),jwks_uri:k().optional(),grant_types:Pe(k().trim().min(1)).min(1).optional(),response_types:Pe(We([`code`])).optional(),application_type:We([`web`,`native`]).optional(),subject_type:We([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:He().optional(),resources:Pe(H1).optional(),skip_consent:Le({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),oge=G1.omit({skip_consent:!0}).extend({client_id:k().refine(e=>e.trim().length>0,`client_id cannot be empty`),client_secret:k().optional(),client_secret_expires_at:Me().int().nonnegative().optional(),client_id_issued_at:Me().int().nonnegative().optional()}).loose(),K1=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],sge=new Set(K1);async function q1(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=H1.safeParse(t);return r.success?{ok:!0}:{ok:!1,reason:`resource identifier ${t} is invalid: ${r.error.issues[0]?.message??`not an absolute URI`}`}}async function cge(e,t){let n=await q1(e,t);if(!n.ok)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}const lge=e=>`${e}/oauth2/userinfo`;async function uge(e){if(!(e.headers.get(`content-type`)?.toLowerCase()??``).includes(`application/x-www-form-urlencoded`))return;let t;try{t=await e.clone().text()}catch{return}if(!t)return;let n=new URLSearchParams(t).getAll(`resource`).filter(e=>e.length>0);return n.length>0?n:void 0}function dge(e){if(e!=null){if(typeof e==`string`)return[e];if(Array.isArray(e)){let t=e.filter(e=>typeof e==`string`&&e.length>0);return t.length>0?t:void 0}}}async function J1(e,t,n,r=[]){if(n===void 0)return!0;let i=Array.isArray(n)?n:[n];if(i.length>64)return!1;let a=new Set(r),o=/* @__PURE__ */ new Set;for(let e of i)a.has(e)||o.add(e);return o.size===0||(await Promise.all(Array.from(o,n=>$1(e,t,n)))).every(Boolean)}async function Y1(e,t,n){let r=dge(n.resource),i=n.requestedScopes.includes(`openid`),a=lge(e.context.baseURL??``);if(!r)return{audienceClaim:void 0,accessTokenTtl:null,refreshTokenTtl:null,signingAlgorithm:null,signingKeyId:null,rawCustomClaims:{},dpopBoundAccessTokensRequired:!1,effectiveScopes:[...n.requestedScopes]};let o=[...new Set(r)],s=[];for(let n of o){if(n===a)continue;let r=await $1(e,t,n);if(r){if(r.disabled)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`});s.push(r)}else throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is not configured`})}let{value:c}=X1(t);c&&s.length>0&&await fge(e,t,n.clientId,s);let l=[...n.requestedScopes];for(let e of s){if(e.allowedScopes===null||e.allowedScopes===void 0)continue;let t=new Set(e.allowedScopes),n=l.filter(e=>t.has(e));if(n.length===0)throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`none of the requested scopes are allowed for resource ${e.identifier}`});l=n}let u=null,d=null;for(let e of s)e.accessTokenTtl!=null&&(u=u===null?e.accessTokenTtl:Math.min(u,e.accessTokenTtl)),e.refreshTokenTtl!=null&&(d=d===null?e.refreshTokenTtl:Math.min(d,e.refreshTokenTtl));let f=/* @__PURE__ */ new Set,p=/* @__PURE__ */ new Set;for(let e of s)e.signingAlgorithm&&f.add(e.signingAlgorithm),e.signingKeyId&&p.add(e.signingKeyId);if(f.size>1)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingAlgorithm pins; a single JWS signature cannot satisfy multiple algorithms`});if(p.size>1)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`multi-resource request has conflicting signingKeyId pins; a single JWS signature cannot satisfy multiple key ids`});let m=f.values().next().value??null,h=p.values().next().value??null,g={};for(let e of s)e.customClaims&&typeof e.customClaims==`object`&&Object.assign(g,e.customClaims);let _=s.some(e=>e.dpopBoundAccessTokensRequired===!0),v=i?[...o,a]:o,y=[...new Set(v)];return{audienceClaim:y.length===1?y[0]:y,accessTokenTtl:u,refreshTokenTtl:d,signingAlgorithm:m,signingKeyId:h,rawCustomClaims:g,dpopBoundAccessTokensRequired:_,effectiveScopes:l}}async function fge(e,t,n,r){if(r.length===0)return;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,a=await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n}]}),o=new Set(a?.map(e=>e.resourceId)??[]),s=r.filter(e=>!o.has(e.identifier));if(s.length>0)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`client ${n} is not linked to resource(s) ${s.map(e=>e.identifier).join(`, `)}`})}async function pge(e,t,n,r){if(r.length===0)return!1;let i=t.schema?.oauthClientResource?.modelName??`oauthClientResource`;return((await e.context.adapter.findMany({model:i,where:[{field:`clientId`,value:n},{field:`resourceId`,operator:`in`,value:r}],limit:1}))?.length??0)>0}async function mge(e,t,n){if(n.length===0)return{};let r=await e.context.adapter.findMany({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,operator:`in`,value:n}]}),i=new Map(r.map(e=>[e.identifier,e])),a={};for(let e of n){let t=i.get(e);t?.customClaims&&typeof t.customClaims==`object`&&Object.assign(a,t.customClaims)}return a}function X1(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}const Z1=/* @__PURE__ */ new Map;function Q1(e){e===void 0?Z1.clear():Z1.delete(e)}async function $1(e,t,n){if(await n0(e.context,t),t.cachedResources?.has(n)){let e=Z1.get(n);if(e)return Object.assign({},e)}let r=await e.context.adapter.findOne({model:t.schema?.oauthResource?.modelName??`oauthResource`,where:[{field:`identifier`,value:n}]});return r&&t.cachedResources?.has(n)&&Z1.set(n,Object.assign({},r)),r}function hge(e){return e.name??e.identifier}function gge(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function e0(e,t){return{identifier:e.identifier,name:hge(e),accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}function _ge(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=e0(e,n);return i}let r={updatedAt:n};return e.name!==void 0&&(r.name=e.name),e.accessTokenTtl!==void 0&&(r.accessTokenTtl=e.accessTokenTtl),e.refreshTokenTtl!==void 0&&(r.refreshTokenTtl=e.refreshTokenTtl),e.signingAlgorithm!==void 0&&(r.signingAlgorithm=e.signingAlgorithm),e.signingKeyId!==void 0&&(r.signingKeyId=e.signingKeyId),e.allowedScopes!==void 0&&(r.allowedScopes=e.allowedScopes),e.customClaims!==void 0&&(r.customClaims=e.customClaims),e.dpopBoundAccessTokensRequired!==void 0&&(r.dpopBoundAccessTokensRequired=e.dpopBoundAccessTokensRequired),e.disabled!==void 0&&(r.disabled=e.disabled),e.metadata!==void 0&&(r.metadata=e.metadata),r}const vge=/no such table|relation.*does not exist|table.*does(?: not|n'?t) exist|model.*(?:does not exist|was not found in the schema)/i;function yge(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=vge.test(r instanceof Error?r.message:String(r)),r=r instanceof Error?r.cause:void 0;n?e.logger.debug(`oauth-provider: oauthResource table not yet created; deferring resource seed to first access.`):e.logger.error("oauth-provider: could not seed `resources` at startup; retrying on first resource access.",t)}let t0=/* @__PURE__ */ new WeakMap;function bge(e,t){let n=e.adapter,r=t0.get(n);r||(r=/* @__PURE__ */ new WeakMap,t0.set(n,r));let i=r.get(t);if(i)return i;let a={completed:!1,promise:null};return r.set(t,a),a}async function xge(e,t){let n=gge(t);if(n.length===0)return;let r=t.resourceSeedMode??`insertOnly`,i=t.schema?.oauthResource?.modelName??`oauthResource`;for(let a of n){let n=await q1(t,a.identifier);if(!n.ok){f.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!sge.has(o.signingAlgorithm)){f.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${K1.join(`, `)}. Continuing without an algorithm override.`);let{signingAlgorithm:e,...t}=o;o=t}let s=[{field:`identifier`,value:o.identifier}],c=await e.adapter.findOne({model:i,where:s}),l=/* @__PURE__ */ new Date;if(!c)try{await e.adapter.create({model:i,data:e0(o,l)});continue}catch(t){if(!await e.adapter.findOne({model:i,where:s}).catch(()=>null))throw t}r!==`insertOnly`&&await e.adapter.update({model:i,where:s,update:_ge(o,r,l)})}}async function n0(e,t){let n=bge(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=xge(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Sge(e){let t=X1(e);f.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function r0(e){return e.headers?.get(`dpop`)??void 0}function i0(e,t){let{baseURL:n}=e.context,r=n.length;for(;r>0&&n[r-1]===`/`;)r--;let i=n.slice(0,r);if(!e.request||!i)return`${i}${t}`;let a=new URL(i).pathname.replace(/\/$/,``),o=new URL(e.request.url).pathname;return`${i}${o.startsWith(`${a}/`)?o.slice(a.length):t}`}const Cge=/* @__PURE__ */ new Set([`openid`,`profile`,`email`,`offline_access`]);function a0(e){return Cge.has(e)}function o0(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function s0(e,t,n,r){if(e.length===0)return;if(!t.includes(`client_credentials`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials_scopes requires the client_credentials grant`});if(n===`none`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`public clients cannot be assigned client_credentials scopes`});let i=new Set(r.scopes??[]),a=e.filter(e=>!i.has(e)||a0(e));if(a.length>0)throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`The following client_credentials scopes are invalid: ${a.join(`, `)}`})}function wge(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(R1))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function c0(e,t){let n={};for(let[r,i]of Object.entries(e??{}))i!==void 0&&(t&&r in t||(n[r]=i));return n}function Tge(e){let t=e.headers?.get(`authorization`),n=oZ(t),r=e.request?.method===`POST`?e.body?.access_token??void 0:void 0;if(n&&r)throw new E(`BAD_REQUEST`,{error_description:`Multiple access token transport methods are not allowed`,error:`invalid_request`});let i=n??(r?{scheme:`Bearer`,token:r}:void 0);return{authorization:i,token:i?.token}}async function Ege(e,t){let{authorization:n}=Tge(e);if(!n?.token)throw new E(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await A0(e,t,n.token);if(fZ(r)&&!e.request)throw new E(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await SZ({payload:r,authorization:n,proofJwt:r0(e),method:e.request?.method??`GET`,url:i0(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:rZ(e.context.internalAdapter)})}catch(e){throw xZ(e)?new E(`UNAUTHORIZED`,{error_description:e.message,error:e.code}):e}let a=r.scope?.split(` `);if(!a?.includes(`openid`))throw new E(`BAD_REQUEST`,{error_description:`Missing required scope`,error:`invalid_scope`});if(!r.sub)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let o=await e.context.internalAdapter.findUserById(r.sub);if(!o)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let s=wge(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||Ehe(t))?await n1(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await b1(o.id,l,t));let u=a?.length?await The(t,{ctx:e,opts:t,user:o,scopes:a,jwt:r,client:l??void 0,requestedClaims:i}):{},d=t.customUserInfoClaims&&a?.length?await t.customUserInfoClaims({user:o,scopes:a,jwt:r,requestedClaims:i}):{};return{...s,...c0(u,s),...c0(d),sub:s.sub}}const Dge=Object.fromEntries(z1.map(e=>[e,void 0]));function l0(e){return dZ(e)?`DPoP`:`Bearer`}async function Oge(e,t){let n=e.body.grant_type;if(!H$(t).includes(n))throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return Yge(e,t);case`client_credentials`:return Xge(e,t);case`refresh_token`:return Zge(e,t);default:{let r=xhe(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:kge(e,t,n)});throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function kge(e,t,n){return{getClient:n=>n1(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=_1(await v1(e,t,`${e.context.baseURL}${e.path??`/oauth2/token`}`));if(!i)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(r?.requireCredentials!==!1&&!a&&!o)throw new E(`BAD_REQUEST`,{error_description:`Missing required client credentials`,error:`invalid_client`});return{clientId:i,client:await h1(e,t,i,a,r?.scopes,o,n,s),method:s,confirmation:c}},issueTokens:r=>{if(!n)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`issueTokens requires a grant type; pass it to getOAuthProviderApi(ctx, opts, grantType).`,error:`server_error`});return S0(e,t,{...r,grantType:n})},hashToken:(e,n)=>s1(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>C0);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>C0);return i(e,t,n,r)}}}async function Age(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=J$(e.context).options,u=n?.id??r.clientId;return E$(e,{options:l,header:{typ:`at+jwt`},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:Q$(i),client_id:r.clientId,azp:r.clientId,scope:a.join(` `),sid:o?.sid,iss:l?.jwt?.issuer??e.context.baseURL,iat:s,exp:c,jti:JH(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function jge(e,t){let n;n=t===`EdDSA`?`SHA-512`:t.endsWith(`384`)?`SHA-384`:t.endsWith(`512`)?`SHA-512`:`SHA-256`;let r=new Uint8Array(await crypto.subtle.digest(n,new TextEncoder().encode(e)));return _P(r.slice(0,r.length/2))}async function Mge(e,t,n,r,i,a,o,s,c,l){let u=Math.floor(Date.now()/1e3),d=u+(t.idTokenExpiresIn??36e3),f=await b1(n.id,r,t),p=s==null?void 0:Math.floor(s.getTime()/1e3),m=j1(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:g1(r.metadata)}):void 0),h=t.disableJwtPlugin?void 0:J$(e.context).options,g=!t.disableJwtPlugin&&!h?.jwt?.sign?await T$(e,h):void 0,_=t.disableJwtPlugin?`HS256`:g?.alg??h?.jwks?.keyPairConfig?.alg,v=c?await jge(c,_):void 0,y=!!(r.enableEndSession||r.backchannelLogoutUri),b={...Dge,auth_time:p,acr:`0`,...m,at_hash:v,iss:h?.jwt?.issuer??e.context.baseURL,sub:f,aud:r.clientId,nonce:a,iat:u,exp:d,sid:y?o:void 0},x=j1(l);if(Object.assign(b,c0(x,b)),t.disableJwtPlugin&&!r.clientSecret)return;let S=t.disableJwtPlugin?await new iI(b).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await a1(e,t.storeClientSecret,r.clientSecret))):await E$(e,{options:h,payload:b,resolvedKey:g??void 0});if(S&&v&&h?.jwt?.sign){let e=gI(S);if(e.alg!==_)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`ID token signed with "${e.alg}" but at_hash was computed for "${_}". Ensure jwt.sign uses the algorithm declared in keyPairConfig.alg.`,error:`server_error`})}return S}async function u0(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function d0(e,t){if(e.prefix?.refreshToken){if(t.startsWith(e.prefix.refreshToken))t=t.replace(e.prefix.refreshToken,``);else throw new E(`BAD_REQUEST`,{error_description:`refresh token not found`,error:`invalid_token`})}return e.formatRefreshToken?.decrypt?e.formatRefreshToken?.decrypt(t):{token:t}}async function Nge(e,t,n,r,i,a,o,s,c,l,u,d){let f=a.iat??Math.floor(Date.now()/1e3),p=a?.exp??f+(t.accessTokenExpiresIn??3600),m=t.generateOpaqueAccessToken?await t.generateOpaqueAccessToken():JH(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await s1(t.storeTokens,m,`access_token`),clientId:r.clientId,sessionId:a?.sid,userId:n?.id,referenceId:s,authorizationCodeId:c,resources:o,refreshId:l,confirmation:u,requestedUserInfoClaims:d?.length?d:void 0,scopes:i,createdAt:/* @__PURE__ */ new Date(f*1e3),expiresAt:/* @__PURE__ */ new Date(p*1e3)}}),(t.prefix?.opaqueAccessToken??``)+m}async function f0(e,t,n){let r=await e.context.adapter.findMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]});r.length&&await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,operator:`in`,value:r.map(e=>e.id)}]}),await e.context.adapter.deleteMany({model:`oauthRefreshToken`,where:[{field:`clientId`,value:t},{field:`userId`,value:n}]})}async function Pge(e,t){let n=async n=>{try{await e.context.adapter.deleteMany({model:n,where:[{field:`authorizationCodeId`,value:t}]})}catch(t){e.context.logger.error(`authorization code replay cleanup failed`,t)}};await n(`oauthAccessToken`),await n(`oauthRefreshToken`)}async function p0(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=s.iat??Math.floor(Date.now()/1e3),m=s?.exp??p+(t.refreshTokenExpiresIn??2592e3),h=t.generateRefreshToken?await t.generateRefreshToken():JH(32,`A-Z`,`a-z`),g=s?.sid,_={token:await s1(t.storeTokens,h,`refresh_token`),clientId:a.clientId,sessionId:g,userId:n.id,referenceId:r,authorizationCodeId:i,authTime:l,confirmation:d,requestedUserInfoClaims:f?.length?f:void 0,scopes:o,resources:u,createdAt:/* @__PURE__ */ new Date(p*1e3),expiresAt:/* @__PURE__ */ new Date(m*1e3)};if(!c?.id)return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:_})).id,token:await u0(t,h,g)};let v=/* @__PURE__ */ new Date(p*1e3),y={revoked:v,rotatedAt:v},b=t.refreshTokenReuseInterval??0;if(b>0&&(y.rotationReplayExpiresAt=/* @__PURE__ */ new Date((p+b)*1e3)),!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:c.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:y}))throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});return{id:(await e.context.adapter.create({model:`oauthRefreshToken`,data:_})).id,token:await u0(t,h,g)}}async function m0(e,t,n){let r=await Y1(e,t,{resource:n.resources,clientId:n.clientId,requestedScopes:n.requestedScopes}),i=r.accessTokenTtl===null?n.scopeExpiresAtSeconds:n.iat+r.accessTokenTtl,a=t.refreshTokenExpiresIn??2592e3,o=r.refreshTokenTtl===null?a:Math.min(r.refreshTokenTtl,a);return{audienceClaim:r.audienceClaim,effectiveScopes:r.effectiveScopes,accessTokenExpiresAtSeconds:Math.min(n.scopeExpiresAtSeconds,i),refreshTokenExpiresAtSeconds:n.iat+o,refreshResources:n.refreshToken?.resources??n.originalResources??n.resources,signingAlgorithm:r.signingAlgorithm,signingKeyId:r.signingKeyId,resourceCustomClaims:r.rawCustomClaims,dpopBoundAccessTokensRequired:r.dpopBoundAccessTokensRequired}}function h0(e){throw new E(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Fge(e){let t=g1(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function g0(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=dZ(n.refreshToken?.confirmation),a=i??r,o=r0(e),s=Fge(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&h0(`DPoP proof header is required`);else try{return{jkt:(await yZ({proofJwt:o,method:`POST`,url:i0(e,e.path??`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:rZ(e.context.internalAdapter)})).jkt}}catch(e){throw aZ(e)&&h0(e.message),e}}function _0(e){return e?[...new Set(e)].sort():void 0}function v0(e,t){let n=_0(e),r=_0(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function y0(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Ige(e,t){return y0(e)===y0(t)}function Lge(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.jkt==`string`&&t[`x5t#S256`]===void 0||typeof t[`x5t#S256`]==`string`&&t.jkt===void 0}function Rge(e){return e===`Bearer`||e===`DPoP`}function zge(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.access_token==`string`&&typeof t.expires_in==`number`&&typeof t.expires_at==`number`&&Rge(t.token_type)&&typeof t.scope==`string`&&(t.refresh_token===void 0||typeof t.refresh_token==`string`)&&(t.id_token===void 0||typeof t.id_token==`string`)}function Bge(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.request;return!!n&&Array.isArray(n.effectiveScopes)&&n.effectiveScopes.every(e=>typeof e==`string`)&&(n.requestedResources===void 0||Array.isArray(n.requestedResources)&&n.requestedResources.every(e=>typeof e==`string`))&&(n.confirmation===void 0||Lge(n.confirmation))&&zge(t.response)}function b0(e){let t=_0(e.requestedResources);return{effectiveScopes:_0(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function Vge(e,t){return v0(e.effectiveScopes,t.effectiveScopes)&&v0(e.requestedResources,t.requestedResources)&&Ige(e.confirmation,t.confirmation)}async function Hge(e,t){return RW({key:e.context.secretConfig,data:JSON.stringify(t)})}async function Uge(e,t){let n=await zW({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(Bge(r))return r}function x0(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=/* @__PURE__ */ new Date}async function Wge(e,t,n,r,i){(t.refreshTokenReuseInterval??0)<=0||await e.context.adapter.update({model:`oauthRefreshToken`,where:[{field:`id`,value:n.id}],update:{rotationReplayResponse:await Hge(e,{request:r,response:i})}})}async function Gge(e,t,n){if(x0(t)&&t.rotationReplayResponse)try{let r=await Uge(e,t.rotationReplayResponse);return!r||!Vge(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function Kge(e,t,n){let r=Math.floor(Date.now()/1e3),i=await m0(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await g0(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return b0({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function qge(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function S0(e,t,n){let{client:r,scopes:i,user:a,grantType:o,referenceId:s,sessionId:c,nonce:l,refreshToken:u,authTime:d,verificationValue:f}=n,p=Math.floor(Date.now()/1e3),m=p+(a?t.accessTokenExpiresIn??3600:t.m2mAccessTokenExpiresIn??3600),h=t.scopeExpirations?i.map(e=>t.scopeExpirations?.[e]?C$(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await m0(e,t,{clientId:r.clientId,requestedScopes:i,resources:n.resources,originalResources:n.originalResources,refreshToken:n.refreshToken,iat:p,scopeExpiresAtSeconds:h}),_=g.audienceClaim,v=g.effectiveScopes,y=g.accessTokenExpiresAtSeconds,b=g.refreshTokenExpiresAtSeconds,x=a&&f1(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,ee=a&&v.includes(`openid`),C=g1(r.metadata),te=ee&&a?{...await whe(t,{ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,referenceId:s,sessionId:c,resources:n.resources,metadata:C}),...n.idTokenClaims??{}}:void 0,ne=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:C,verificationValue:f}):void 0,w=g.refreshResources,T=n.confirmation??await g0(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),re=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],ie=x&&a&&!S?await p0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,w,T,re):void 0,ae=S?await V1({ctx:e,opts:t,user:a,client:r,scopes:v,grantType:o,sessionId:c,resources:n.resources,referenceId:s,metadata:C,perRequestClaims:n.accessTokenClaims,resourcePolicyClaims:g.resourceCustomClaims}):void 0,[oe,se]=await Promise.all([S?Age(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:ae,confirmation:T}):Nge(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,ie?.id,T,re),ie||(x&&a?p0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,w,T,re):void 0)]),ce=ee?await Mge(e,t,a,r,v,l,c,d,oe,te):void 0,le={...ne,...n.tokenResponse??{},access_token:oe,expires_in:y-p,expires_at:y,token_type:l0(T),refresh_token:se?.token,scope:v.join(` `),id_token:ce};if(u?.id&&se?.id)try{await Wge(e,t,u,b0({effectiveScopes:v,requestedResources:n.resources,confirmation:T}),le)}catch(t){e.context.logger.error(`failed to store refresh token rotation replay`,t)}return e.json(le)}async function Jge(e,t,n,r,i,a){let o=await s1(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await Pge(e,o),new E(`BAD_REQUEST`,{error_description:`invalid code`,error:`invalid_grant`});let c;try{c=JSON.parse(s.value)}catch{throw new E(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`})}let l=age.safeParse(c);if(!l.success)throw new E(`BAD_REQUEST`,{error_description:`malformed verification value`,error:`invalid_grant`});let u=l.data;if(u.query.client_id!==r)throw new E(`BAD_REQUEST`,{error_description:`invalid client_id`,error:`invalid_grant`});let d=u.query.redirect_uri;if(d){if(!i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri is required`,error:`invalid_request`});if(d!==i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`})}else if(i)throw new E(`BAD_REQUEST`,{error_description:`redirect_uri mismatch`,error:`invalid_grant`});let f=Z$(u.resource)??Z$(u.query.resource),p=a??f;if(a&&f){let e=new Set(a),t=new Set(f);for(let n of e)if(!t.has(n))throw new E(`BAD_REQUEST`,{error_description:`requested resource not authorized`,error:`invalid_target`})}return{verificationValue:u,effectiveResources:p,authorizedResources:f,authorizationCodeId:o}}async function Yge(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=_1(await v1(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=Z$(l);if(!n)throw new E(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_request`});if(!o)throw new E(`BAD_REQUEST`,{error_description:`code is required`,error:`invalid_request`});let d=n&&r,f=n&&o&&s;if(!d&&!f&&!i)throw new E(`BAD_REQUEST`,{error_description:`Either code_verifier or client_secret is required`,error:`invalid_request`});let p=await h1(e,t,n,r,void 0,i,`authorization_code`,a),{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await Jge(e,t,o,n,c,u),v=m.query.scope?.split(` `);if(!v)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`verification scope unset`,error:`invalid_scope`});if(p1(p,v),D1(p,{scopes:(m.query?.scope)?.split(` `)||[],nonce:m.query?.nonce})){if(!f)throw new E(`BAD_REQUEST`,{error_description:`PKCE is required for this client`,error:`invalid_request`})}else if(!(f||d||i))throw new E(`BAD_REQUEST`,{error_description:`Either PKCE (code_verifier) or client authentication (client_secret or client_assertion) is required`,error:`invalid_request`});let y=!!m.query?.code_challenge,b=!!s;if(y||b){if(y&&!b)throw new E(`BAD_REQUEST`,{error_description:`code_verifier required because PKCE was used in authorization`,error:`invalid_request`});if(!y&&b)throw new E(`BAD_REQUEST`,{error_description:`code_verifier provided but PKCE was not used in authorization`,error:`invalid_request`});if((m.query?.code_challenge_method===`S256`?await JY(s):void 0)!==m.query?.code_challenge)throw new E(`BAD_REQUEST`,{error_description:`code verification failed`,error:`invalid_grant`})}if(!m.userId)throw new E(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let x=await e.context.internalAdapter.findUserById(m.userId);if(!x)throw new E(`BAD_REQUEST`,{error_description:`missing user, user may have been deleted`,error:`invalid_user`});let S=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:m.sessionId}]});if(!S||S.expiresAt</* @__PURE__ */ new Date)throw new E(`BAD_REQUEST`,{error_description:`session no longer exists`,error:`invalid_request`});let ee=m.authTime==null?Ahe(S):X$(m.authTime),C=I1(m.query.claims,B1(t));return S0(e,t,{client:p,scopes:m.query.scope?.split(` `)??[],user:x,grantType:`authorization_code`,referenceId:m.referenceId,sessionId:S.id,nonce:m.query?.nonce,authTime:ee,verificationValue:m,authorizationCodeId:_,requestedUserInfoClaims:C,resources:h,originalResources:g})}async function Xge(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=_1(await v1(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=Z$(s);if(!n)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await h1(e,t,n,r,void 0,i,`client_credentials`,a);if(l.tokenEndpointAuthMethod===`none`)throw new E(`BAD_REQUEST`,{error_description:`public clients cannot use the client_credentials grant`,error:`unauthorized_client`});let u=l.clientCredentialsScopes;if(!u?.length)throw new E(`BAD_REQUEST`,{error_description:`client has no authorized client_credentials scopes`,error:`unauthorized_client`});let d=o?.split(` `);if(d){let e=new Set(u),t=d.filter(t=>!e.has(t)||a0(t));if(t.length)throw new E(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],S0(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function Zge(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=_1(await v1(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=Z$(c);if(!n)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});if(!o)throw new E(`BAD_REQUEST`,{error_description:`Missing a required refresh_token for refresh_token grant`,error:`invalid_request`});let u=await h1(e,t,n,r,void 0,i,`refresh_token`,a),d=await d0(t,o),f=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await c1(t.storeTokens,d.token,`refresh_token`)}]});if(!f)throw new E(`BAD_REQUEST`,{error_description:`session not found`,error:`invalid_grant`});if(f.clientId!==n||f.expiresAt</* @__PURE__ */ new Date)throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`});if(l&&f.resources&&!l.every(e=>f.resources?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`requested resource invalid`,error:`invalid_target`});let p=f?.scopes,m=s?.split(` `);if(m){let e=new Set(p);for(let t of m)if(!e.has(t))throw new E(`BAD_REQUEST`,{error_description:`unable to issue scope ${t}`,error:`invalid_scope`})}if(p1(u,m??p),f.revoked){if(x0(f)){let n=await Gge(e,f,await Kge(e,t,{client:u,refreshToken:f,scopes:m??p,resources:l??f.resources}));if(n)return qge(e,n);throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await f0(e,n,f.userId),new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}let h=await e.context.internalAdapter.findUserById(f.userId);if(!h)throw new E(`BAD_REQUEST`,{error_description:`user not found`,error:`invalid_request`});let g=f.authTime==null?void 0:X$(f.authTime);return S0(e,t,{client:u,scopes:m??p,user:h,grantType:`refresh_token`,referenceId:f.referenceId,authorizationCodeId:f.authorizationCodeId,sessionId:f.sessionId,refreshToken:f,resources:l??f.resources,authTime:g,requestedUserInfoClaims:f.requestedUserInfoClaims})}var C0=/* @__PURE__ */ A$({introspectEndpoint:()=>M0,requireActiveAccessToken:()=>i_e,requireActiveAccessTokenWithClaims:()=>A0,validateAccessToken:()=>k0});const w0=`Invalid access token`,Qge=`Bearer error="invalid_token", error_description="${w0}"`;function T0(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function $ge(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function E0(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&pge(e,t,r,a)}async function e_e(e,t,n,r){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let i=J$(e.context),a=i.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await nI(n,dI(await zZ(n,{jwksFetch:a?.jwks?.remoteUrl?a.jwks.remoteUrl:async()=>(await i.endpoints.getJwks(e))?.response,jwksCacheKey:i})),{issuer:s})).payload}catch(e){if(e instanceof iP||e instanceof uP)return{active:!1};throw e instanceof TypeError||Y$(e)?new O(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`}):e}let l=c.aud;if(!await J1(e,t,l,[o])||!c.azp)return{active:!1};let u=await n1(e,t,c.azp);if(!u||u?.disabled||!await E0(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:$ge(l,o)}))return{active:!1};let d=c.sid;if(d){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:d}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return{active:!1}}return c.client_id=c.azp,c.active=!0,c.token_type=l0(c.cnf),c}async function t_e(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await c1(t.storeTokens,i,`access_token`)}]});if(!a)throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_token`});if(!a.expiresAt||a.expiresAt</* @__PURE__ */ new Date||a.revoked)return T0();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await n1(e,t,a.clientId),!s||s?.disabled||!await E0(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return T0();let c=a.sessionId??void 0;if(c){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:c}]});if(!t||t.expiresAt</* @__PURE__ */ new Date)return T0()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await J1(e,t,o,[u]))return T0();let d=o?[...o]:void 0;d?.length&&a.scopes?.includes(`openid`)&&(d.includes(u)||d.push(u));let f=o?.length?await mge(e,t,o):{},p=s?await V1({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:g1(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:f}):{},m=(t.disableJwtPlugin?void 0:J$(e.context))?.options;return{payload:{...p,active:!0,iss:m?.jwt?.issuer??e.context.baseURL,aud:Q$(d),client_id:a.clientId,azp:a.clientId,sub:l?.id,sid:c,exp:Math.floor(new Date(a.expiresAt).getTime()/1e3),iat:Math.floor(new Date(a.createdAt).getTime()/1e3),scope:a.scopes?.join(` `),token_type:l0(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function n_e(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await c1(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_token`});if(!i.clientId||i.clientId!==r||!i.expiresAt||i.expiresAt</* @__PURE__ */ new Date||i.revoked)return{active:!1};let a=i.sessionId??void 0;if(a){let t=await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:a}]});(!t||t.expiresAt</* @__PURE__ */ new Date)&&(a=void 0)}let o;return i.userId&&(o=await e.context.internalAdapter.findUserById(i?.userId)??void 0),{active:!0,client_id:r,iss:((t.disableJwtPlugin?void 0:J$(e.context))?.options)?.jwt?.issuer??e.context.baseURL,sub:o?.id,sid:a,exp:Math.floor(new Date(i.expiresAt).getTime()/1e3),iat:Math.floor(new Date(i.createdAt).getTime()/1e3),scope:i.scopes?.join(` `),token_type:l0(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function D0(){return new O(`UNAUTHORIZED`,{error_description:w0,error:`invalid_token`},{"WWW-Authenticate":Qge})}function r_e(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function O0(e,t,n,r){try{return{payload:await e_e(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(e)}try{return await t_e(e,t,n,r)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw D0()}async function k0(e,t,n,r){return(await O0(e,t,n,r)).payload}async function i_e(e,t,n,r){let i=await k0(e,t,n,r);if(i.active)return i;throw D0()}async function A0(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await O0(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw D0()}async function j0(e,t,n,r){if(!n.active||!n.sub)return n;let i=n.client_id??n.azp;if(!i)return n;let a=i===r.clientId?r:await n1(e,t,i);if(!a)return n;let o=await b1(n.sub,a,t);return{...n,sub:o}}async function M0(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=_1(await v1(e,t,`${e.context.baseURL}/oauth2/introspect`));if(!i||!a&&!o)throw new O(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(n&&typeof n==`string`&&(n=sZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await h1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return j0(e,t,await k0(e,t,n,c.clientId),c)}catch(e){if(e instanceof O){if(r===`access_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return j0(e,t,await n_e(e,t,(await d0(t,n)).token,c.clientId),c)}catch(e){if(e instanceof O){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof O){if(r_e(e))return{active:!1};throw e}throw e instanceof Error?(f.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(f.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}function N0(e){return e?.get(`sec-fetch-mode`)===`cors`}var a_e=/* @__PURE__ */ e({a:()=>V2,c:()=>f2,d:()=>n2,f:()=>e2,h:()=>t2,i:()=>s4,l:()=>u2,n:()=>t4,o:()=>R_e,r:()=>i4,s:()=>T2,t:()=>p4,u:()=>Q0});async function o_e(e,t,n){let r=await r4.get(),i=r?.query;if(!i)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let a=new URLSearchParams(i),o=a.get(`scope`)?.split(` `)??[],s=B1(t),c=I1(a.get(`claims`),s),l=a.get(`client_id`);if(!l)throw new E(`BAD_REQUEST`,{error_description:`client_id is required`,error:`invalid_client`});let u=e.body.scope?.split(` `);if(u&&!u.every(e=>o?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`Scope not originally requested`,error:`invalid_request`});let d=e.body.claims,f=d===void 0?c:I1(d,s);if(d!==void 0&&!f.every(e=>c.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`Claim not originally requested`,error:`invalid_request`});if(e.body.accept!==!0)return{redirect:!0,url:c4(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,p4(e,t))};let p=await zJ(e),m=y1(a.get(`prompt`)??``).has(`login`),h=m&&w1(p?.session.createdAt,r?.signedQueryIssuedAt);if(m&&!h)return e?.headers?.set(`accept`,`application/json`),e.query=C1(a),await n(e);let g=await x1(t,{user:p?.user,session:p?.session,scopes:u??o}),_=await S1(e,l,p?.user.id,g),v=Math.floor(Date.now()/1e3),y=a.getAll(`resource`),b={clientId:l,userId:p?.user.id,scopes:u??o,requestedUserInfoClaims:f,createdAt:/* @__PURE__ */ new Date(v*1e3),updatedAt:/* @__PURE__ */ new Date(v*1e3),resources:y.length?y:void 0,referenceId:g};if(_?.id?await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:_.id}],update:{resources:b.resources,scopes:b.scopes,requestedUserInfoClaims:b.requestedUserInfoClaims,updatedAt:/* @__PURE__ */ new Date(v*1e3)}}):await e.context.adapter.create({model:`oauthConsent`,data:{...b,scopes:b.scopes}}),u&&a.set(`scope`,b.scopes.join(` `)),d!==void 0){let e=Xhe(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let x=T1(a,`consent`);return h&&(x=T1(x,`login`),x=E1(x)),e.query=C1(x),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id})}async function s_e(e,t){if(e.body.selected===!0)return await c_e(e,t);if(e.body.created===!0)return await l_e(e,t);if(e.body.postLogin===!0)return await u_e(e,t);throw new E(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function c_e(e,t){let n=(await r4.get())?.query;if(!n)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});return e.headers?.set(`accept`,`application/json`),e.query=C1(T1(new URLSearchParams(n),`select_account`)),await t(e)}async function l_e(e,t){let n=(await r4.get())?.query;if(!n)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let r=new URLSearchParams(n);return e.headers?.set(`accept`,`application/json`),e.query=C1(T1(r,`create`)),await t(e)}async function u_e(e,t){let n=await r4.get(),r=n?.query;if(!r)throw new E(`BAD_REQUEST`,{error_description:`missing oauth query`,error:`invalid_request`});let i=new URLSearchParams(r);e.headers?.set(`accept`,`application/json`),e.query=C1(i);let a=await zJ(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id,isPostLoginContinuation:!0})}async function d_e(e,t,n,r){return E$(e,{options:t,payload:{...r,events:{"http://schemas.openid.net/event/backchannel-logout":{}}},header:{typ:`logout+jwt`},resolvedKey:n??void 0})}async function f_e(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await SH(e.context.adapter),o=[{field:`sessionId`,value:r}],[s,c]=await Promise.all([n.findMany({model:`oauthAccessToken`,where:o}),n.findMany({model:`oauthRefreshToken`,where:o})]),l=/* @__PURE__ */ new Set;for(let e of s)l.add(e.clientId);for(let e of c)l.add(e.clientId);if(l.size===0)return null;let u=await n.findMany({model:`oauthClient`,where:[{field:`clientId`,operator:`in`,value:Array.from(l)}]}),d=s.filter(e=>!e.revoked).map(e=>e.id),f=c.filter(e=>!e.revoked&&!e.scopes?.includes(`offline_access`)).map(e=>e.id),p=t.disableJwtPlugin?[]:u.filter(e=>!!e.backchannelLogoutUri&&!e.disabled);return{accessTokenIds:d,refreshTokenIds:f,sessionId:r,targets:(await Promise.all(p.map(async e=>{try{return{client:e,sub:await b1(i,e,t)}}catch(t){return a.warn(`back-channel logout: unable to resolve subject for client ${e.clientId}`,t),null}}))).filter(e=>e!==null)}}catch(e){return a.error(`back-channel logout planning failed`,e),null}}async function p_e(e,t){let n=/* @__PURE__ */ new Date,r=await SH(e.context.adapter),i=await Promise.allSettled([t.accessTokenIds.length>0?r.updateMany({model:`oauthAccessToken`,where:[{field:`id`,operator:`in`,value:t.accessTokenIds}],update:{revoked:n}}):Promise.resolve(),t.refreshTokenIds.length>0?r.updateMany({model:`oauthRefreshToken`,where:[{field:`id`,operator:`in`,value:t.refreshTokenIds}],update:{revoked:n}}):Promise.resolve()]);for(let t of i)t.status===`rejected`&&e.context.logger.error(`back-channel logout: token revocation update failed`,t.reason);t.targets.length>0&&await m_e(e,t)}async function m_e(e,t){let n=e.context.logger,r=J$(e.context)?.options,i=r?.jwt?.issuer??e.context.baseURL,a=Math.floor(Date.now()/1e3),o=a+120,s=r?.jwt?.sign?null:await T$(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=JH(32,`a-z`,`A-Z`,`0-9`),d=await d_e(e,r,s,{iss:i,aud:c.clientId,sub:l,sid:t.sessionId,iat:a,exp:o,jti:u}),f=await fetch(c.backchannelLogoutUri,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:new URLSearchParams({logout_token:d}),signal:AbortSignal.timeout(5e3),redirect:`error`});f.status!==200&&f.status!==204&&n.warn(`back-channel logout to client ${c.clientId} returned ${f.status}`)}catch(e){n.warn(`back-channel logout to client ${c.clientId} failed`,e)}}))}function P0(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&amp;`;case`<`:return`&lt;`;case`>`:return`&gt;`;case`"`:return`&quot;`;case`'`:return`&#39;`;default:return e}})}function F0(e){let t=e.request?.headers??e.headers;if(!t||N0(t))return!1;let n=t.get(`accept`)??``;return t.get(`sec-fetch-mode`)===`navigate`||n.includes(`text/html`)||n.includes(`application/xhtml+xml`)}function I0(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${P0(e)}</title></head><body>${t}</body></html>`,{status:n,headers:{"cache-control":`no-store`,"content-security-policy":`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,"content-type":`text/html; charset=utf-8`,pragma:`no-cache`,"x-content-type-options":`nosniff`}})}function L0(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function h_e(e){try{return new URL(L0(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function R0(e){return I0(`Confirm logout`,`<main><h1>Confirm logout</h1><p>Do you want to log out of this account?</p><form method="post" data-oidc-logout-confirmation action="${P0(L0(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function z0(e){return I0(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${P0(e)}`:`Logged out.`}</p></main>`)}function g_e(e,t){return I0(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${P0(e)}</p></main>`,t)}function B0(e,t,n,r){if(F0(e))return g_e(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new O(t,{error:n,error_description:r})}function V0(e){return`${e.context.authCookies.sessionToken.name}.oauth_logout_confirmation`}function H0(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:h_e(e),sameSite:`lax`}}async function U0(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+3e5};await e.setSignedCookie(V0(e),JSON.stringify(r),e.context.secret,H0(e,300))}async function __e(e){let t=await e.getSignedCookie(V0(e),e.context.secret);if(typeof t!=`string`)return null;try{let e=JSON.parse(t);if(typeof e!=`object`||!e)return null;let n=e;return n.sessionId!==void 0&&(typeof n.sessionId!=`string`||n.sessionId.length===0)||n.clientId!==void 0&&(typeof n.clientId!=`string`||n.clientId.length===0)||n.postLogoutRedirectUri!==void 0&&(typeof n.postLogoutRedirectUri!=`string`||n.postLogoutRedirectUri.length===0)||n.state!==void 0&&typeof n.state!=`string`||n.redirectInvalid!==void 0&&typeof n.redirectInvalid!=`boolean`||n.postLogoutRedirectUri!==void 0&&n.clientId===void 0||typeof n.expiresAt!=`number`||!Number.isFinite(n.expiresAt)?null:{...typeof n.sessionId==`string`?{sessionId:n.sessionId}:{},...typeof n.clientId==`string`?{clientId:n.clientId}:{},...typeof n.postLogoutRedirectUri==`string`?{postLogoutRedirectUri:n.postLogoutRedirectUri}:{},...typeof n.state==`string`?{state:n.state}:{},...typeof n.redirectInvalid==`boolean`?{redirectInvalid:n.redirectInvalid}:{},expiresAt:n.expiresAt}}catch{return null}}function W0(e){e.setCookie(V0(e),``,H0(e,0))}async function G0(e){let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(typeof t!=`string`||t.length===0)return null;try{let n=await e.context.internalAdapter.findSession(t);return n?{session:n.session}:null}catch(t){throw e.context.logger.error(`Failed to read the current logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the current session`})}}async function v_e(e,t){try{return await e.context.adapter.findOne({model:`session`,where:[{field:`id`,value:t}]})}catch(t){throw e.context.logger.error(`Failed to read the hinted logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to read the hinted session`})}}async function K0(e,t){if(typeof t.token!=`string`||t.token.length===0)throw new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`});try{await e.context.internalAdapter.deleteSession(t.token)}catch(t){throw e.context.logger.error(`Failed to delete the logout session`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to complete logout`})}}async function q0(e,t,n){try{return await n1(e,t,n)}catch(t){throw e.context.logger.error(`Failed to resolve the logout client`,t),new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Unable to resolve the logout client`})}}function J0(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function y_e(e){if(typeof e.aud==`string`&&e.aud.length>0)return e.aud;if(typeof e.azp==`string`&&e.azp.length>0)return e.azp;let t=J0(e.aud);return t.length===1?t[0]:null}async function b_e(e,t,n,r){if(r)return q0(e,t,r);let i;try{i=_I(n)}catch{return null}let a=y_e(i);return a?q0(e,t,a):null}async function x_e(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await a1(e,t.storeClientSecret,r.clientSecret),{payload:o}=await zF(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=J$(e.context).options,{payload:r}=await zF(n,dI(await zZ(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==p4(e,t)||!J0(i.aud).includes(r.clientId)||typeof i.sid!=`string`||i.sid.length===0||typeof i.sub!=`string`||i.sub.length===0?null:i}catch{return null}}function Y0(e,t,n){if(!t)return{invalid:!1};if(!e.postLogoutRedirectUris?.includes(t))return{invalid:!0};if(!n)return{uri:t,invalid:!1};try{let e=new URL(t);return e.searchParams.set(`state`,n),{uri:e.toString(),invalid:!1}}catch{return{invalid:!0}}}function X0(e,t){return t.post_logout_redirect_uri?Y0(e,t.post_logout_redirect_uri,t.state).invalid?{redirectInvalid:!0}:{clientId:e.clientId,postLogoutRedirectUri:t.post_logout_redirect_uri,...t.state===void 0?{}:{state:t.state}}:{}}async function S_e(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await q0(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:Y0(r,n.postLogoutRedirectUri,n.state)}async function Z0(e,t,n={}){return t?F0(e)?(await U0(e,t.session.id,n),R0(e)):B0(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):F0(e)?(await U0(e,void 0,n),R0(e)):B0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function C_e(e,t){let n=await __e(e),r=await G0(e);if(!n||n.expiresAt<=Date.now())return B0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await S_e(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?B0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await K0(e,r.session),lq(e),W0(e),i.uri?u4(e,i.uri):F0(e)?z0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(W0(e),i.uri?u4(e,i.uri):F0(e)?z0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):B0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function w_e(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await G0(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await q0(e,t,i.client_id);if(!r)return B0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return B0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return B0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=X0(r,i)}return Z0(e,a,n)}let o=await b_e(e,t,i.id_token_hint,i.client_id);if(!o)return a&&F0(e)?Z0(e,a):B0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return B0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return B0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await x_e(e,t,i.id_token_hint,o);if(!s)return a&&F0(e)?Z0(e,a,i.client_id?X0(o,i):{}):B0(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await v_e(e,c),u=a?.session.id===c;if(a&&!u)return Z0(e,a,X0(o,i));let d=Y0(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await K0(e,f),u&&lq(e),W0(e),d.uri?u4(e,d.uri):F0(e)?z0(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function T_e(e,t){return C_e(e,t)}function Q0(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:f4(t?.jwt?.issuer??r),authorization_endpoint:`${r}/oauth2/authorize`,token_endpoint:`${r}/oauth2/token`,jwks_uri:n?.jwt_disabled?void 0:t?.jwks?.remoteUrl??`${r}${t?.jwks?.jwksPath??`/jwks`}`,registration_endpoint:n?.dynamic_client_registration_supported?`${r}/oauth2/register`:void 0,introspection_endpoint:`${r}/oauth2/introspect`,revocation_endpoint:`${r}/oauth2/revoke`,response_types_supported:n?.grant_types_supported&&!n.grant_types_supported.includes(`authorization_code`)?[]:[`code`],response_modes_supported:[`query`],grant_types_supported:n?.grant_types_supported??[`authorization_code`,`client_credentials`,`refresh_token`],token_endpoint_auth_methods_supported:n?.token_endpoint_auth_methods_supported??[...n?.public_client_supported?[`none`]:[],`client_secret_basic`,`client_secret_post`,`private_key_jwt`],token_endpoint_auth_signing_alg_values_supported:[...iX],introspection_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],introspection_endpoint_auth_signing_alg_values_supported:[...iX],revocation_endpoint_auth_methods_supported:n?.endpoint_auth_methods_supported??[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],revocation_endpoint_auth_signing_alg_values_supported:[...iX],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...tZ],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function $0(e,t){let n=t.disableJwtPlugin?void 0:J$(e.context).options,r=V$(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:Q0(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:H$(t),token_endpoint_auth_methods_supported:W$(t,{includeNone:i}),endpoint_auth_methods_supported:W$(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function e2(e,t){let{clientDiscoveries:n,authMetadata:r}=$0(e,t);return K$(e,t,`oauth-authorization-server`,{...r1(n),...r})}function t2(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=$0(e,t),o={...a,claims_supported:B1(t),claims_parameter_supported:!0,userinfo_endpoint:`${n}/oauth2/userinfo`,subject_types_supported:t.pairwiseSecret?[`public`,`pairwise`]:[`public`],acr_values_supported:[`0`],id_token_signing_alg_values_supported:(()=>{if(t.disableJwtPlugin)return[`HS256`];let e=r?.jwks?.keyPairConfig?.alg??`EdDSA`,n=r?.jwks?.keyPairConfigs?.map(e=>e.alg)??[];return Array.from(/* @__PURE__ */ new Set([e,...n]))})(),end_session_endpoint:`${n}/oauth2/end-session`,request_parameter_supported:!1,request_uri_parameter_supported:!1,prompt_values_supported:[`login`,`consent`,`create`,`select_account`,`none`]};return K$(e,t,`openid-configuration`,{...r1(i),...o})}function n2(e,t){let n=new Headers(t);return n.has(`Cache-Control`)||n.set(`Cache-Control`,`public, max-age=15, stale-while-revalidate=15, stale-if-error=86400`),n.set(`Content-Type`,`application/json`),new Response(JSON.stringify(e),{status:200,headers:n})}function r2(e,t,n){let{redirectOnError:r,onValidationError:i,errorCodesByField:a,defaultError:o=`invalid_request`,...s}=t;if(!r)return X(e,{...s,onValidationError:async e=>{throw i&&await i(e),new O(`BAD_REQUEST`,{...i2(e.issues,a,o)})}},n);let c=r,{body:l,query:u,...d}=s;async function f(e,t,n){if(!n)return{ok:!0};let r=await n.safeParseAsync(e[t]??{});return r.success?(e[t]=r.data,{ok:!0}):(i&&await i({message:r.error.message,issues:r.error.issues}),{ok:!1,response:c({...i2(r.error.issues,a,o),ctx:e})})}return X(e,d,async e=>{let t=await f(e,`body`,l);if(!t.ok)return t.response;let r=await f(e,`query`,u);return r.ok?n(e):r.response})}function i2(e,t,n=`invalid_request`){let r=e[0];if(!r)return{error:n,error_description:`Invalid request.`};let i=r.path?.[0],a=typeof i==`string`?i:void 0,o=a?t?.[a]:void 0,s=r.path?.length?nee(r.path):``;return{error:E_e(r,o,n),error_description:O_e(r,s)}}function E_e(e,t,n){return typeof t==`string`?t:D_e(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function D_e(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function O_e(e,t){if(!t)return e.message;if(e.code===`invalid_type`)return e.message.endsWith(`received undefined`)?`${t} is required`:e.message.endsWith(`received array`)?`${t} must not appear more than once`:`${t} must be a ${e.expected??`valid value`}`;if(e.code===`invalid_value`){let n=e.values;if(Array.isArray(n)&&n.length>0)return`${t} must be one of: ${n.join(`, `)}`}return`${t}: ${e.message}`}const k_e=e=>zq(async t=>{if(!e.allowPublicClientPrelogin)throw new E(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await e1(n,t.context.secret))throw new E(`UNAUTHORIZED`,{error:`invalid_signature`})}),a2={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},A_e=[`Ed25519`],j_e=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function o2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function s2(e,t){return typeof e[t]==`string`&&e[t].length>0}function c2(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(a2,e)}function l2(e){return A_e.some(t=>t===e)}function M_e(e){switch(e.kty){case`RSA`:return s2(e,`n`)&&s2(e,`e`);case`EC`:return c2(e.crv)&&s2(e,`x`)&&s2(e,`y`);case`OKP`:return l2(e.crv)&&s2(e,`x`);default:return!1}}function N_e(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!iX.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return c2(e.crv)&&a2[e.crv]===e.alg;case`OKP`:return l2(e.crv)&&e.alg===`EdDSA`;default:return!1}}function u2(e){let t=o2(e)&&Array.isArray(e.keys)?e.keys:void 0;if(!t?.length)return{valid:!1,error:`jwks must be an RFC 7517 JWK Set object with a non-empty keys array`};for(let e of t){if(!o2(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||j_e.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!M_e(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!N_e(e))return{valid:!1,error:`jwks key alg must be supported for private_key_jwt and compatible with its key type and signing curve`}}return{valid:!0,jwks:{keys:t}}}function d2(e){let t=u2(e);if(!t.valid)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}const P_e=Object.freeze(Object.keys({clientId:!0,clientSecret:!0,clientDiscoveryId:!0,disabled:!0,scopes:!0,clientCredentialsScopes:!0,userId:!0,createdAt:!0,updatedAt:!0,expiresAt:!0,name:!0,uri:!0,icon:!0,contacts:!0,tos:!0,policy:!0,softwareId:!0,softwareVersion:!0,softwareStatement:!0,redirectUris:!0,postLogoutRedirectUris:!0,backchannelLogoutUri:!0,backchannelLogoutSessionRequired:!0,tokenEndpointAuthMethod:!0,grantTypes:!0,responseTypes:!0,applicationType:!0,jwks:!0,jwksUri:!0,requirePKCE:!0,dpopBoundAccessTokens:!0,skipConsent:!0,enableEndSession:!0,subjectType:!0,referenceId:!0,metadata:!0})),F_e=/* @__PURE__ */ `client_id.client_secret.client_secret_expires_at.scope.user_id.client_id_issued_at.client_name.client_uri.logo_uri.contacts.tos_uri.policy_uri.jwks.jwks_uri.software_id.software_version.software_statement.redirect_uris.post_logout_redirect_uris.backchannel_logout_uri.backchannel_logout_session_required.token_endpoint_auth_method.grant_types.response_types.application_type.disabled.skip_consent.enable_end_session.require_pkce.dpop_bound_access_tokens.subject_type.reference_id`.split(`.`),I_e=/* @__PURE__ */ new Set([...P_e,...F_e,`public`,`type`,`resources`,`client_credentials_scopes`]),L_e=/* @__PURE__ */ new Set(/* @__PURE__ */ `disabled.client_secret.client_secret_expires_at.client_id_issued_at.skip_consent.enable_end_session.require_pkce.reference_id.user_id.resources.clientSecret.clientDiscoveryId.skipConsent.enableEndSession.requirePKCE.referenceId.userId.clientId.applicationType.tokenEndpointAuthMethod.redirectUris.postLogoutRedirectUris.grantTypes.responseTypes.scopes.expiresAt.createdAt.updatedAt.softwareId.softwareVersion.softwareStatement.backchannelLogoutUri.backchannelLogoutSessionRequired.jwksUri.dpopBoundAccessTokens.subjectType`.split(`.`));function f2(e){return L_e.has(e)}function p2(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!I_e.has(e)))}async function m2(e,t,n,r,i){if(!t)throw new E(`UNAUTHORIZED`);if(!e.headers)throw new E(`BAD_REQUEST`);if(r===`configure-client-credentials-scopes`&&!n.clientPrivileges||n.clientPrivileges&&!await n.clientPrivileges({headers:e.headers,action:r,session:t.session,user:t.user,clientId:i}))throw new E(`UNAUTHORIZED`)}async function h2(e,t,n,r,i){if(!t)throw new E(`UNAUTHORIZED`);if(!e.headers)throw new E(`BAD_REQUEST`);if(n.resourcePrivileges&&!await n.resourcePrivileges({headers:e.headers,action:r,session:t.session,user:t.user,resourceId:i}))throw new E(`UNAUTHORIZED`)}var R_e=/* @__PURE__ */ A$({consumeClientAssertion:()=>T2,isPrivateHostname:()=>S2,verifyClientAssertion:()=>E2});const g2=/* @__PURE__ */ new WeakMap,_2=65536,z_e=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function v2(e,t,n,r){if(e.set(t,{jwks:n,fetchedAt:r}),e.size>500){let t=e.keys().next().value;t!==void 0&&e.delete(t)}}function y2(e){let t=g2.get(e);if(t)return t;let n=/* @__PURE__ */ new Map;return g2.set(e,n),n}function b2(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}const x2=[...iX];function S2(e){return!CY(e)}function B_e(e,t,n){let r=new URL(t);if(r.protocol!==`https:`)throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must use HTTPS`,error:`invalid_client`});if(r.username||r.password)throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not contain credentials`,error:`invalid_client`});if(t.includes(`#`))throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not include a fragment component`,error:`invalid_client`});if(S2(r.hostname))throw new O(`BAD_REQUEST`,{error_description:`jwks_uri must not point to a private or reserved address`,error:`invalid_client`});if(!(n&&r.origin===n)&&!e.context.isTrustedOrigin(r.href))throw new O(`BAD_REQUEST`,{error_description:`client jwks_uri is not trusted`,error:`invalid_client`})}function V_e(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function H_e(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>_2)throw await e.body?.cancel(),Error(`JWKS response exceeds 64 KiB`);if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;if(i+=t.byteLength,i>_2)throw await n.cancel(),Error(`JWKS response exceeds 64 KiB`);r.push(t)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)}async function C2(e,t=globalThis.fetch){let n=new AbortController,r=setTimeout(()=>n.abort(),5e3);try{let r=await t(e,{signal:n.signal,headers:{accept:`application/json`},redirect:`error`});if(r.redirected)throw Error(`JWKS fetch redirected`);if(r.status!==200)throw Error(`JWKS fetch returned ${r.status}`);let i=r.headers.get(`content-type`);if(!i||!z_e.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await H_e(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=u2(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function w2(){return new O(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function U_e(e,t,n){if(n.jwks)return JSON.parse(n.jwks);if(!n.jwksUri)throw new O(`BAD_REQUEST`,{error_description:`client has no JWKS configured`,error:`invalid_client`});let r=n.clientDiscoveryId?V$(t).find(e=>e.id===n.clientDiscoveryId):void 0;if(n.clientDiscoveryId&&!r?.fetchClientMetadataResource)throw new O(`BAD_REQUEST`,{error_description:`client discovery does not provide a metadata resource transport`,error:`invalid_client`});B_e(e,n.jwksUri,n.clientDiscoveryId?V_e(n.clientId):void 0);let i=Date.now(),a=b2(n),o=y2(t),s=o.get(a);if(s&&i-s.fetchedAt<3e5)return s.jwks;let c;try{c=await C2(n.jwksUri,r?.fetchClientMetadataResource)}catch{if(s&&i-s.fetchedAt<6e5)return s.jwks;throw w2()}if(!c.valid)throw w2();return v2(o,a,c.jwks,i),c.jwks}async function W_e(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?V$(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await C2(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(v2(y2(e),b2(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function T2(e,t,n){let{namespace:r,payload:i,expectedAudience:a}=n;if(!(Array.isArray(i.aud)?i.aud:i.aud==null?[]:[i.aud]).includes(a))throw new O(`BAD_REQUEST`,{error_description:`client assertion aud does not match the endpoint`,error:`invalid_client`});let o=t.assertionMaxLifetime??300,s=Math.floor(Date.now()/1e3);if(typeof i.exp!=`number`)throw new O(`BAD_REQUEST`,{error_description:`client assertion must include exp claim`,error:`invalid_client`});if(i.exp<=s)throw new O(`BAD_REQUEST`,{error_description:`client assertion has expired`,error:`invalid_client`});if(i.exp-s>o)throw new O(`BAD_REQUEST`,{error_description:`client assertion exp is too far in the future (max ${o}s)`,error:`invalid_client`});if(typeof i.iat==`number`&&s-i.iat>o)throw new O(`BAD_REQUEST`,{error_description:`client assertion iat is too far in the past (max ${o}s)`,error:`invalid_client`});if(typeof i.jti!=`string`||i.jti.length===0)throw new O(`BAD_REQUEST`,{error_description:`client assertion must include jti claim`,error:`invalid_client`});let c=await MU(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=xe(new Uint8Array(c).slice(0,24),e.context.options);try{await e.context.adapter.create({model:`oauthClientAssertion`,data:{id:l,expiresAt:/* @__PURE__ */ new Date(i.exp*1e3)},forceAllowId:!0})}catch(t){let n=!1;try{n=!!await e.context.adapter.findOne({model:`oauthClientAssertion`,where:[{field:`id`,value:l}]})}catch{}throw n?new O(`BAD_REQUEST`,{error_description:`client assertion jti has already been used`,error:`invalid_client`}):t}}async function E2(e,t,n,r,i,a,o){if(r!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)throw new O(`BAD_REQUEST`,{error_description:`unsupported client_assertion_type`,error:`invalid_client`});let s;try{s=gI(n)}catch{throw new O(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!s.alg||!x2.includes(s.alg))throw new O(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${s.alg}`,error:`invalid_client`});let c;try{c=_I(n)}catch{throw new O(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT payload`,error:`invalid_client`})}let l=c.sub??c.iss;if(!l)throw new O(`BAD_REQUEST`,{error_description:`client assertion must contain sub or iss claim identifying the client`,error:`invalid_client`});if(i&&i!==l)throw new O(`BAD_REQUEST`,{error_description:`client_id in body does not match assertion sub/iss`,error:`invalid_client`});let u=await n1(e,t,l);if(!u)throw new O(`BAD_REQUEST`,{error_description:`client not found`,error:`invalid_client`});if(u.disabled)throw new O(`BAD_REQUEST`,{error_description:`client is disabled`,error:`invalid_client`});if(u.tokenEndpointAuthMethod!==`private_key_jwt`)throw new O(`BAD_REQUEST`,{error_description:`client is not registered for private_key_jwt authentication`,error:`invalid_client`});o?.assertClient?.(u);let d=await U_e(e,t,u),f=a??`${e.context.baseURL}/oauth2/token`,p=p4(e,t),m=o?.endpointAudienceOnly?[f]:[.../* @__PURE__ */ new Set([f,p])],h={issuer:l,subject:l,audience:m,algorithms:x2},g;try{({payload:g}=await nI(n,dI(d),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await W_e(t,u);if(e)try{({payload:g}=await nI(n,dI(e),h))}catch{throw new O(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new O(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}else throw new O(`UNAUTHORIZED`,{error_description:`client assertion signature verification failed`,error:`invalid_client`})}let _=(Array.isArray(g.aud)?g.aud:[g.aud]).find(e=>typeof e==`string`&&m.includes(e));return await T2(e,t,{namespace:`private_key_jwt:${l}`,payload:g,expectedAudience:_}),{clientId:l,client:u}}function D2(e,t,n){return new O(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...Iq})}async function G_e(e,t,n){let r=e.headers,i;try{i=Dhe(r?.get(`authorization`))}catch{throw D2(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw D2(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);let a;try{a=await t.validateInitialAccessToken({initialAccessToken:i,headers:r,clientMetadata:n})}catch(e){throw e instanceof O?e:new O(`INTERNAL_SERVER_ERROR`,{error:`server_error`,error_description:`Initial access token validation failed`})}if(!a)throw D2(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}const K_e=[`authorization_code`];function O2(e){return[.../* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function k2(e){let t=e.grant_types??[...K_e];if(t.length>0)return t;throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`grant_types must contain at least one grant type`})}function q_e(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function A2(e,t){let n=new Set(H$(e)),r=t.filter(e=>n.has(e));if(r.length===0)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`no mutually supported grant_type among ${t.join(`, `)}`});return r}function j2(e,t=`web`){let n=k2(e);return{...e,token_endpoint_auth_method:e.token_endpoint_auth_method??`client_secret_basic`,application_type:e.application_type??(t===null?void 0:t),grant_types:n,response_types:q_e(e,n)}}function J_e(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function Y_e(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function M2(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(e=>Y_e(e)||P2(e))?`native`:`web`:n}function N2(e){throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function X_e(e){let t=/^http:\/\/([^/?#]*)/i.exec(e)?.[1];if(!t)return null;let n=t.slice(t.lastIndexOf(`@`)+1);if(n.startsWith(`[`)){let e=n.indexOf(`]`);return e<0?null:n.slice(0,e+1).toLowerCase()}return(n.split(`:`)[0]??``).toLowerCase()}function P2(e){let t=X_e(e);return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}function Z_e(e,t){let n=/* @__PURE__ */ new Set([...e.clientRegistrationDefaultResources??[],...e.clientRegistrationAllowedResources??[]]);for(let e of t)if(!n.has(e))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${e} is not allowed for client registration`})}async function Q_e(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[.../* @__PURE__ */ new Set([...r,...n])];for(let n of i){let r=await $1(e,t,n);if(!r)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} does not exist`});if(r.disabled)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`requested resource ${n} is disabled`})}return i}function $_e(e,t){let n;try{n=new URL(e)}catch{N2(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&N2(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&N2(`redirect URI localhost must not include trailing dots: ${e}`);let a=xY(n.hostname)||n.hostname===`localhost`;t===`web`?(!i||a)&&N2(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&N2(`native clients must not use https loopback redirect URIs: ${e}`):r?P2(e)||N2(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):k1(n)||N2(`native private-use redirect URI schemes must not use a reserved scheme; they must be an authority-free reverse-domain URI or a custom-scheme URI with a host and a path: ${e}`)}async function eve(e,t){let n=e.body;if(!t.allowDynamicClientRegistration)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client registration is disabled`});let r=await zJ(e),i=r?void 0:await G_e(e,t,n),a=!!i;if(!(r||a||t.allowUnauthenticatedClientRegistration))throw new E(`UNAUTHORIZED`,{error_description:`Authentication required for client registration`},{"WWW-Authenticate":`Bearer`,...Iq});let o=n.grant_types?.length?A2(t,n.grant_types):n.grant_types,s=n.grant_types?.includes(`authorization_code`)&&!o?.includes(`authorization_code`),c={...n,grant_types:o,response_types:s?void 0:n.response_types};if(!r&&!a&&c.grant_types?.includes(`client_credentials`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`client_credentials grant requires authenticated registration`});let l=Array.isArray(n.resources)?n.resources.filter(e=>typeof e==`string`&&e.length>0):[];r&&await m2(e,r,t,`create`);let u=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),d=await B2(e,t,{metadata:c,registrationSource:`dynamic`,userId:u?void 0:r?.session.userId,referenceId:u,requestedResources:l});return e.setStatus(201),e.json(d)}async function F2(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=j2(e,r?null:n?.registrationSource===`dynamic`?M2(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(W$(t,{includeNone:!0})).has(a))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported token_endpoint_auth_method ${a}`});if(i.dpop_bound_access_tokens!==void 0&&typeof i.dpop_bound_access_tokens!=`boolean`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`dpop_bound_access_tokens must be a boolean`});let o=i.grant_types??[],s=i.response_types,c=i.application_type;if(c!==void 0&&c!==`web`&&c!==`native`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`application_type must be web or native`});if(o.includes(`authorization_code`)&&(!i.redirect_uris||i.redirect_uris.length===0))throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:`Redirect URIs are required for authorization_code and implicit grant types`});for(let e of i.redirect_uris??[])$_e(e,c??(r?`native`:`web`));if(r)A2(t,o);else{let e=new Set(H$(t));for(let t of o)if(!e.has(t))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`unsupported grant_type ${t}`})}if(o.includes(`authorization_code`)&&!s?.includes(`code`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'authorization_code' grant type is used, 'code' response type must be included`});if(!o.includes(`authorization_code`)&&s?.includes(`code`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`When 'code' response type is used, 'authorization_code' grant type must be included`});if(i.subject_type!==void 0){if(i.subject_type!==`public`&&i.subject_type!==`pairwise`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`subject_type must be "public" or "pairwise"`});if(i.subject_type===`pairwise`&&!t.pairwiseSecret)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise subject_type requires server pairwiseSecret configuration`});if(i.subject_type===`pairwise`&&i.redirect_uris?.some(J_e))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients cannot use custom-scheme redirect URIs that include a host`});if(i.subject_type===`pairwise`&&i.redirect_uris&&i.redirect_uris.length>1&&new Set(i.redirect_uris.map(e=>new URL(e).host)).size>1)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host.`})}let l=(i?.scope)?.split(` `).filter(e=>e.length),u=n?.registrationSource===`dynamic`||n?.registrationSource===`clientMetadataDocument`,d=u?O2(t):t.scopes;if(d){let e=new Set(d);for(let t of l??[])if(!e?.has(t))throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`cannot request scope ${t}`})}if(u&&i.require_pkce===!1)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`pkce is required for registered clients.`});if(i.jwks||i.jwks_uri){if(i.jwks&&i.jwks_uri)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks and jwks_uri are mutually exclusive`});if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.protocol!==`https:`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must use HTTPS`});if(e.username||e.password)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not contain credentials`});if(i.jwks_uri.includes(`#`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not include a fragment component`});if(S2(e.hostname))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must not point to a private or reserved address`});if(n?.ctx&&!n.ctx.context.isTrustedOrigin(e.href)){let t=typeof i.client_id==`string`?i.client_id:void 0;if(!(r&&t!==void 0&&URL.canParse(t)&&new URL(t).origin===e.origin))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must belong to a trusted origin or the Client ID Metadata Document origin`})}}catch(e){throw e instanceof E?e:new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`jwks_uri must be a valid URL`})}i.jwks&&d2(i.jwks)}if(a===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`private_key_jwt requires either jwks or jwks_uri`});if(i.backchannel_logout_uri!==void 0){if(t.disableJwtPlugin)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri requires the jwt plugin (disableJwtPlugin must be false)`});let e;try{e=new URL(i.backchannel_logout_uri)}catch{throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must be an absolute URL`})}if(i.backchannel_logout_uri.includes(`#`))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not include a fragment component`});if(e.protocol!==`https:`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must use https`});if(e.username||e.password)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not contain credentials`});if(S2(e.hostname))throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`backchannel_logout_uri must not point to a private or reserved address`})}}const I2=Symbol(`client-registration-collision`);function L2(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[I2]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function R2(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=j2(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?M2(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=G$(t,i.token_endpoint_auth_method);await F2(i,t,{registrationSource:n.registrationSource,ctx:e});let c=n.clientId??t.generateClientId?.()??JH(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||JH(32,`a-z`,`A-Z`),u=l?await o1(e,t,l):void 0,d=n.registrationSource===`dynamic`&&!a&&t.clientRegistrationRequirePKCE===!1,f=i.require_pkce??(!d&&void 0),p=Math.floor(Date.now()/1e3),{resources:m,...h}=n.registrationSource===`dynamic`||n.registrationSource===`clientMetadataDocument`?{...i,scope:O2(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=W2({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?C$(t.clientRegistrationClientSecretExpiration,p):0:void 0,client_id:c,client_secret:u,client_id_issued_at:p,require_pkce:f,user_id:g?.referenceId?void 0:g?.userId,reference_id:g?.referenceId});_.clientCredentialsScopes=n.registrationSource===`clientMetadataDocument`?n.existingClient?.clientCredentialsScopes??[]:n.registrationSource===`managed`?n.clientCredentialsScopes??[]:[],_.clientDiscoveryId=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,n.registrationSource===`clientMetadataDocument`&&i.application_type===void 0&&(_.applicationType=null);let v=n.registrationSource===`clientMetadataDocument`?[]:n.requestedResources??[];n.registrationSource===`dynamic`&&Z_e(t,v);let y=await Q_e(e,t,v),b=t.schema?.oauthClient?.modelName??`oauthClient`,x=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,S=n.registrationSource===`clientMetadataDocument`?n.existingClient:void 0,ee=n.registrationSource===`clientMetadataDocument`?n.clientDiscoveryId:null,C=await wH(e.context.adapter,async()=>{let t=await SH(e.context.adapter),r,i=!1;if(S){let e=await t.update({model:b,where:[{field:`clientId`,value:c},{field:`clientDiscoveryId`,value:ee}],update:{..._,disabled:S.disabled,skipConsent:S.skipConsent,enableEndSession:S.enableEndSession,createdAt:S.createdAt,updatedAt:/* @__PURE__ */ new Date(p*1e3)}});if(!e)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=e}else{try{r=await t.create({model:b,data:{..._,createdAt:/* @__PURE__ */ new Date(p*1e3),updatedAt:/* @__PURE__ */ new Date(p*1e3)}})}catch(e){throw n.registrationSource===`clientMetadataDocument`&&H2(e)?{[I2]:!0,kind:`oauth-client-row-unique`,clientId:c,cause:e}:e}i=!0}let a=y.length===0?[]:await t.findMany({model:x,where:[{field:`clientId`,value:c}]}),o=new Set(a.map(e=>e.resourceId)),s=/* @__PURE__ */ new Date;for(let e of y)if(!o.has(e))try{await t.create({model:x,data:{clientId:c,resourceId:e,createdAt:s}})}catch(t){throw n.registrationSource===`clientMetadataDocument`&&H2(t)?{[I2]:!0,kind:`oauth-client-resource-link-unique`,clientId:c,resourceId:e,cause:t}:t}return{client:r,created:i}});return{client:C.client,clientSecret:l,resources:y,created:C.created}}function z2(e,t){let n=G2({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function tve(e,t){return{...z2(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function B2(e,t,n){return z2(await R2(e,t,n),t)}async function nve(e,t,n){return tve(await R2(e,t,n),t)}function rve(e,t){if(e&&e.clientDiscoveryId!==t)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client_id is already owned by a different registration source`})}async function V2(e,t,n){if(rve(n.existingClient,n.clientDiscoveryId),n.metadata.backchannel_logout_uri!==void 0||n.metadata.backchannel_logout_session_required!==void 0)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Documents cannot register a back-channel logout target`});if((n.metadata.token_endpoint_auth_method??`none`)!==`none`&&n.metadata.token_endpoint_auth_method!==`private_key_jwt`)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:`Client ID Metadata Document clients cannot use a shared secret`});let r={...n,metadata:{...n.metadata,token_endpoint_auth_method:n.metadata.token_endpoint_auth_method??`none`,client_secret:void 0,client_secret_expires_at:void 0},registrationSource:`clientMetadataDocument`};try{return await R2(e,t,r)}catch(i){if(!L2(i))throw i;let a=t.schema?.oauthClient?.modelName??`oauthClient`,o=t.schema?.oauthClientResource?.modelName??`oauthClientResource`,s=await e.context.adapter.findOne({model:a,where:[{field:`clientId`,value:n.clientId}]});if(i.clientId!==n.clientId||!s||s.clientDiscoveryId!==n.clientDiscoveryId||i.kind===`oauth-client-resource-link-unique`&&!await e.context.adapter.findOne({model:o,where:[{field:`clientId`,value:i.clientId},{field:`resourceId`,value:i.resourceId}]}))throw i.cause;try{return await R2(e,t,{...r,existingClient:s})}catch(e){throw L2(e)?e.cause:e}}}function H2(e){if(!e||typeof e!=`object`)return!1;let t=e,n=String(t.code??t.errno??``);return[`1062`,`11000`,`23505`,`ER_DUP_ENTRY`,`P2002`,`SQLITE_CONSTRAINT_UNIQUE`].includes(n)||t.name===`MongoServerError`&&t.code===11e3?!0:typeof t.message==`string`&&/(?:duplicate|unique constraint|unique key)/i.test(t.message)}async function U2(e,t,n){let r=await zJ(e);if(await m2(e,r,t,`create`),!r)throw new E(`UNAUTHORIZED`);let i=t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0,{client_credentials_scopes:a,...o}=e.body,s=n?.admin?o0(a??[]):[];s0(s,k2(o),o.token_endpoint_auth_method,t),s.length>0&&await m2(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await h2(e,r,t,`link`,n);let l={metadata:o,registrationSource:`managed`,userId:i?void 0:r.session.userId,referenceId:i,clientCredentialsScopes:s,...c?{requestedResources:c}:{}},u=n?.admin?await nve(e,t,l):await B2(e,t,l);return e.setStatus(201),e.json(u)}function W2(e){let{client_id:t,client_secret:n,client_secret_expires_at:r,scope:i,user_id:a,client_id_issued_at:o,client_name:s,client_uri:c,logo_uri:l,contacts:u,tos_uri:d,policy_uri:f,jwks:p,jwks_uri:m,software_id:h,software_version:g,software_statement:_,redirect_uris:v,post_logout_redirect_uris:y,backchannel_logout_uri:b,backchannel_logout_session_required:x,token_endpoint_auth_method:S,grant_types:ee,response_types:C,application_type:te,disabled:ne,skip_consent:w,enable_end_session:T,require_pkce:re,dpop_bound_access_tokens:ie,subject_type:ae,reference_id:oe,metadata:se}=e,ce=r?/* @__PURE__ */ new Date(Number(r)*1e3):void 0,le=o?/* @__PURE__ */ new Date(o*1e3):void 0,ue=i?.split(` `),de=p2(se??{}),fe=de&&Object.keys(de).length?JSON.stringify(de):void 0;return{clientId:t,clientSecret:n,disabled:ne,scopes:ue,userId:a,createdAt:le,expiresAt:ce,name:s,uri:c,icon:l,contacts:u,tos:d,policy:f,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:ee,responseTypes:C,jwks:p?JSON.stringify(p):void 0,jwksUri:m,applicationType:te,skipConsent:w,enableEndSession:T,requirePKCE:re,dpopBoundAccessTokens:ie,subjectType:ae,referenceId:oe,metadata:fe}}function G2(e){let{clientId:t,clientSecret:n,disabled:r,scopes:i,userId:a,createdAt:o,updatedAt:s,expiresAt:c,name:l,uri:u,icon:d,contacts:f,tos:p,policy:m,softwareId:h,softwareVersion:g,softwareStatement:_,redirectUris:v,postLogoutRedirectUris:y,backchannelLogoutUri:b,backchannelLogoutSessionRequired:x,tokenEndpointAuthMethod:S,grantTypes:ee,responseTypes:C,applicationType:te,jwks:ne,jwksUri:w,skipConsent:T,enableEndSession:re,requirePKCE:ie,dpopBoundAccessTokens:ae,subjectType:oe,referenceId:se,metadata:ce}=e,le=c?Math.round(new Date(c).getTime()/1e3):void 0,ue=o?Math.round(new Date(o).getTime()/1e3):void 0,de=i?.join(` `);return{...p2(g1(ce)),client_id:t,client_secret:n??void 0,client_secret_expires_at:n?le??0:void 0,scope:de??void 0,user_id:a??void 0,client_id_issued_at:ue??void 0,client_name:l??void 0,client_uri:u??void 0,logo_uri:d??void 0,contacts:f??void 0,tos_uri:p??void 0,policy_uri:m??void 0,jwks:ne?JSON.parse(ne):void 0,jwks_uri:w??void 0,software_id:h??void 0,software_version:g??void 0,software_statement:_??void 0,redirect_uris:v??[],post_logout_redirect_uris:y??void 0,backchannel_logout_uri:b??void 0,backchannel_logout_session_required:x??void 0,token_endpoint_auth_method:S??void 0,grant_types:ee??void 0,response_types:C??void 0,application_type:te??void 0,disabled:r??void 0,skip_consent:T??void 0,enable_end_session:re??void 0,require_pkce:ie??void 0,dpop_bound_access_tokens:ae??void 0,subject_type:oe??void 0,reference_id:se??void 0}}async function ive(e,t){let n=await zJ(e);if(await m2(e,n,t,`read`,e.query.client_id),!n)throw new E(`UNAUTHORIZED`);let r=await n1(e,t,e.query.client_id);if(!r)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(r.userId){if(r.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(r.referenceId&&t.clientReference){if(r.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);let i=G2(r);return i.client_secret=void 0,i}async function K2(e,t,n){let r=await n1(e,t,n);if(!r||r.disabled)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return G2({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function ave(e,t){let n=await zJ(e);if(await m2(e,n,t,`list`),!n)throw new E(`UNAUTHORIZED`);let r=await t.clientReference?.(n);if(r)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`referenceId`,value:r}]}).then(e=>e?e.map(e=>{let t=G2(e);return t.client_secret=void 0,t}):null);if(n.user.id)return await e.context.adapter.findMany({model:`oauthClient`,where:[{field:`userId`,value:n.user.id}]}).then(e=>e?e.map(e=>{let t=G2(e);return t.client_secret=void 0,t}):null);throw new E(`BAD_REQUEST`,{message:`either user_id or reference_id must be provided`})}async function ove(e,t){let n=await zJ(e);if(await m2(e,n,t,`delete`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;t1(t,r);let i=await n1(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthClient`,where:[{field:`clientId`,value:r}]})}async function q2(e,t,n){let r=await zJ(e);if(await m2(e,r,t,`update`,e.body.client_id),!r)throw new E(`UNAUTHORIZED`);let i=e.body.client_id;t1(t,i);let a=await n1(e,t,i);if(!a)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let{client_credentials_scopes:o,...s}=e.body.update,c=a.userId?a.userId===r.user.id:a.referenceId&&t.clientReference?a.referenceId===await t.clientReference(r):!1,l=!c&&n?.admin&&o!==void 0&&Object.keys(s).length===0;if(!c&&!l)throw new E(`UNAUTHORIZED`);if(l&&await m2(e,r,t,`configure-client-credentials-scopes`,i),Object.keys(s).length===0&&o===void 0){let e=G2(a);return e.client_secret=void 0,n?.admin?{...e,client_credentials_scopes:[...a.clientCredentialsScopes??[]]}:e}let u=s.grant_types??a.grantTypes??[],d=s.token_endpoint_auth_method??a.tokenEndpointAuthMethod,f=o===void 0?void 0:o0(o);f!==void 0&&(s0(f,u,d,t),f.length>0&&!l&&await m2(e,r,t,`configure-client-credentials-scopes`,i)),await F2({...G2(a),...s},t,{ctx:e});let p={...W2(s)};!u.includes(`client_credentials`)||d===`none`?p.clientCredentialsScopes=[]:f!==void 0&&(p.clientCredentialsScopes=f),s.token_endpoint_auth_method&&(s.token_endpoint_auth_method===`private_key_jwt`?p.clientSecret=null:(p.jwks=null,p.jwksUri=null,p.clientSecret||=await o1(e,t,t.generateClientSecret?.()||JH(32,`a-z`,`A-Z`))));let m=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:i}],update:{...p,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!m)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});let h=G2(m);return h.client_secret=void 0,n?.admin?{...h,client_credentials_scopes:[...m.clientCredentialsScopes??[]]}:h}async function sve(e,t){let n=await zJ(e);if(await m2(e,n,t,`rotate`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;t1(t,r);let i=await n1(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});if(i.userId){if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`)}else if(i.referenceId&&t.clientReference){if(i.referenceId!==await t.clientReference(n))throw new E(`UNAUTHORIZED`)}else throw new E(`UNAUTHORIZED`);if(i.tokenEndpointAuthMethod===`none`||!i.clientSecret)throw new E(`BAD_REQUEST`,{error_description:`secret rotation is only available for clients using client_secret authentication`,error:`invalid_client`});let a=t.generateClientSecret?.()||JH(32,`a-z`,`A-Z`),o=a?await o1(e,t,a):void 0,s=await e.context.adapter.update({model:`oauthClient`,where:[{field:`clientId`,value:r}],update:{clientSecret:o,updatedAt:/* @__PURE__ */ new Date(Math.floor(Date.now()/1e3)*1e3)}});if(!s)throw new E(`INTERNAL_SERVER_ERROR`,{error_description:`unable to update client`,error:`invalid_client`});return G2({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}async function cve(e,t){if(!t.allowClientKeyRotation)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client key rotation is disabled`});let{body:n}=e;d2(n.jwks);let{client:r}=await E2(e,t,n.client_assertion,n.client_assertion_type,void 0,i0({context:e.context,request:void 0},`/oauth2/client/rotate-keys`),{endpointAudienceOnly:!0,assertClient:e=>lve(t,e)});if(!await e.context.adapter.incrementOne({model:`oauthClient`,where:[{field:`clientId`,value:r.clientId},{field:`jwks`,value:r.jwks}],increment:{},set:{jwks:JSON.stringify(n.jwks),updatedAt:/* @__PURE__ */ new Date}}))throw new E(`CONFLICT`,{error:`invalid_request`,error_description:`client keys changed while rotating; retry with a fresh client assertion`});return{client_id:r.clientId,jwks:n.jwks}}function lve(e,t){if(t1(e,t.clientId),t.clientDiscoveryId||t.jwksUri||!t.jwks)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client keys are not stored inline; rotate them where the client publishes them`})}const J2=k().trim().min(1),Y2=Pe(k().trim().min(1)).min(1),uve=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:A({redirect_uris:Pe(A1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Pe(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Pe(A1).min(1).optional(),backchannel_logout_uri:A1.optional(),backchannel_logout_session_required:He().optional(),token_endpoint_auth_method:J2.optional(),application_type:We([`web`,`native`]).optional(),jwks:U1.optional(),jwks_uri:k().optional(),grant_types:Y2.optional(),client_credentials_scopes:Pe(k().trim().min(1)).optional(),resources:Pe(H1).optional(),response_types:Pe(We([`code`])).optional(),client_secret_expires_at:Ee([k(),Me()]).optional().default(0),skip_consent:He().optional(),enable_end_session:He().optional(),require_pkce:He().optional(),dpop_bound_access_tokens:He().optional(),subject_type:We([`public`,`pairwise`]).optional(),metadata:Ne(k(),Je()).optional()}),metadata:{noStore:!0,SERVER_ONLY:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},client_credentials_scopes:{type:`array`,items:{type:`string`},description:`Server-authorized scope ceiling for client_credentials tokens`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},require_pkce:{type:`boolean`,description:`Whether the client requires PKCE`,default:!0},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>U2(t,e,{admin:!0})),dve=e=>X(`/oauth2/create-client`,{method:`POST`,use:[VJ],body:A({redirect_uris:Pe(A1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Pe(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Pe(A1).min(1).optional(),backchannel_logout_uri:A1.optional(),backchannel_logout_session_required:He().optional(),token_endpoint_auth_method:J2.optional(),application_type:We([`web`,`native`]).optional(),jwks:U1.optional(),jwks_uri:k().optional(),grant_types:Y2.optional(),response_types:Pe(We([`code`])).optional(),dpop_bound_access_tokens:He().optional()}),metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`URI of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URI for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final server-owned resources linked to the client`},disabled:{type:`boolean`,description:`Whether the client is disabled`},metadata:{type:`object`,additionalProperties:!0,nullable:!0,description:`Additional metadata for the application`}},required:[`client_id`]}}}}}}}},async t=>U2(t,e)),fve=e=>X(`/oauth2/get-client`,{method:`GET`,use:[VJ],query:A({client_id:k()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>ive(t,e)),pve=e=>X(`/oauth2/public-client`,{method:`GET`,use:[VJ],query:A({client_id:k()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return K2(t,e,n)}),mve=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[k_e(e)],body:A({client_id:k(),oauth_query:k().optional()}),metadata:{openapi:{description:`Gets publicly available client fields (prior to login)`}}},async t=>{let n=t.body.client_id;return K2(t,e,n)}),hve=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[VJ],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>ave(t,e)),gve=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:A({client_id:k(),update:A({redirect_uris:Pe(A1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Pe(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Pe(A1).min(1).optional(),backchannel_logout_uri:A1.optional(),backchannel_logout_session_required:He().optional(),application_type:We([`web`,`native`]).optional(),grant_types:Y2.optional(),client_credentials_scopes:Pe(k().trim().min(1)).optional(),response_types:Pe(We([`code`])).optional(),client_secret_expires_at:Ee([k(),Me()]).optional(),skip_consent:He().optional(),enable_end_session:He().optional(),disabled:He().optional(),dpop_bound_access_tokens:He().optional(),metadata:Ne(k(),Je()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>q2(t,e,{admin:!0})),_ve=e=>X(`/oauth2/update-client`,{method:`POST`,use:[VJ],body:A({client_id:k(),update:A({redirect_uris:Pe(A1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Pe(k().min(1)).min(1).optional(),tos_uri:k().optional(),policy_uri:k().optional(),software_id:k().optional(),software_version:k().optional(),software_statement:k().optional(),post_logout_redirect_uris:Pe(A1).min(1).optional(),backchannel_logout_uri:A1.optional(),backchannel_logout_session_required:He().optional(),application_type:We([`web`,`native`]).optional(),grant_types:Y2.optional(),response_types:Pe(We([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>q2(t,e)),vve=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[VJ],body:A({client_id:k()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>sve(t,e)),yve=e=>r2(`/oauth2/client/rotate-keys`,{method:`POST`,body:A({client_assertion:k(),client_assertion_type:k(),jwks:U1}),errorCodesByField:{client_assertion:`invalid_client`,client_assertion_type:`invalid_client`,jwks:`invalid_client_metadata`},metadata:{noStore:!0,openapi:{description:`Replaces the signing keys of a private_key_jwt client. The request is authenticated by a client assertion signed with one of the client's current keys and addressed to this endpoint. Keys left out of the new set stop verifying at once.`}}},async t=>cve(t,e)),bve=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[VJ],body:A({client_id:k()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>ove(t,e));async function X2(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function xve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.query;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await X2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);return i}async function Sve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function Cve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await X2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);await e.context.adapter.delete({model:`oauthConsent`,where:[{field:`id`,value:r}]})}async function wve(e,t){let n=await zJ(e);if(!n)throw new E(`UNAUTHORIZED`);let{id:r}=e.body;if(!r)throw new E(`NOT_FOUND`,{error_description:`missing id parameter`,error:`not_found`});let i=await X2(e,t,r);if(!i)throw new E(`NOT_FOUND`,{error_description:`no consent`,error:`not_found`});if(i.userId!==n.user.id)throw new E(`UNAUTHORIZED`);let a=await n1(e,t,i.clientId);if(!a)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});let o=a?.scopes??t.scopes??[],s=e.body.update,c=s.scopes;if(c&&!c.every(e=>o?.includes(e)))throw new E(`BAD_REQUEST`,{error_description:`unable to provide scopes to ${a?.referenceId??a?.userId}`,error:`invalid_request`});let l=Math.floor(Date.now()/1e3);return await e.context.adapter.update({model:`oauthConsent`,where:[{field:`id`,value:r}],update:{...s,updatedAt:/* @__PURE__ */ new Date(l*1e3)}})}const Tve=e=>X(`/oauth2/get-consent`,{method:`GET`,query:A({id:k()}),use:[VJ],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>xve(t,e)),Eve=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[VJ],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Sve(t,e)),Dve=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[VJ],body:A({id:k(),update:A({scopes:Pe(k())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>wve(t,e)),Ove=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[VJ],body:A({id:k()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>Cve(t,e)),Z2=e=>e.schema?.oauthResource?.modelName??`oauthResource`,Q2=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,kve=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function $2(e){try{return decodeURIComponent(e)}catch{return e}}function Ave(e,t){return{identifier:e.identifier,name:e.name??e.identifier,accessTokenTtl:e.accessTokenTtl??null,refreshTokenTtl:e.refreshTokenTtl??null,signingAlgorithm:e.signingAlgorithm??null,signingKeyId:e.signingKeyId??null,allowedScopes:e.allowedScopes??null,customClaims:e.customClaims??null,dpopBoundAccessTokensRequired:e.dpopBoundAccessTokensRequired??!1,disabled:e.disabled??!1,policyVersion:1,metadata:e.metadata??null,createdAt:t,updatedAt:t}}async function jve(e,t){await h2(e,await zJ(e),t,`create`);let n=e.body;if(!n?.identifier)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await cge(t,n.identifier);let r=/* @__PURE__ */ new Date,i;try{i=await e.context.adapter.create({model:Z2(t),data:Ave(n,r)})}catch(e){let t=e instanceof Error?e.message:String(e);throw/unique|duplicate|UNIQUE/i.test(t)?new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} already exists`}):e}if(!i)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`resource ${n.identifier} could not be created`});return Q1(i.identifier),e.json(i,{status:201})}async function Mve(e,t){await h2(e,await zJ(e),t,`list`);let n=await e.context.adapter.findMany({model:Z2(t)});return e.json(n??[])}async function Nve(e,t){let n=$2(e.params.identifier);await h2(e,await zJ(e),t,`read`,n);let r=await e.context.adapter.findOne({model:Z2(t),where:[{field:`identifier`,value:n}]});if(!r)throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(r)}async function Pve(e,t){let n=$2(e.params.identifier);if(await h2(e,await zJ(e),t,`update`,n),!await e.context.adapter.findOne({model:Z2(t),where:[{field:`identifier`,value:n}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});let r={updatedAt:/* @__PURE__ */ new Date};for(let t of[`name`,`accessTokenTtl`,`refreshTokenTtl`,`signingAlgorithm`,`signingKeyId`,`allowedScopes`,`customClaims`,`dpopBoundAccessTokensRequired`,`disabled`,`metadata`])Object.prototype.hasOwnProperty.call(e.body,t)&&(r[t]=e.body[t]);await e.context.adapter.update({model:Z2(t),where:[{field:`identifier`,value:n}],update:r}),Q1(n);let i=await e.context.adapter.findOne({model:Z2(t),where:[{field:`identifier`,value:n}]});if(!i)throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return e.json(i)}async function Fve(e,t){let n=$2(e.params.identifier);if(await h2(e,await zJ(e),t,`delete`,n),!await e.context.adapter.findOne({model:Z2(t),where:[{field:`identifier`,value:n}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${n} not found`});return await e.context.adapter.delete({model:Z2(t),where:[{field:`identifier`,value:n}]}),Q1(n),e.json({deleted:!0})}async function Ive(e,t){let n=await zJ(e),r=$2(e.params.identifier),i=$2(e.params.client_id);if(await h2(e,n,t,`link`,r),!await e.context.adapter.findOne({model:Z2(t),where:[{field:`identifier`,value:r}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`resource ${r} not found`});if(!await e.context.adapter.findOne({model:kve(t),where:[{field:`clientId`,value:i}]}))throw new E(`NOT_FOUND`,{error:`not_found`,error_description:`client ${i} not found`});try{await e.context.adapter.create({model:Q2(t),data:{clientId:i,resourceId:r,createdAt:/* @__PURE__ */ new Date}})}catch(t){let n=t instanceof Error?t.message:String(t);if(/unique|duplicate|UNIQUE/i.test(n))return e.json({linked:!0,alreadyLinked:!0});throw t}return e.json({linked:!0})}async function Lve(e,t){let n=await zJ(e),r=$2(e.params.identifier),i=$2(e.params.client_id);return await h2(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:Q2(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}const e4=A({identifier:k().min(1).optional(),name:k().optional(),accessTokenTtl:Me().int().positive().nullable().optional(),refreshTokenTtl:Me().int().positive().nullable().optional(),signingAlgorithm:We(K1).nullable().optional(),signingKeyId:k().nullable().optional(),allowedScopes:Pe(k()).nullable().optional(),customClaims:Ne(k(),Je()).nullable().optional(),dpopBoundAccessTokensRequired:He().optional(),disabled:He().optional(),metadata:Ne(k(),Je()).nullable().optional()}),Rve=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:e4.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>jve(t,e)),zve=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Mve(t,e)),Bve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Nve(t,e)),Vve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:e4,metadata:{SERVER_ONLY:!0}},async t=>Pve(t,e)),Hve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Fve(t,e)),Uve=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>Ive(t,e)),Wve=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Lve(t,e));async function Gve(e,t,n){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let r=J$(e.context),i=r.options,a;try{a=(await nI(n,dI(await zZ(n,{jwksFetch:i?.jwks?.remoteUrl?i.jwks.remoteUrl:async()=>(await r.endpoints.getJwks(e))?.response,jwksCacheKey:r})),{issuer:i?.jwt?.issuer??e.context.baseURL})).payload}catch(e){if(e instanceof iP||e instanceof uP)return null;throw e instanceof TypeError||Y$(e)?new O(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`}):e}let o=`${e.context.baseURL}/oauth2/userinfo`;if(!a.azp||!await J1(e,t,a.aud,[o]))return null;throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are self-contained and cannot be revoked server-side`,error:`unsupported_token_type`})}async function Kve(e,t,n,r){let i=n;if(t.prefix?.opaqueAccessToken){if(i.startsWith(t.prefix.opaqueAccessToken))i=i.replace(t.prefix.opaqueAccessToken,``);else throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`})}let a=await e.context.adapter.findOne({model:`oauthAccessToken`,where:[{field:`token`,value:await c1(t.storeTokens,i,`access_token`)}]});if(!a)throw new O(`BAD_REQUEST`,{error_description:`opaque access token not found`,error:`invalid_request`});if(!a.clientId||a.clientId!==r)return null;a.id?await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`id`,value:a.id}]}):await e.context.adapter.delete({model:`oauthAccessToken`,where:[{field:`token`,value:a.token}]})}async function qve(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await c1(t.storeTokens,n,`refresh_token`)}]});if(!i)throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`});if(i.revoked)throw await f0(e,r,i.userId),new O(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});if(!i.clientId||i.clientId!==r)return null;let a=Math.floor(Date.now()/1e3);if(!await e.context.adapter.incrementOne({model:`oauthRefreshToken`,where:[{field:`id`,value:i.id},{field:`revoked`,operator:`eq`,value:null}],increment:{},set:{revoked:/* @__PURE__ */ new Date(a*1e3)}}))throw await f0(e,r,i.userId),new O(`BAD_REQUEST`,{error_description:`refresh token revoked`,error:`invalid_request`});await e.context.adapter.deleteMany({model:`oauthAccessToken`,where:[{field:`refreshId`,value:i.id}]})}async function Jve(e,t,n,r){try{return await Gve(e,t,r)}catch(e){if(e instanceof O){if(e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}try{return await Kve(e,t,r,n)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw new O(`BAD_REQUEST`,{error_description:`Invalid access token`,error:`invalid_request`})}async function Yve(e,t){let{token:n,token_type_hint:r}=e.body;r!==`access_token`&&r!==`refresh_token`&&(r=void 0);let{clientId:i,clientSecret:a,preVerified:o,authMethod:s}=_1(await v1(e,t,`${e.context.baseURL}/oauth2/revoke`));if(!i)throw new O(`UNAUTHORIZED`,{error_description:`missing required credentials`,error:`invalid_client`});if(typeof n==`string`&&(n=sZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await h1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await Jve(e,t,c.clientId,n)}catch(e){if(e instanceof O){if(r===`access_token`||e.body?.error===`unsupported_token_type`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}if(r===void 0||r===`refresh_token`)try{return await qve(e,t,(await d0(t,n)).token,c.clientId)}catch(e){if(e instanceof O){if(r===`refresh_token`)throw e}else if(e instanceof Error)throw e;else throw Error(e)}throw new O(`BAD_REQUEST`,{error_description:`token not found`,error:`invalid_request`})}catch(e){if(e instanceof O){if(e.body?.error===`unsupported_token_type`)throw e;if(e.name===`BAD_REQUEST`)return null;throw e}throw e instanceof Error?(f.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(f.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}const Xve={oauthClient:{modelName:`oauthClient`,fields:{clientId:{type:`string`,unique:!0,required:!0},clientSecret:{type:`string`,required:!1},clientDiscoveryId:{type:`string`,required:!1},disabled:{type:`boolean`,defaultValue:!1,required:!1},skipConsent:{type:`boolean`,required:!1},enableEndSession:{type:`boolean`,required:!1},subjectType:{type:`string`,required:!1},scopes:{type:`string[]`,required:!1},clientCredentialsScopes:{type:`string[]`,required:!1,defaultValue:[]},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},name:{type:`string`,required:!1},uri:{type:`string`,required:!1},icon:{type:`string`,required:!1},contacts:{type:`string[]`,required:!1},tos:{type:`string`,required:!1},policy:{type:`string`,required:!1},softwareId:{type:`string`,required:!1},softwareVersion:{type:`string`,required:!1},softwareStatement:{type:`string`,required:!1},redirectUris:{type:`string[]`,required:!0},postLogoutRedirectUris:{type:`string[]`,required:!1},backchannelLogoutUri:{type:`string`,required:!1},backchannelLogoutSessionRequired:{type:`boolean`,required:!1},tokenEndpointAuthMethod:{type:`string`,required:!1},applicationType:{type:`string`,required:!1},jwks:{type:`string`,required:!1},jwksUri:{type:`string`,required:!1},grantTypes:{type:`string[]`,required:!1},responseTypes:{type:`string[]`,required:!1},requirePKCE:{type:`boolean`,required:!1},dpopBoundAccessTokens:{type:`boolean`,required:!1,defaultValue:!1},referenceId:{type:`string`,required:!1},metadata:{type:`json`,required:!1}}},oauthResource:{modelName:`oauthResource`,fields:{identifier:{type:`string`,required:!0,unique:!0},name:{type:`string`,required:!0},accessTokenTtl:{type:`number`,required:!1},refreshTokenTtl:{type:`number`,required:!1},signingAlgorithm:{type:`string`,required:!1},signingKeyId:{type:`string`,required:!1},allowedScopes:{type:`string[]`,required:!1},customClaims:{type:`json`,required:!1},dpopBoundAccessTokensRequired:{type:`boolean`,required:!1,defaultValue:!1},disabled:{type:`boolean`,required:!1,defaultValue:!1},createdAt:{type:`date`,required:!1},updatedAt:{type:`date`,required:!1},policyVersion:{type:`number`,required:!1,defaultValue:1},metadata:{type:`json`,required:!1}}},oauthClientResource:{modelName:`oauthClientResource`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`,onDelete:`cascade`},index:!0},resourceId:{type:`string`,required:!0,references:{model:`oauthResource`,field:`identifier`,onDelete:`cascade`},index:!0},metadata:{type:`json`,required:!1},createdAt:{type:`date`,required:!1}},indexes:[{fields:[`clientId`,`resourceId`],unique:!0}]},oauthRefreshToken:{fields:{token:{type:`string`,required:!0,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!0,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},rotatedAt:{type:`date`,required:!1},rotationReplayResponse:{type:`string`,required:!1},rotationReplayExpiresAt:{type:`date`,required:!1},authTime:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthAccessToken:{modelName:`oauthAccessToken`,fields:{token:{type:`string`,unique:!0},clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},sessionId:{type:`string`,required:!1,references:{model:`session`,field:`id`,onDelete:`set null`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},authorizationCodeId:{type:`string`,required:!1,index:!0},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},refreshId:{type:`string`,required:!1,references:{model:`oauthRefreshToken`,field:`id`},index:!0},expiresAt:{type:`date`},createdAt:{type:`date`},revoked:{type:`date`,required:!1},confirmation:{type:`json`,required:!1},scopes:{type:`string[]`,required:!0}}},oauthConsent:{modelName:`oauthConsent`,fields:{clientId:{type:`string`,required:!0,references:{model:`oauthClient`,field:`clientId`},index:!0},userId:{type:`string`,required:!1,references:{model:`user`,field:`id`},index:!0},referenceId:{type:`string`,required:!1},resources:{type:`string[]`,required:!1},requestedUserInfoClaims:{type:`string[]`,required:!1},scopes:{type:`string[]`,required:!0},createdAt:{type:`date`},updatedAt:{type:`date`}}},oauthClientAssertion:{modelName:`oauthClientAssertion`,fields:{expiresAt:{type:`date`,required:!0}}}},t4=[`openid`,`profile`,`email`,`offline_access`],n4=A({id_token_hint:k().optional(),client_id:k().optional(),post_logout_redirect_uri:A1.optional(),state:k().optional()}),r4=yH(()=>null),i4=r4.get,a4=/* @__PURE__ */ new WeakMap,o4=`signedQueryIssuedAtMs`;function Zve(e){let t=typeof e==`number`?e:typeof e==`string`?Number(e):void 0;if(!(!t||!Number.isFinite(t)||t<=0))return new Date(t)}const s4=e=>{let t=e.clientRegistrationAllowedScopes;if(e.clientRegistrationDefaultScopes){let n=t?/* @__PURE__ */ new Set([...t,...e.clientRegistrationDefaultScopes]):/* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes]);t=Array.from(n)}let n=new Set((e.scopes??t4).filter(e=>e.length));if(t){for(let e of t)if(!n.has(e))throw new D(`clientRegistrationAllowedScope ${e} not found in scopes`)}for(let t of e.advertisedMetadata?.scopes_supported??[])if(!n?.has(t))throw new D(`advertisedMetadata.scopes_supported ${t} not found in scopes`);let r=new Set((e.resources??[]).map(e=>typeof e==`string`?e:e.identifier));for(let[t,n]of[[`clientRegistrationDefaultResources`,e.clientRegistrationDefaultResources],[`clientRegistrationAllowedResources`,e.clientRegistrationAllowedResources]])for(let e of n??[])if(!r.has(e))throw new D(`${t} resource ${e} not found in resources`);let i=/* @__PURE__ */ new Set([`sub`,`iss`,`aud`,`exp`,`iat`,`sid`,`scope`,`azp`,...z1.filter(e=>n.has(R1[e].scope))]),a={codeExpiresIn:600,accessTokenExpiresIn:3600,m2mAccessTokenExpiresIn:3600,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,allowUnauthenticatedClientRegistration:!1,allowDynamicClientRegistration:!1,disableJwtPlugin:!1,storeClientSecret:e.disableJwtPlugin?`encrypted`:`hashed`,storeTokens:`hashed`,grantTypes:[`authorization_code`,`client_credentials`,`refresh_token`],...e,scopes:Array.from(n),claims:Array.from(i),clientRegistrationAllowedScopes:t};if(z$(a.extensions),a.pairwiseSecret&&a.pairwiseSecret.length<32)throw new D(`pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security`);if(a.grantTypes&&a.grantTypes.includes(`refresh_token`)&&!a.grantTypes.includes(`authorization_code`))throw new D(`refresh_token grant requires authorization_code grant`);if(a.disableJwtPlugin&&(a.storeClientSecret===`hashed`||typeof a.storeClientSecret==`object`&&`hash`in a.storeClientSecret))throw new D(`unable to store hashed secrets because id tokens will be signed with secret`);if(!a.disableJwtPlugin&&(a.storeClientSecret===`encrypted`||typeof a.storeClientSecret==`object`&&(`encrypt`in a.storeClientSecret||`decrypt`in a.storeClientSecret)))throw new D(`encryption method not recommended, please use 'hashed' or the 'hash' function`);let o=async(e,t)=>{let n=new URL(e.url).pathname,r=t.options.advanced?.skipTrailingSlashes?n.replace(/\/+$/,``)||`/`:n,i=a.disableJwtPlugin?t.baseURL:J$(t)?.options?.jwt?.issuer??t.baseURL,o=`/`;try{o=new URL(i).pathname.replace(/\/$/,``)||``}catch{o=new URL(t.baseURL).pathname.replace(/\/$/,``)||``}let s={context:t},c=/* @__PURE__ */ new Set([`/.well-known/oauth-authorization-server${o}`,`${o}/.well-known/oauth-authorization-server`]),l=`${o}/.well-known/openid-configuration`,u=c.has(r),d=a.scopes?.includes(`openid`)&&r===l,f=t=>{let n=n2(t);return e.method===`HEAD`?new Response(null,{status:n.status,headers:n.headers}):n};if((u||d)&&e.method!==`GET`&&e.method!==`HEAD`)return{response:new Response(null,{status:405,headers:{Allow:`GET, HEAD`}})};if(u)return a.scopes?.includes(`openid`)?{response:f(t2(s,a))}:{response:f(e2(s,a))};if(d)return{response:f(t2(s,a))}},s=r2(`/oauth2/authorize`,{method:[`GET`,`POST`],body:A({}).passthrough(),redirectOnError:v4(a),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Authorize an OAuth 2.1 request from query parameters or an application/x-www-form-urlencoded POST body`,parameters:[{name:`response_type`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 response type (e.g., 'code')`},{name:`client_id`,in:`query`,required:!0,schema:{type:`string`},description:`OAuth 2.1 client ID`},{name:`redirect_uri`,in:`query`,required:!1,schema:{type:`string`,format:`uri`},description:`OAuth 2.1 redirect URI`},{name:`scope`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 scopes (space-separated)`},{name:`state`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth 2.1 state parameter`},{name:`request_uri`,in:`query`,required:!1,schema:{type:`string`},description:`Pushed Authorization Request URI referencing stored parameters`},{name:`code_challenge`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge`},{name:`code_challenge_method`,in:`query`,required:!1,schema:{type:`string`},description:`PKCE code challenge method`},{name:`nonce`,in:`query`,required:!1,schema:{type:`string`},description:`OpenID Connect nonce`},{name:`max_age`,in:`query`,required:!1,schema:{type:`integer`,minimum:0},description:`Maximum authentication age in seconds; forces re-authentication when exceeded`},{name:`resource`,in:`query`,required:!1,schema:{type:`array`,items:{type:`string`}},description:`Requested protected resource(s) for the access token. May be supplied multiple times as repeated 'resource' query parameters (RFC 8707) or as an array of strings.`},{name:`prompt`,in:`query`,required:!1,schema:{type:`string`},description:`OAuth2 prompt parameter`}],responses:{302:{description:`Redirect to client with code or error`,headers:{Location:{description:`Redirect URI with code or error`,schema:{type:`string`,format:`uri`}}}},400:{description:`Invalid request`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},state:{type:`string`}},required:[`error`]}}}}}}}},async e=>aye(e,a,e.authorizeSettings??{isAuthorize:!0})),c=(e,t)=>CQ(s,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:`1.7.10`,options:a,onRequest:o,init:async e=>{if(e.options.secondaryStorage&&e.options.session?.storeSessionInDatabase!==!0)throw new D("OAuth Provider requires `session.storeSessionInDatabase: true` when using secondaryStorage");if(a.allowClientKeyRotation){let t=e.adapter.id===`memory`?`the memory adapter`:e.options.advanced?.database?.generateId===`serial`?'`advanced.database.generateId: "serial"`':void 0;if(t)throw new D(`\`allowClientKeyRotation\` requires single-use client assertions, which ${t} does not enforce`)}if(await n0(e,a).catch(t=>yge(e,t)),Sge(a),!a.disableJwtPlugin){let t=J$(e)?.options,n=t?.jwt?.issuer??e.baseURL,r=t?.jwt?.issuer==null&&typeof e.options.baseURL==`object`&&e.options.baseURL!==null&&`allowedHosts`in e.options.baseURL;try{new URL(n)}catch(e){if(!r||n!==``)throw e}}return{options:{databaseHooks:{session:{delete:{async before(e,t){if(!t)return;let n=await f_e(t,a,{sessionId:e.id,userId:e.userId});if(!n)return;let r=a4.get(t)??/* @__PURE__ */ new Map;r.set(e.id,n),a4.set(t,r)},async after(e,t){if(!t)return;let n=a4.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&a4.delete(t),!r)return;let i=p_e(t,r).catch(e=>{t.context.logger.error(`Back-channel logout failed after session deletion`,e)});await t.context.runInBackgroundOrAwait(i)}}}}}}},hooks:{before:[{matcher(e){return e.body?.oauth_query},handler:zq(async e=>{let t=e.body.oauth_query;if(!await e1(t,e.context.secret))throw new E(`BAD_REQUEST`,{error:`invalid_signature`});let n=dhe(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(j$),r.delete(M$),await r4.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Aq({query:r.toString(),...n?{[o4]:n.getTime()}:{}})})}],after:[{matcher(e){return xG(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:zq(async e=>{let t=xG(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await r4.get(),r=(await Dq())?.serverContext,i=n?.query??r?.query;if(!i)return;let a=new URLSearchParams(i),o=await e.context.internalAdapter.findSession(t);if(!o)return;e.context.session=o;let s=e.request?.headers?.get(`sec-fetch-mode`)?.toLowerCase(),l=e.request?.headers?.get(`accept`)?.toLowerCase()??``;s===`navigate`||!s&&(l.includes(`text/html`)||l.includes(`application/xhtml+xml`))||e.headers?.set(`accept`,`application/json`);let u=n?.signedQueryIssuedAt??Zve(r?.[o4]),d=T1(a,`login`);return w1(o.session.createdAt,u)&&(d=E1(d)),e.query=C1(d),await c(e)})}]},endpoints:{getOAuthServerConfig:X(`/.well-known/oauth-authorization-server`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>a.scopes&&a.scopes.includes(`openid`)?t2(e,a):e2(e,a)),getOpenIdConfig:X(`/.well-known/openid-configuration`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async e=>{if(a.scopes&&!a.scopes.includes(`openid`))throw new E(`NOT_FOUND`);return t2(e,a)}),oauth2Authorize:s,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:A({accept:He().meta({description:`Accept or deny user consent for a set of scopes`}),scope:k().optional().meta({description:`List of accept of accepted space-separated scopes. If none is provided, then all originally requested scopes are accepted.`}),claims:F1.optional().meta({description:`Accepted OIDC claims request object. If none is provided, then all originally requested claims are accepted.`}),oauth_query:k().optional().meta({description:`The redirected page's query parameters`})}),use:[VJ],metadata:{openapi:{description:`Handle OAuth2 consent`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`The URI to redirect to, either with an authorization code or an error`}},required:[`redirect_uri`]}}}}}}}},async e=>o_e(e,a,c)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:A({selected:He().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:He().optional().meta({description:`Confirms an account was registered`}),postLogin:He().optional().meta({description:`Resumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true.`}),oauth_query:k().optional().meta({description:`The redirected page's query parameters`})}),use:[VJ],metadata:{openapi:{description:`Continues OAuth2 authorization flow`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`The URI to redirect to, either with an authorization code or an error`}},required:[`redirect_uri`]}}}}}}}},async e=>s_e(e,c)),oauth2Token:r2(`/oauth2/token`,{method:`POST`,cloneRequest:!0,body:A({grant_type:k().trim().min(1),client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),code:k().optional(),code_verifier:k().optional(),redirect_uri:A1.optional(),refresh_token:k().optional(),resource:Ee([H1,Pe(H1).min(1)]).optional(),scope:k().optional()}).passthrough(),errorCodesByField:{grant_type:{missing:`invalid_request`,invalid:`unsupported_grant_type`},resource:{invalid:`invalid_target`}},metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Obtain an OAuth2.1 access token`,parameters:[{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT for issuing DPoP-bound tokens`}],requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{grant_type:{type:`string`,description:`OAuth2 grant type`},client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},code:{type:`string`,description:`Authorization code (for authorization_code grant)`},code_verifier:{type:`string`,description:`PKCE code verifier (for authorization_code grant)`},redirect_uri:{type:`string`,format:`uri`,description:`Redirect URI (for authorization_code grant)`},refresh_token:{type:`string`,description:`Refresh token (for refresh_token grant)`},resource:{oneOf:[{type:`string`,description:`Single resource (URL)`},{type:`array`,items:{type:`string`},description:`Multiple resources (URLs)`}],description:`Requested protected resource(s) for the access token`},scope:{type:`string`,description:`Requested scopes (for client_credentials grant)`}},required:[`grant_type`]}}}},responses:{200:{description:`Access token response`,content:{"application/json":{schema:{type:`object`,properties:{access_token:{type:`string`,description:`The access token issued by the authorization server`},token_type:{type:`string`,description:`The type of the token issued`,enum:[`Bearer`,`DPoP`]},expires_in:{type:`number`,description:`Lifetime in seconds of the access token`},refresh_token:{type:`string`,description:`Refresh token, if issued`},scope:{type:`string`,description:`Scopes granted by the access token`},id_token:{type:`string`,description:`ID Token (if OpenID Connect)`}},required:[`access_token`,`token_type`,`expires_in`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>{if(e.request){let t=await uge(e.request);t&&t.length>1&&(e.body.resource=t)}return Oge(e,a)}),oauth2Introspect:r2(`/oauth2/introspect`,{method:`POST`,cloneRequest:!0,body:A({client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),token:k(),token_type_hint:k().optional()}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Introspect an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to introspect (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token introspection response`,content:{"application/json":{schema:{type:`object`,properties:{active:{type:`boolean`,description:`Whether the token is active`},scope:{type:`string`,description:`Scopes associated with the token`},client_id:{type:`string`,description:`Client ID associated with the token`},username:{type:`string`,description:`Username associated with the token`},token_type:{type:`string`,description:`Type of the token`},exp:{type:`number`,description:`Expiration time of the token (seconds since epoch)`},iat:{type:`number`,description:`Issued at time (seconds since epoch)`},nbf:{type:`number`,description:`Not before time (seconds since epoch)`},sub:{type:`string`,description:`Subject of the token`},aud:{type:`string`,description:`Audience of the token`},iss:{type:`string`,description:`Issuer of the token`},jti:{type:`string`,description:`JWT ID`}},required:[`active`]}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>M0(e,a)),oauth2Revoke:r2(`/oauth2/revoke`,{method:`POST`,cloneRequest:!0,body:A({client_id:k().optional(),client_secret:k().optional(),client_assertion:k().optional(),client_assertion_type:k().optional(),token:k(),token_type_hint:k().optional()}),metadata:{allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Revoke an OAuth2 access or refresh token`,requestBody:{required:!0,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`OAuth2 client ID`},client_secret:{type:`string`,description:`OAuth2 client secret`},token:{type:`string`,description:`The token to revoke (access or refresh token)`},token_type_hint:{type:`string`,description:"Hint about the token type. Recognized values: `access_token`, `refresh_token`."}},required:[`token`]}}}},responses:{200:{description:`Token revoked successfully. The response body is empty.`,content:{"application/json":{schema:{type:`object`,description:`Empty object on success`}}}},400:{description:`Invalid request or error response`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`},error_uri:{type:`string`}},required:[`error`]}}}}}}}},async e=>Yve(e,a)),oauth2UserInfo:X(`/oauth2/userinfo`,{method:[`GET`,`POST`],body:A({access_token:k().optional()}).passthrough().optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],openapi:{description:`Get OpenID Connect user information (UserInfo endpoint)`,security:[{bearerAuth:[]},{OAuth2:[`openid`,`profile`,`email`]}],parameters:[{name:`Authorization`,in:`header`,required:!1,schema:{type:`string`},description:`Bearer or DPoP access token`},{name:`DPoP`,in:`header`,required:!1,schema:{type:`string`},description:`RFC 9449 DPoP proof JWT when using a DPoP-bound access token`}],responses:{200:{description:`User information retrieved successfully`,content:{"application/json":{schema:{type:`object`,properties:{sub:{type:`string`,description:`Subject identifier (user ID)`},email:{type:`string`,format:`email`,nullable:!0,description:`User's email address, included if 'email' scope is granted`},name:{type:`string`,nullable:!0,description:`User's full name, included if 'profile' scope is granted`},picture:{type:`string`,format:`uri`,nullable:!0,description:`User's profile picture URL, included if 'profile' scope is granted`},given_name:{type:`string`,nullable:!0,description:`User's given name, included if 'profile' scope is granted`},family_name:{type:`string`,nullable:!0,description:`User's family name, included if 'profile' scope is granted`},email_verified:{type:`boolean`,nullable:!0,description:`Whether the email is verified, included if 'email' scope is granted`}},required:[`sub`]}}}},401:{description:`Unauthorized - invalid or missing access token`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}},403:{description:`Forbidden - insufficient scope`,content:{"application/json":{schema:{type:`object`,properties:{error:{type:`string`},error_description:{type:`string`}},required:[`error`]}}}}}}}},async e=>Ege(e,a)),oauth2EndSession:r2(`/oauth2/end-session`,{method:[`GET`,`POST`],body:n4.optional(),query:n4.optional(),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`,`application/json`],$Infer:{body:{},query:{}},openapi:{description:`RP-Initiated Logout endpoint. Accepts standard logout parameters through GET or an application/x-www-form-urlencoded POST body, plus JSON for Better Auth generated-client calls. Requests without a usable id_token_hint may require explicit OP confirmation.`,responses:{200:{description:`Logout completed, or an HTML confirmation page was returned for browser navigation. A redirect is used only for an exact registered post_logout_redirect_uri.`,content:{"application/json":{schema:{type:`object`,properties:{redirect_uri:{type:`string`,format:`uri`,description:`URI to redirect to after logout (if post_logout_redirect_uri was provided)`},message:{type:`string`,description:`Success message`}}}},"text/html":{schema:{type:`string`}}}}}}}},async e=>w_e(e,a)),oauth2EndSessionConfirmation:r2(`/oauth2/end-session/confirm`,{method:`POST`,body:A({action:Ue(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>T_e(e,a)),registerOAuthClient:r2(`/oauth2/register`,{method:`POST`,body:G1,errorCodesByField:{redirect_uris:`invalid_redirect_uri`,post_logout_redirect_uris:`invalid_redirect_uri`,software_statement:`invalid_software_statement`,resources:`invalid_target`},defaultError:`invalid_client_metadata`,metadata:{noStore:!0,openapi:{description:`Register an OAuth2 application`,responses:{201:{description:`OAuth2 application registered successfully`,content:{"application/json":{schema:{type:`object`,properties:{client_id:{type:`string`,description:`Unique identifier for the client`},client_secret:{type:`string`,description:`Secret key for the client`},client_secret_expires_at:{type:`number`,description:`Time the client secret will expire. If 0, the client secret will never expire.`},scope:{type:`string`,description:`Space-separated scopes allowed by the client`},user_id:{type:`string`,description:`ID of the user who registered the client, null if registered anonymously`},client_id_issued_at:{type:`number`,description:`Creation timestamp of this client`},client_name:{type:`string`,description:`Name of the OAuth2 application`},client_uri:{type:`string`,description:`Name of the OAuth2 application`},logo_uri:{type:`string`,description:`Icon URL for the application`},contacts:{type:`array`,items:{type:`string`},description:`List representing ways to contact people responsible for this client, typically email addresses`},tos_uri:{type:`string`,description:`Client's terms of service uri`},policy_uri:{type:`string`,description:`Client's policy uri`},software_id:{type:`string`,description:`Unique identifier assigned by the developer to help in the dynamic registration process`},software_version:{type:`string`,description:`Version identifier for the software_id`},software_statement:{type:`string`,description:`JWT containing metadata values about the client software as claims`},redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed redirect uris`},post_logout_redirect_uris:{type:`array`,items:{type:`string`,format:`uri`},description:`List of allowed logout redirect uris`},backchannel_logout_uri:{type:`string`,format:`uri`,description:`RP URL to receive signed Logout Tokens when the end-user's OP session terminates`},backchannel_logout_session_required:{type:`boolean`,description:"Whether the RP requires a `sid` claim in every Logout Token"},token_endpoint_auth_method:{type:`string`,description:`Requested authentication method for the token endpoint`},grant_types:{type:`array`,items:{type:`string`},description:`Grant types the client may use at the token endpoint`},response_types:{type:`array`,items:{type:`string`,enum:[`code`]},description:`Response types the client may use at the authorization endpoint`},application_type:{type:`string`,description:`OIDC application type used to classify redirect URI policy`,enum:[`web`,`native`]},resources:{type:`array`,items:{type:`string`,format:`uri`},description:`Final resource identifiers linked to the registered client`},disabled:{type:`boolean`,description:`Whether the client is disabled`}},required:[`client_id`]}}}}}}}},async e=>eve(e,a)),adminCreateOAuthClient:uve(a),createOAuthClient:dve(a),getOAuthClient:fve(a),getOAuthClientPublic:pve(a),getOAuthClientPublicPrelogin:mve(a),getOAuthClients:hve(a),adminUpdateOAuthClient:gve(a),updateOAuthClient:_ve(a),rotateClientSecret:vve(a),rotateClientKeys:yve(a),deleteOAuthClient:bve(a),getOAuthConsent:Tve(a),getOAuthConsents:Eve(a),updateOAuthConsent:Dve(a),deleteOAuthConsent:Ove(a),adminCreateOAuthResource:Rve(a),adminListOAuthResources:zve(a),adminGetOAuthResource:Bve(a),adminUpdateOAuthResource:Vve(a),adminDeleteOAuthResource:Hve(a),adminLinkClientResource:Uve(a),adminUnlinkClientResource:Wve(a)},schema:lG(structuredClone(Xve),a?.schema),rateLimit:[...a.rateLimit?.token===!1?[]:[{pathMatcher:e=>e===`/oauth2/token`,window:a.rateLimit?.token?.window??60,max:a.rateLimit?.token?.max??20}],...a.rateLimit?.authorize===!1?[]:[{pathMatcher:e=>e===`/oauth2/authorize`,window:a.rateLimit?.authorize?.window??60,max:a.rateLimit?.authorize?.max??30}],...a.rateLimit?.introspect===!1?[]:[{pathMatcher:e=>e===`/oauth2/introspect`,window:a.rateLimit?.introspect?.window??60,max:a.rateLimit?.introspect?.max??100}],...a.rateLimit?.revoke===!1?[]:[{pathMatcher:e=>e===`/oauth2/revoke`,window:a.rateLimit?.revoke?.window??60,max:a.rateLimit?.revoke?.max??30}],...a.rateLimit?.register===!1?[]:[{pathMatcher:e=>e===`/oauth2/register`,window:a.rateLimit?.register?.window??60,max:a.rateLimit?.register?.max??5}],...a.rateLimit?.rotateClientKeys===!1?[]:[{pathMatcher:e=>e===`/oauth2/client/rotate-keys`,window:a.rateLimit?.rotateClientKeys?.window??60,max:a.rateLimit?.rotateClientKeys?.max??5}],...a.rateLimit?.userinfo===!1?[]:[{pathMatcher:e=>e===`/oauth2/userinfo`,window:a.rateLimit?.userinfo?.window??60,max:a.rateLimit?.userinfo?.max??60}]]}};function Qve(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function $ve(e){let{max_age:t,...n}=e;return n}function c4(e,t,n,r,i,a=`query`){let o=new URLSearchParams({error:t,error_description:n});return r&&o.append(`state`,r),i&&o.append(`iss`,i),a===`fragment`?`${e}#${o.toString()}`:bq(e,o)}function eye(e){let t=typeof e.response_mode==`string`?e.response_mode:void 0;if(t===`fragment`)return`fragment`;if(t===`query`)return`query`;let n=typeof e.response_type==`string`?e.response_type:void 0;return n&&/\b(token|id_token)\b/.test(n)?`fragment`:`query`}const tye={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function nye(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l4(e){return typeof e==`string`?e:void 0}function rye(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...nye(n)?n:{}}}const u4=(e,t)=>{let n=N0(e.request?.headers),r=e.headers?.get(`accept`)?.includes(`application/json`);if(n||r)return{redirect:!0,url:t.toString()};throw e.redirect(t)};function d4(e,t,n,r,i){return u4(e,c4(n.redirect_uri,r,i,n.state,p4(e,t)))}function f4(e){try{let t=new URL(e);return t.protocol!==`https:`&&!SY(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function p4(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=J$(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return f4(n)}function m4(e,t,n){return c4(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function h4(e){let t;try{t=new URL(e)}catch{return}let n=xY(t.hostname)||t.hostname===`localhost`;if(t.protocol!==`http:`||!n)return;let r=e.indexOf(`://`);if(r<0)return;let i=r+3,a=e.slice(i).search(/[/?#]/u),o=e.length;a>=0&&(o=i+a);let s=e.slice(i,o),c;if(s.startsWith(`[`)){let t=s.indexOf(`]`);if(t<0)return;if(s[t+1]!==`:`)return e;c=t+1}else if(c=s.lastIndexOf(`:`),c<0)return e;let l=s.slice(c+1);if(!/^\d*$/u.test(l))return;let u=i+c;return`${e.slice(0,u)}${e.slice(o)}`}function g4(e,t){if(!e||!t)return;let n;try{n=new URL(t)}catch{return}let r=t.includes(`#`),i=n.username.length>0||n.password.length>0;if(r||i)return;let a=h4(t);return e.find(e=>e===t?!0:a?h4(e)===a:!1)}function _4(e){if(!A1.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function iye(e,t,n,r){if(!n||!r)return null;let i;try{i=await n1(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=g4(a,r);if(t.validateRedirectUri){if(!_4(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function v4(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await iye(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?u4(r,c4(a,t,n,typeof i.state==`string`?i.state:void 0,p4(r,e),eye(i))):u4(r,m4(r,t,n))}}async function aye(e,t,n){if(t.grantTypes&&!t.grantTypes.includes(`authorization_code`))throw new O(`NOT_FOUND`);if(!e.request)throw new O(`UNAUTHORIZED`,{error_description:`request not found`,error:`invalid_request`});let r=e.request,i=rye(e,n);e.query=i;let a=l4(i.request),o=l4(i.request_uri);if(a!==void 0&&o!==void 0)return v4(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return v4(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=l4(i.client_id);if(!n)return v4(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return v4(t)({error:`request_uri_not_supported`,error_description:`request_uri not supported`,ctx:e});let r=await t.requestUriResolver({requestUri:o,clientId:n,ctx:e});if(!r)return v4(t)({error:`invalid_request_uri`,error_description:`request_uri is invalid or expired`,ctx:e});let a=i.client_id;i=r,a&&(i.client_id=a)}e.query=i;let s=W1.safeParse(i);if(!s.success){let n=i2(s.error.issues,tye);return v4(t)({...n,ctx:e})}if(i=s.data,e.query=i,await r4.set({query:y4(i).toString()}),!i.response_type)return v4(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?y1(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return u4(e,m4(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return u4(e,m4(e,`unsupported_response_type`,`unsupported response type`));let u=await n1(e,t,i.client_id);if(!u)return u4(e,m4(e,`invalid_client`,`client not found`));if(u.disabled)return u4(e,m4(e,`client_disabled`,`client is disabled`));if(!f1(u,`authorization_code`))return u4(e,m4(e,`unauthorized_client`,`client is not authorized to use the authorization_code grant`));let d=u.redirectUris??[],f=!1;if(i.redirect_uri){let e=!!g4(d,i.redirect_uri);if(t.validateRedirectUri&&_4(i.redirect_uri))try{f=await t.validateRedirectUri(i.redirect_uri,d,e)}catch{f=!1}else t.validateRedirectUri||(f=e)}if(!f)return u4(e,m4(e,`invalid_redirect`,`invalid redirect uri`));let p=i.scope?.split(` `).filter(e=>e);if(p){let n=new Set(u.scopes??t.scopes),r=p.filter(e=>!n?.has(e));if(r.length)return u4(e,c4(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,p4(e,t)))}p||(p=u.scopes??t.scopes??[],i.scope=p.join(` `));let m=p.includes(`openid`);if(i.claims!==void 0&&!m)return u4(e,c4(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,p4(e,t)));if(m&&!Jhe(i.claims))return u4(e,c4(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,p4(e,t)));if(m&&!Yhe(i.claims,`0`))return u4(e,c4(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,p4(e,t)));let h=I1(i.claims,B1(t));if(i.resource!==void 0)try{await Y1(e,t,{resource:i.resource,clientId:u.clientId,requestedScopes:p})}catch(n){if(n instanceof O){let r=n.body?.error??`invalid_target`,a=n.body?.error_description??`requested resource invalid`;return u4(e,c4(i.redirect_uri,r,a,i.state,p4(e,t)))}throw n}let g=D1(u,{scopes:p,nonce:i.nonce});if(g&&(!i.code_challenge||!i.code_challenge_method))return u4(e,c4(i.redirect_uri,`invalid_request`,g.valueOf(),i.state,p4(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return u4(e,c4(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,p4(e,t)));if(![`S256`].includes(i.code_challenge_method))return u4(e,c4(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,p4(e,t)))}let _=Z$(i.resource)??[],v=await zJ(e),y=i.max_age,b=v!=null&&y!==void 0&&Qve(new Date(v.session.createdAt),y,/* @__PURE__ */ new Date);if(!v||v!=null&&y!==void 0&&!b||c?.has(`login`)||c?.has(`create`))return l?d4(e,t,i,`login_required`,`authentication required`):x4(e,t,c?.has(`create`)?`create`:`login`);if(b&&(i=$ve(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return x4(e,t,`select_account`);if(n?.isAuthorize&&t.selectAccount&&await t.selectAccount.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p}))return l?d4(e,t,i,`account_selection_required`,`End-User account selection is required`):x4(e,t,`select_account`);if(t.signup?.shouldRedirect){let n=await t.signup.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p});if(n)return l?d4(e,t,i,`interaction_required`,`End-User interaction is required`):x4(e,t,`create`,{page:typeof n==`string`?n:void 0})}if(!n?.postLogin&&t.postLogin&&await t.postLogin.shouldRedirect({headers:r.headers,user:v.user,session:v.session,scopes:p,isContinuation:n?.isPostLoginContinuation??!1}))return l?d4(e,t,i,`interaction_required`,`End-User interaction is required`):x4(e,t,`post_login`);if(c?.has(`consent`))return x4(e,t,`consent`,{sessionId:v.session.id});let x=await x1(t,{user:v.user,session:v.session,scopes:p});if(u.skipConsent)return b4(e,t,{query:i,clientId:u.clientId,userId:v.user.id,sessionId:v.session.id,authTime:new Date(v.session.createdAt).getTime(),referenceId:x,resource:_});let S=await S1(e,u.clientId,v.user.id,x);if(!S||!p.every(e=>S.scopes.includes(e))||!h.every(e=>(S.requestedUserInfoClaims??[]).includes(e)))return l?d4(e,t,i,`consent_required`,`End-User consent is required`):x4(e,t,`consent`,{sessionId:v.session.id});let ee=S?.resources??[];return _.some(e=>!ee.includes(e))?l?d4(e,t,i,`consent_required`,`End-User consent is required`):x4(e,t,`consent`,{sessionId:v.session.id}):b4(e,t,{query:i,clientId:u.clientId,userId:v.user.id,sessionId:v.session.id,authTime:new Date(v.session.createdAt).getTime(),referenceId:x,resource:_})}function y4(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))if(r!=null){if(Array.isArray(r))for(let e of r)t.append(n,String(e));else n===`claims`&&typeof r==`object`?t.set(n,JSON.stringify(r)):t.set(n,String(r))}return t}async function b4(e,t,n){let r=JH(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await s1(t.storeTokens,r,`authorization_code`),updatedAt:/* @__PURE__ */ new Date(i*1e3),expiresAt:/* @__PURE__ */ new Date(a*1e3),value:JSON.stringify({type:`authorization_code`,query:n.query,userId:n.userId,sessionId:n?.sessionId,referenceId:n.referenceId,authTime:n.authTime,resource:n.resource})};await e.context.internalAdapter.createVerificationValue({...o,createdAt:/* @__PURE__ */ new Date(i*1e3)});let s=new URL(n.query.redirect_uri);return s.searchParams.set(`code`,r),n.query.state&&s.searchParams.set(`state`,n.query.state),s.searchParams.set(`iss`,p4(e,t)),u4(e,s.toString())}async function x4(e,t,n,r){let i=await oye(e,t,{postLoginClearedForSession:n===`consent`&&t.postLogin?r?.sessionId:void 0}),a=t.loginPage;if(n===`select_account`)a=t.selectAccount?.page??t.loginPage;else if(n===`post_login`){if(!t.postLogin?.page)throw new O(`INTERNAL_SERVER_ERROR`,{error_description:`postLogin should have been defined`});a=t.postLogin?.page}else n===`consent`?a=t.consentPage:n===`create`&&(a=t.signup?.page??t.loginPage);return u4(e,`${r?.page??a}?${i}`)}async function oye(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=y4(e.query);a.set(`exp`,String(i)),a.set(j$,String(r)),a.delete(`sig`),a.delete(M$),n?.postLoginClearedForSession&&a.set(M$,n.postLoginClearedForSession),uhe(a);let o=await VW(P$(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}const sye=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,cye=/* @__PURE__ */ new Set([`client_secret_post`,`client_secret_basic`,`client_secret_jwt`]);function S4(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`}function lye(e){if(sye.test(e))return`client_id URL MUST NOT contain dot segments`;if(e.includes(`#`))return`client_id URL MUST NOT contain a fragment`;let t;try{t=new URL(e)}catch{return`client_id is not a valid URL`}if(t.protocol!==`https:`)return`client_id URL must use HTTPS`;let n=/^https:\/\//i.exec(e);if(!n||e.includes(`\\`))return`client_id URL MUST use an explicit HTTPS authority form`;let r=e.slice(n[0].length),i=r.search(/[/?#]/);return i===0?`client_id URL MUST use an explicit HTTPS authority form`:i<0||r[i]!==`/`?`client_id URL MUST contain an explicit path component`:t.username||t.password?`client_id URL MUST NOT contain credentials`:CY(t.hostname)?null:`client_id URL must not target a private or reserved address`}function uye(e){let t=[];try{let n=new URL(e);n.pathname===`/`&&t.push(`client_id URL path / is NOT RECOMMENDED (§3)`),n.search&&t.push(`client_id URL SHOULD NOT contain a query string (§3)`)}catch{}return t}function dye(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||k1(t)}catch{return!1}}function fye(e,t,n={}){if(!t||typeof t!=`object`)return{valid:!1,error:`metadata document is not a JSON object`};for(let e of Object.keys(t))if(f2(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let r=oge.strip().safeParse(t);if(!r.success){let e=r.error.issues[0];return{valid:!1,error:`${e?.path.join(`.`)||`metadata document`}: ${e?.message??`invalid client metadata`}`}}let i=r.data,a=[];if(i.client_id!==e)return{valid:!1,error:`client_id "${String(i.client_id)}" does not match the metadata document URL`};if(n.metadataProfile===`mcp-2026-07-28`&&!i.client_name?.trim())return{valid:!1,error:`client_name must be a non-empty string`};for(let e of[`backchannel_logout_uri`,`backchannel_logout_session_required`])if(i[e]!==void 0)return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let o=/* @__PURE__ */ new Set([`none`,`private_key_jwt`]);if(typeof i.token_endpoint_auth_method==`string`){if(cye.has(i.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${i.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!o.has(i.token_endpoint_auth_method))return{valid:!1,error:`token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients`};if(i.token_endpoint_auth_method===`private_key_jwt`&&!i.jwks&&!i.jwks_uri)return{valid:!1,error:`private_key_jwt requires either jwks or jwks_uri in the metadata document`}}if(i.jwks&&!u2(i.jwks).valid)return{valid:!1,error:`jwks must contain only structurally valid public keys`};if(i.jwks_uri)try{let e=new URL(i.jwks_uri);if(e.username||e.password)return{valid:!1,error:`jwks_uri must not contain credentials`};if(i.jwks_uri.includes(`#`))return{valid:!1,error:`jwks_uri must not contain a fragment`}}catch{return{valid:!1,error:`jwks_uri must be a valid URL`}}if(n.metadataProfile===`mcp-2026-07-28`&&!i.redirect_uris||i.redirect_uris&&!i.redirect_uris.every(e=>dye(e)))return{valid:!1,error:`redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs`};for(let e of[`client_uri`,`logo_uri`,`tos_uri`,`policy_uri`]){if(i[e]!==void 0&&typeof i[e]!=`string`)return{valid:!1,error:`${e} must be a string`};if(typeof i[e]==`string`)try{let t=new URL(i[e]);if(t.protocol!==`https:`&&t.protocol!==`http:`)return{valid:!1,error:`${e} must use HTTP(S)`};if(t.username||t.password)return{valid:!1,error:`${e} must not contain credentials`};if(!CY(t.hostname))return{valid:!1,error:`${e} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${e} is not a valid URL`}}}let s=n.originBoundFields??[`post_logout_redirect_uris`,`client_uri`],c;try{c=new URL(e).origin}catch{return{valid:!1,error:`client_id is not a valid URL`}}for(let e of s){let t=i[e];if(t===void 0)continue;let n;if(typeof t==`string`)n=[t];else if(Array.isArray(t)){if(!t.every(e=>typeof e==`string`))return{valid:!1,error:`${e} must be a string or an array of strings`};n=t}else return{valid:!1,error:`${e} must be a string or an array of strings`};for(let t of n){let n;try{n=new URL(t)}catch{return{valid:!1,error:`${e} contains an invalid URL: "${t}"`}}let r=e===`redirect_uris`||e===`post_logout_redirect_uris`,i=r&&k1(n);if(n.protocol!==`https:`&&n.protocol!==`http:`&&!i)return{valid:!1,error:`all values for ${e} must use HTTP(S) or a private-use scheme`};if(i&&(e===`redirect_uris`||O1(n)))continue;let a=r&&(n.protocol===`http:`||n.protocol===`https:`)&&SY(n.hostname);if(n.origin!==c&&!a)return{valid:!1,error:`${e} value "${t}" must have the same origin as client_id (${c})`}}}return a.push(...uye(e)),{valid:!0,metadata:{...i,token_endpoint_auth_method:i.token_endpoint_auth_method??`none`},...a.length>0?{warnings:a}:{}}}const C4=5e3,w4=5120,pye=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,T4=`Failed to fetch metadata document (network error or redirect blocked)`,E4=`cimd`;function D4(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function O4(){return D4(`Metadata document exceeds ${w4/1024}KB size limit`)}async function mye(e,t,n){let r=e.body?.getReader();if(!r){let n=await e.text();if(new TextEncoder().encode(n).byteLength>t)throw O4();return n}let i=[],a=0,o,s=new Promise((e,t)=>{o=t}),c=()=>{o?.(/* @__PURE__ */ Error(`Metadata document body read aborted`)),r.cancel().catch(()=>{})};n.aborted?c():n.addEventListener(`abort`,c,{once:!0});try{for(;;){let{done:e,value:n}=await Promise.race([r.read(),s]);if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel(),O4();i.push(n)}}finally{n.removeEventListener(`abort`,c),r.releaseLock()}let l=new Uint8Array(a),u=0;for(let e of i)l.set(e,u),u+=e.byteLength;return new TextDecoder().decode(l)}function hye(e){return{cacheControl:e.get(`cache-control`)??void 0,vary:e.get(`vary`)??void 0,expires:e.get(`expires`)??void 0,date:e.get(`date`)??void 0,age:e.get(`age`)??void 0,etag:e.get(`etag`)??void 0,lastModified:e.get(`last-modified`)??void 0}}async function gye(e,t,n,r){let i=lye(t);if(i)throw D4(i);if(n.isMetadataDocumentUrlAllowed&&!await n.isMetadataDocumentUrlAllowed(t,e))throw D4(`client_id URL is not permitted by the server's fetch policy`);let a=new Headers({Accept:`application/json`});r?.etag&&a.set(`If-None-Match`,r.etag),r?.lastModified&&a.set(`If-Modified-Since`,r.lastModified);let o,s=new AbortController,c=!1,l=setTimeout(()=>{c=!0,s.abort()},C4);try{try{o=await n.fetchClientMetadataResource(t,{headers:a,redirect:`error`,signal:s.signal})}catch{throw D4(c?`Metadata document fetch timed out after ${C4}ms`:T4)}if(o.redirected)throw D4(`Metadata document fetch must not follow redirects`);let i=hye(o.headers);if(o.status===304){if(!r?.etag&&!r?.lastModified)throw D4(`Metadata document returned 304 without a conditional validator`);return{status:`not-modified`,cacheHeaders:i}}if(o.status!==200)throw D4(`Metadata document fetch returned HTTP ${o.status}`);let l=o.headers.get(`content-type`)??``;if(!pye.test(l))throw D4(`Metadata document must be JSON (got Content-Type "${l||`(none)`}")`);let u;try{let e=o.headers.get(`content-length`);if(e){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>w4)throw await o.body?.cancel(),O4()}u=await mye(o,w4,s.signal)}catch(e){throw c?D4(`Metadata document fetch timed out after ${C4}ms`):e instanceof O?e:D4(T4)}let d;try{d=JSON.parse(u)}catch{throw D4(`Metadata document is not valid JSON`)}let f=fye(t,d,{originBoundFields:n.originBoundFields,metadataProfile:n.metadataProfile});if(!f.valid)throw D4(f.error);for(let t of f.warnings??[])e.context.logger.warn(`cimd metadata document warning: ${t}`);return{status:`modified`,metadata:f.metadata,cacheHeaders:i}}finally{clearTimeout(l)}}async function k4(e,t,n,r,i,a){let o=a?{...a}:void 0,s=await V2(e,i,{clientId:t,clientDiscoveryId:E4,metadata:{...n,client_id:n.client_id,redirect_uris:n.redirect_uris??[]},existingClient:a});if(s.created)try{await r.onClientCreated?.({client:s.client,clientMetadataDocument:n,context:e})}catch(t){e.context.logger.error(`cimd onClientCreated notification failed`,t)}else try{o&&await r.onClientRefreshed?.({client:s.client,previousClient:o,clientMetadataDocument:n,context:e})}catch(t){e.context.logger.error(`cimd onClientRefreshed notification failed`,t)}return s.client}const A4={minimumFetchInterval:1,maximumConcurrentFetches:16,maximumConcurrentFetchesPerOrigin:4,maximumFetchesPerMinute:120,maximumFetchesPerOriginPerMinute:30};function _ye(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function j4(e){return new O(`TOO_MANY_REQUESTS`,{error:`temporarily_unavailable`,error_description:e})}function vye(e,t){if(typeof e==`number`){if(!Number.isFinite(e)||e<0)throw new D(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`);return e*1e3}try{let t=Math.floor(Date.now()/1e3),n=(C$(e,t)-t)*1e3;if(!Number.isFinite(n)||n<0)throw Error(`negative duration`);return n}catch{throw new D(`cimd metadataFetchPolicy.${t} must be a non-negative number of seconds or duration string`)}}function M4(e,t){if(!Number.isInteger(e)||e<1)throw new D(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function yye(e){let t=e.metadataFetchPolicy;return{minimumFetchIntervalMs:vye(t?.minimumFetchInterval??A4.minimumFetchInterval,`minimumFetchInterval`),maximumConcurrentFetches:M4(t?.maximumConcurrentFetches??A4.maximumConcurrentFetches,`maximumConcurrentFetches`),maximumConcurrentFetchesPerOrigin:M4(t?.maximumConcurrentFetchesPerOrigin??A4.maximumConcurrentFetchesPerOrigin,`maximumConcurrentFetchesPerOrigin`),maximumFetchesPerMinute:M4(t?.maximumFetchesPerMinute??A4.maximumFetchesPerMinute,`maximumFetchesPerMinute`),maximumFetchesPerOriginPerMinute:M4(t?.maximumFetchesPerOriginPerMinute??A4.maximumFetchesPerOriginPerMinute,`maximumFetchesPerOriginPerMinute`)}}function N4(e,t){let n=t-6e4,r=0;for(;r<e.length&&e[r]<=n;)r+=1;r>0&&e.splice(0,r)}function bye(e,t){if(typeof e==`number`)return Math.max(0,e*1e3);let n=Math.floor(t/1e3);return Math.max(0,(C$(e,n)-n)*1e3)}function xye(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;for(let r of e?.split(`,`)??[]){let[e,...i]=r.trim().split(`=`),a=e?.toLowerCase();if(!a)continue;t.has(a)&&n.add(a);let o=i.join(`=`).trim();t.set(a,!o||o.replace(/^"|"$/g,``))}return{directives:t,duplicates:n}}function P4(e){if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Sye(e,t,n){let{directives:r,duplicates:i}=xye(e.cacheControl),a=e.vary?.split(`,`).some(e=>e.trim()===`*`);if(r.has(`no-store`)||r.has(`private`)||a)return{cacheable:!1,expiresAt:n};let o=bye(t,n);if(r.has(`no-cache`))return{cacheable:!0,expiresAt:n};let s=P4(e.age)??0,c=e.date?Date.parse(e.date):n,l=Number.isFinite(c)?Math.max(0,n-c):0,u=Math.max(l,s*1e3),d=null,f=r.has(`s-maxage`),p=P4(r.get(`s-maxage`)),m=r.has(`max-age`),h=P4(r.get(`max-age`)),g=f?p===null||i.has(`s-maxage`):m&&(h===null||i.has(`max-age`)),_=f?p:h;if(g)d=0;else if(_!==null)d=Math.max(0,_*1e3-u);else if(e.expires){let t=Date.parse(e.expires);Number.isFinite(t)&&(d=Math.max(0,t-(Number.isFinite(c)?c:n)-u))}return{cacheable:!0,expiresAt:n+Math.min(o,d??o)}}function Cye(e,t){return{cacheControl:t.cacheControl??e.cacheControl,vary:t.vary??e.vary,expires:t.expires??e.expires,date:t.date??e.date,age:t.age??e.age,etag:t.etag??e.etag,lastModified:t.lastModified??e.lastModified}}function wye(e,t,n,r){let i=Sye(t,n,r);return i.cacheable?{metadata:e,expiresAt:i.expiresAt,etag:t.etag,lastModified:t.lastModified,responseCacheHeaders:t}:null}function Tye(e){let t=e.metadataRevalidationInterval??`60m`,n=e.maxCacheEntries??1e3;if(!Number.isInteger(n)||n<1)throw new D(`cimd maxCacheEntries must be a positive integer`);let r=yye(e),i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=[],l=0,u=e=>{let t=i.get(e);if(t)return i.delete(e),i.set(e,t),t},d=(e,t)=>{for(i.delete(e);i.size>=n;){let e=i.keys().next().value;if(typeof e!=`string`)break;i.delete(e)}i.set(e,t)},f=(e,t)=>{if(!o.has(e))for(;o.size>=n;){let e=!1;for(let[n,i]of o)if(!a.has(n)&&!(r.minimumFetchIntervalMs>0&&t-i<r.minimumFetchIntervalMs)){o.delete(n),e=!0;break}if(!e)throw j4(`metadata fetch client state is at capacity`)}},p=(e,t)=>{let r=s.get(e);if(r)return N4(r.fetchStartTimesMs,t),s.delete(e),s.set(e,r),r;for(;s.size>=n;){let e=!1;for(let[n,r]of s)if(N4(r.fetchStartTimesMs,t),!(r.activeFetchCount>0||r.fetchStartTimesMs.length>0)){s.delete(n),e=!0;break}if(!e)throw j4(`metadata fetch origin state is at capacity`)}let i={activeFetchCount:0,fetchStartTimesMs:[]};return s.set(e,i),i},m=e=>{let t=Date.now(),n=o.get(e);if(r.minimumFetchIntervalMs>0&&n!==void 0&&t-n<r.minimumFetchIntervalMs)throw j4(`metadata document fetch is within the per-client minimum interval`);f(e,t);let i=new URL(e).origin,a=p(i,t);if(N4(c,t),l>=r.maximumConcurrentFetches)throw j4(`global metadata fetch concurrency limit exceeded`);if(a.activeFetchCount>=r.maximumConcurrentFetchesPerOrigin)throw j4(`metadata fetch concurrency limit exceeded for client origin`);if(c.length>=r.maximumFetchesPerMinute)throw j4(`global metadata fetch rate limit exceeded`);if(a.fetchStartTimesMs.length>=r.maximumFetchesPerOriginPerMinute)throw j4(`metadata fetch rate limit exceeded for client origin`);o.delete(e),o.set(e,t),c.push(t),a.fetchStartTimesMs.push(t),l+=1,a.activeFetchCount+=1;let s=!1;return()=>{s||(s=!0,--l,--a.activeFetchCount)}};return async(n,r,s)=>{if(!S4(r))return null;let c=n.context.getPlugin(`oauth-provider`);if(!c)throw new D(`cimd discovery invoked without the oauth-provider plugin installed`);let l=c.options,f=u(r),p=Date.now();if(f&&f.expiresAt>p)return s||k4(n,r,f.metadata,e,l);let h=a.get(r);if(h!==void 0)return h;let g=m(r),_=(async()=>{let a=await gye(n,r,e,f?{etag:f.etag,lastModified:f.lastModified}:void 0);if(a.status===`not-modified`&&!f)throw _ye(`Metadata document returned 304 without a validated cached document`);let c=a.status===`modified`?a.metadata:f.metadata,u=await k4(n,r,c,e,l,s??void 0),p=wye(c,a.status===`modified`?a.cacheHeaders:Cye(f.responseCacheHeaders,a.cacheHeaders),t,Date.now());return p?d(r,p):i.delete(r),o.delete(r),u})();a.set(r,_);try{return await _}catch(e){throw o.delete(r),o.set(r,Date.now()),e}finally{a.get(r)===_&&a.delete(r),g()}}}function Eye(e){return{id:E4,matches:S4,resolve:Tye(e),fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}}}const Dye=e=>{let t=Eye(e);return{id:`cimd`,version:`1.7.10`,init(e){yhe(e,{clientDiscovery:t})}}},Oye=/* @__PURE__ */ new Set([204,205,304]);function kye(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(Array.isArray(r))for(let e of r)t.append(n,e);else r!==void 0&&t.append(n,r);return t}const Aye=async(e,t)=>{let n=new Request(e,t),r=new URL(n.url);if(r.protocol!==`https:`)throw TypeError(`CIMD Node transport requires an HTTPS URL`);if(n.method!==`GET`&&n.method!==`HEAD`)throw TypeError(`CIMD Node transport supports only GET and HEAD`);let i=await _ee(r.hostname,{all:!0,verbatim:!0});if(i.length===0)throw TypeError(`metadata hostname returned no DNS addresses`);for(let e of i)if(!CY(e.address))throw TypeError(`metadata hostname must resolve only to public-routable addresses`);let a=i[0],o=Object.fromEntries(n.headers.entries());o.host=r.host;let s=t?.signal??(e instanceof Request?e.signal:n.signal);return new Promise((e,t)=>{let i=xt(r,{agent:!1,headers:o,method:n.method,servername:_t(r.hostname.replace(/^\[|\]$/g,``))===0?r.hostname:void 0,signal:s,lookup:(e,t,n)=>{t.all?n(null,[a]):n(null,a.address,a.family)}},t=>{let r=t.statusCode??500,i=n.method===`HEAD`||Oye.has(r)?null:mt.toWeb(t);e(new Response(i,{headers:kye(t.headers),status:r,statusText:t.statusMessage}))});i.once(`error`,t),i.end()})};function jye(e,t=8){let n=0;return(r,i)=>{let a=i?.signal??(r instanceof Request?r.signal:void 0);return a?.aborted?Promise.reject(a.reason):n>=t?Promise.reject(/* @__PURE__ */ Error(`CIMD transport capacity reached`)):(n++,new Promise((t,o)=>{let s=!1,c=()=>{s=!0,o(a?.reason)};a?.addEventListener(`abort`,c,{once:!0});let l=()=>{n--,a?.removeEventListener(`abort`,c)};Promise.resolve().then(()=>(a?.throwIfAborted(),e(r,i))).then(e=>{l(),s?e.body?.cancel().catch(()=>{}):t(e)},e=>{l(),o(e)})}))}}var F4=class e extends P()(`clankerauth/CimdTransport`){static layer=_f(e,{fetch:jye(Aye)});static layerWith=t=>t===void 0?e.layer:_f(e,{fetch:t})};const I4=`x-clankerauth-peer`,Mye=e=>gt({requestTimeout:15e3,headersTimeout:1e4},e),Nye=(e,t)=>{t.writeHead(503).end()},Pye=ym(`NodeHttp.listen`)(function*(e,t){let n=Nye,r=Mye((e,t)=>n(e,t)),i=op(e=>{r.close(()=>e(L)),r.closeAllConnections()});yield*qp(op(n=>{let i=e=>n(z(e));r.once(`error`,i),r.listen(e,t,()=>{r.off(`error`,i),n(L)})}),()=>i);let a=r.address();return a instanceof Object?{port:a.port,serve:e=>Jp(()=>i).pipe(hp(()=>I(()=>n=e)))}:yield*up(/* @__PURE__ */ Error(`Expected a TCP listener`))}),Fye=_h(65536),Iye=/^\/forward-auth(?:\?|$)/,Lye=(e,t,n)=>{let r=(e[`x-forwarded-for`]?.split(`,`).map(e=>e.trim()).filter(Boolean))?.at(-1);return n&&r?r:Ri(t,()=>`unknown`)},Rye=({baseURL:e,trustProxy:t})=>n=>R(function*(){let r=yield*pM,i=r.source,a=i instanceof ht?i.url:r.url;if(!a?.startsWith(`/`)||a.startsWith(`//`))return fA({status:400});let o=It(r.headers,Iye.test(a)?kg(`forwarded`):Ag([`forwarded`,`x-forwarded-host`,`x-forwarded-proto`]),Eg(`host`,new URL(e).host),Eg(I4,Lye(r.headers,r.remoteAddress,t)),kg(`x-forwarded-for`)),s=yield*n.pipe(Wp(pM,r.modify({headers:o})),Wp(qO,Fye));return i instanceof ht?HE(s.body).pipe(WE(`Stream`,e=>DA(s,cO(e.stream.pipe(kse(()=>I(()=>i.socket.destroy()))),e.contentType,e.contentLength))),qE(()=>s)):s}).pipe(tm),L4=e=>`${R4}${e}`,R4=`resource:`,z4=(e,t,n)=>e`DELETE FROM verification WHERE json_valid(value) AND json_extract(value, '$.type') = 'authorization_code' AND (${t} IS NULL OR json_extract(value, '$.query.client_id') = ${t}) AND (${n} IS NULL OR json_extract(value, '$.referenceId') = ${n})`,B4=ym(`Authorization.clear`)(function*(e,t){let n=t.clientId??null,r=t.resource===void 0?null:L4(t.resource);yield*e`DELETE FROM oauthConsent WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*z4(e,n,r),yield*e`DELETE FROM oauthAccessToken WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*e`DELETE FROM oauthRefreshToken WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`}),zye=hoe(W({message:Hx(U),error_description:Hx(U)})),Bye=e=>Ri(Wi(zye(e.body),e=>zi(e.message??e.error_description)),()=>`Request could not be completed`),V4=e=>new nV({message:e}),H4=e=>new XB({message:e}),U4=(e,t={})=>rp({try:e,catch:e=>{if(!Fq(e))return YB.of(e);let n=e.statusCode,r=n===400||n===422?t.refused:n===404?t.missing:n===409?t.conflict:n===503?t.unavailable:void 0;return r?r(Bye(e)):YB.of(e)}}),W4=(e,t)=>new TI({message:t,issues:[{path:e,message:t}]}),Vye=Mx(K(GV)),Hye=on(`RequestParseError`),Uye=e=>Vye(e)?e:rj(e)&&Hye(e.reason)?new rV({message:`Request body could not be read`}):YB.of(e),Wye=new Map(GV.map(e=>[e,gb(`httpApiStatus`)(e.ast)??500])),Gye=_A(K(GV)),G4=e=>{let t=Uye(e),n=GV.find(e=>Mx(e)(t));return Gye(t,{status:Wye.get(n)??500}).pipe(Ep)},K4=(e,t)=>e===t||e.endsWith(`.${t}`),Kye=e=>{try{return new URL(`https://${e}`).hostname===e&&e.includes(`.`)&&!_t(e)}catch{return!1}},q4=(e,t)=>e.protocol===`https:`||e.protocol===`http:`&&([`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||t),J4=`HTTPS origins (HTTP allowed on loopback, or anywhere with CLANKERAUTH_ALLOW_INSECURE_HTTP=true)`,Y4=(e,t)=>URL.canParse(e)&&new URL(e).origin===e&&q4(new URL(e),t),X4=H(function*(e){let{allowInsecureHttp:t,baseURL:n,cookieDomain:r}=e;return Y4(n,t)?_g(e.secret).length<32?yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BETTER_AUTH_SECRET must have at least 32 characters`)):e.mcpAllowedOrigins.every(e=>Y4(e,t))?r!==void 0&&(!Kye(r)||!K4(new URL(n).hostname,r))?yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_COOKIE_DOMAIN must be a bare parent domain of the CLANKERAUTH_BASE_URL host, such as home.example`)):e:yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_MCP_ALLOWED_ORIGINS must contain exact ${J4}`)):yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BASE_URL must be one of: ${J4}`))}),qye=R(function*(){let e={baseURL:yield*EE(`CLANKERAUTH_BASE_URL`),secret:yield*pce(`CLANKERAUTH_BETTER_AUTH_SECRET`),database:yield*EE(`CLANKERAUTH_DATABASE`).pipe(vE(`data/clankerauth.sqlite`)),host:yield*EE(`CLANKERAUTH_HOST`).pipe(vE(`127.0.0.1`)),port:yield*fce(`CLANKERAUTH_PORT`).pipe(vE(3e3)),mcpAllowedOrigins:yield*dce(WS,`CLANKERAUTH_MCP_ALLOWED_ORIGINS`).pipe(vE([])),trustProxy:yield*DE(`CLANKERAUTH_TRUST_PROXY`).pipe(vE(!1)),allowInsecureHttp:yield*DE(`CLANKERAUTH_ALLOW_INSECURE_HTTP`).pipe(vE(!1)),cookieDomain:yield*EE(`CLANKERAUTH_COOKIE_DOMAIN`).pipe(vE(void 0))};return yield*X4(e)});var Z4=class e extends P()(`clankerauth/Settings`){static layer=bf(e,qye)};const Q4=`Exactly one configured resource is required`,$4=[`offline_access`],Jye=tH(VS(G(U))),Yye=tH(W({identifier:U,name:U,allowedScopes:U})),e3=tH(G(OV)),t3=(e,t)=>[.../* @__PURE__ */ new Set([...$4,...t.flatMap(t=>e.find(e=>e.identifier===t)?.scopes??[])])],n3=ym(`ResourceCatalog.validateSelection`)(function*(e,t){let n=t.findIndex(t=>!e.some(e=>e.identifier===t));if(n!==-1)return yield*W4([`resources`,n],`Unknown Resource`)}),r3=ym(`ResourceCatalog.accessForClient`)(function*(e,t){return yield*e3(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource WHERE clientId = ${e} ORDER BY resourceId`)});var i3=class e extends P()(`clankerauth/ResourceCatalog`){static layer=bf(e,R(function*(){let{sql:e}=yield*aH,t=lV((yield*Z4).baseURL),n=ym(`ResourceCatalog.decode`)(function*(e){let n=yield*Yye(e),r=yield*Jye(n.allowedScopes);return{identifier:n.identifier,name:n.name,scopes:r.filter(e=>!$4.includes(e)),builtIn:n.identifier===t}}),r=ym(`ResourceCatalog.list`)(function*(){let t=yield*e`SELECT identifier, name, allowedScopes FROM oauthResource ORDER BY createdAt, identifier`;return yield*ep(t,n)}),i=ym(`ResourceCatalog.get`)(function*(t){let r=yield*e`SELECT identifier, name, allowedScopes FROM oauthResource WHERE identifier = ${t}`;return r[0]?yield*n(r[0]):void 0});return{list:r,get:i,application:e=>V(i(e),e=>e?.builtIn?void 0:e),access:ym(`ResourceCatalog.access`)(function*(){return yield*e3(yield*e`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource ORDER BY clientId, resourceId`)}),hasAccess:ym(`ResourceCatalog.hasAccess`)(function*(t,n){return(yield*e`SELECT 1 FROM oauthClient c WHERE c.clientId = ${t} AND (c.userId IS NULL
511
+ OR EXISTS (SELECT 1 FROM oauthClientResource l WHERE l.clientId = c.clientId AND l.resourceId = ${n}))`).length>0}),scopesFor:ym(`ResourceCatalog.scopesFor`)(function*(e){let t=yield*r();return yield*n3(t,e),t3(t,e)})}}))};const Xye=moe(W({typ:U,payload:tS(U,_C)})),Zye=e=>({id:`signer`,endpoints:{signDocument:X.serverOnly({method:`POST`,body:Xye},async t=>t.json({token:await E$(t,{options:e,header:{typ:t.body.typ},payload:t.body.payload})}))}}),Qye=e=>typeof e==`string`,$ye=(e,t,n,r,i,a)=>{let o={disableSettingJwtHeader:!0,jwt:{issuer:`${e.baseURL}/api/auth`},jwks:{keyPairConfig:{alg:`EdDSA`,crv:`Ed25519`}}},s=s4({loginPage:`/login`,consentPage:`/consent`,scopes:[...$4],resources:[{identifier:lV(e.baseURL),name:`clankerauth administration`,allowedScopes:[...$4,uV.read,uV.write]}],resourceSeedMode:`merge`,rateLimit:{register:{window:60,max:10}},postLogin:{page:`/consent`,shouldRedirect:()=>!1,consentReferenceId:async({scopes:e})=>{let t=await i4(),r=new URLSearchParams(t?.query),a=r.getAll(`resource`);if(a.length!==1||!await i(n.get(a[0])))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:Q4});let o=r.get(`client_id`);if(!o||!await i(n.hasAccess(o,a[0])))throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:`Client access is required`});let s=await i(n.scopesFor(a));if(e.some(e=>!s.includes(e)))throw new E(`BAD_REQUEST`,{error:`invalid_scope`,error_description:`Resource scopes changed; start authorization again`});return L4(a[0])}},grantTypes:[`authorization_code`,`refresh_token`],allowDynamicClientRegistration:!0,allowUnauthenticatedClientRegistration:!0,clientRegistrationRequirePKCE:!0,enforcePerClientResources:!1,accessTokenExpiresIn:900,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:30,codeExpiresIn:120,clientPrivileges:async({user:e,action:t})=>!!e&&t!==`configure-client-credentials-scopes`,resourcePrivileges:async({user:e})=>!!e});return{options:{appName:`clankerauth`,baseURL:e.baseURL,secret:_g(e.secret),database:{db:t,type:`sqlite`,transaction:!0},trustedOrigins:[e.baseURL],logger:{disabled:!0},disabledPaths:[`/token`],emailAndPassword:{enabled:!0,minPasswordLength:8,maxPasswordLength:128},databaseHooks:{user:{create:{before:async()=>{if(await a())throw new E(`CONFLICT`,{message:`Setup already completed`})}}}},hooks:{before:zq(async e=>{if(e.path===`/oauth2/register`){let t=e.body.redirect_uris;!e.body.application_type&&Array.isArray(t)&&t.some(e=>{if(!Qye(e))return!1;try{return new URL(e).protocol!==`https:`}catch{return!1}})&&(e.body.application_type=`native`),delete e.body.resources}})},session:{expiresIn:2592e3,updateAge:86400},advanced:{ipAddress:{ipAddressHeaders:[I4]}},rateLimit:{enabled:!0,storage:`database`,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:5}}},plugins:[$me({defaultPrefix:`clankerauth_`,maximumNameLength:100,enableSessionForAPIKeys:!1,keyExpiration:{defaultExpiresIn:null,minExpiresIn:0},rateLimit:{enabled:!1}}),lhe(o),Zye(o),s,Dye({fetchClientMetadataResource:r,metadataProfile:`mcp-2026-07-28`,metadataRevalidationInterval:300,maxCacheEntries:1e3,metadataFetchPolicy:{maximumConcurrentFetches:8,maximumConcurrentFetchesPerOrigin:2,maximumFetchesPerMinute:60,maximumFetchesPerOriginPerMinute:15}})]},oauthPlugin:s}};var a3=class e extends P()(`clankerauth/Issuer`){static layer=bf(e,R(function*(){let e=yield*Z4,{kysely:t}=yield*aH,n=yield*i3,{fetch:r}=yield*F4,i=gm(yield*Lp()),{options:a,oauthPlugin:o}=$ye(e,t,n,r,i,async()=>await(await SH((await s.$context).adapter)).count({model:`user`})>0),{auth:s,context:c}=yield*ym(`Auth.initialize`)(function*(){let e=yield*rp(()=>AQ(a));if(e.schemaProblems.length)return yield*z(/* @__PURE__ */ Error(`Database schema requires manual repair`));yield*rp(()=>e.runMigrations());let t=vme(a);return{auth:t,context:yield*rp(()=>t.$context)}},rm)();return{auth:s,context:c,publishScopes:e=>I(()=>{o.options.scopes=[...e]})}}))};const ebe=Nx(jV),tbe=Nx(W({id:U,key:U,referenceId:U,expiresAt:sS(eC),permissions:sS(VS(jV))})),o3=H(function*(e){return{keyId:e.id,name:e.name??``,enabled:e.enabled,permissions:yield*ebe(e.permissions??{}).pipe(bp(()=>vp(Sm(`An API key's stored permissions do not decode; it is listed with none`,{keyId:e.id}),{}))),expiresAt:e.expiresAt?xh(e.expiresAt):null,createdAt:xh(e.createdAt)}});var s3=class e extends P()(`clankerauth/ApiKeys`){static layer=bf(e,R(function*(){let{auth:e}=yield*a3,{sql:t}=yield*aH,n=yield*i3,r=ym(`ApiKeys.validate`)(function*(e){if(e!==void 0)for(let[t,r]of Object.entries(e)){let e=yield*n.get(t);if(e?.builtIn)return yield*W4([`permissions`,t],`Administration requires OAuth access tokens, not API keys`);if(!e||r.some(t=>!e.scopes.includes(t)))return yield*W4([`permissions`,t],`Select explicitly granted, currently available Resource scopes`)}});return{list:ym(`ApiKeys.list`)(function*(){let{providerHeaders:t}=yield*aV,n=yield*t,r=yield*U4(()=>e.api.listApiKeys({headers:n,query:{sortBy:`createdAt`,sortDirection:`asc`}}));return{keys:yield*ep(r.apiKeys,o3)}}),create:ym(`ApiKeys.create`)(function*(t){let n=yield*aV;yield*r(t.permissions);let i=t.expiresAt===null?null:(Th(t.expiresAt)-(yield*Nf))/1e3;if(i!==null&&i<1)return yield*W4([`expiresAt`],`Expiry must be in the future`);let a=yield*U4(()=>e.api.createApiKey({body:{userId:n.userId,name:t.name.trim(),permissions:La(t.permissions,e=>[...e]),expiresIn:i}}),{refused:V4});return{...yield*o3(a),key:a.key}}),update:ym(`ApiKeys.update`)(function*(t){let n=yield*aV;return yield*r(t.permissions),yield*o3(yield*U4(()=>e.api.updateApiKey({body:{userId:n.userId,keyId:t.keyId,name:t.name?.trim(),enabled:t.enabled,permissions:t.permissions&&La(t.permissions,e=>[...e])}}),{refused:V4,missing:()=>$B.of(t.keyId)}))}),delete:ym(`ApiKeys.delete`)(function*({keyId:t}){let{providerHeaders:n}=yield*aV,r=yield*n;return yield*U4(()=>e.api.deleteApiKey({headers:r,body:{keyId:t}}),{missing:()=>$B.of(t)}),{deleted:!0}}),keyList:ym(`ApiKeys.keyList`)(function*(r){let i=yield*Nf,a=(yield*n.application(r))?.scopes??[],o=a.length?yield*t`
512
+ SELECT id, key, referenceId, expiresAt, permissions FROM apikey
513
+ WHERE enabled = 1 AND (expiresAt IS NULL OR expiresAt > ${new Date(i).toISOString()})
514
+ `:[],s=yield*ep(o,e=>R(function*(){let t=yield*tbe(e),n=(t.permissions?.[r]??[]).filter(e=>a.includes(e));return n.length?[yield*rp(()=>Vde(new Uint8Array(Buffer.from(t.key,`base64url`)),r,{keyId:t.id,ownerId:t.referenceId,scopes:n,expiresAt:t.expiresAt===null?null:Th(t.expiresAt)}))]:[]}).pipe(bp(()=>vp(Sm(`An API key row cannot be listed; it is left out of key lists`,{keyId:e.id}),[])))),c=Math.floor(i/1e3),{token:l}=yield*U4(()=>e.api.signDocument({body:{typ:vI,payload:{aud:r,iat:c,exp:c+86400,keys:s.flat()}}}));return{list:l}})}}))};const c3=e=>e.userId===null,nbe=tH(G(W({userId:sS(U)}))),l3=ym(`Clients.requireManaged`)(function*(e,t){let[n]=yield*nbe(yield*t`SELECT userId FROM oauthClient WHERE clientId = ${e}`);if(!n)return yield*z(ZB.of(e));if(c3(n))return yield*z(eV.of(e))}),rbe=tH(G(W({clientId:U}))),u3=e=>({identifier:encodeURIComponent(e)}),ibe=e=>{try{return new URL(e).href===e&&!e.includes(`#`)}catch{return!1}},abe=ym(`Resources.validateInput`)(function*(e){let t=e.identifier.trim(),n=e.name.trim(),r=[...new Set(e.scopes.map(e=>e.trim()))];if(!ibe(t))return yield*W4([`identifier`],`Resource identifiers must be absolute URIs in canonical form, without a fragment`);let i=e.scopes.findIndex(e=>$4.includes(e.trim()));return i===-1?{identifier:t,name:n,scopes:r}:yield*W4([`scopes`,i],`offline_access is reserved`)});var d3=class e extends P()(`clankerauth/Resources`){static layer=bf(e,R(function*(){let{sql:e,transaction:t}=yield*aH,{auth:n,publishScopes:r}=yield*a3,i=yield*i3,a=yield*Sw(1),o=e=>a.withPermit(e),s=ym(`Resources.syncClient`)(function*(e,t,n){let r=yield*r3(n,e),i=JSON.stringify(t3(t,r.map(e=>e.resource)));yield*e`UPDATE oauthClient SET scopes = ${i}, updatedAt = ${yield*Nf} WHERE clientId = ${n} AND scopes IS NOT ${i}`}),c=ym(`Resources.synchronize`)(function*(){let t=yield*i.list(),n=t3(t,t.map(e=>e.identifier));yield*r(n),yield*e`UPDATE oauthClient SET scopes = ${JSON.stringify(n)}, updatedAt = ${yield*Nf} WHERE userId IS NULL AND scopes IS NOT ${JSON.stringify(n)}`;for(let n of yield*rbe(yield*e`SELECT clientId FROM oauthClient WHERE userId IS NOT NULL ORDER BY clientId`))yield*s(e,t,n.clientId)}),l=e=>e?.builtIn?z(W4([`identifier`],`The administration Resource is fixed`)):L,u=B(aV,e=>e.providerHeaders);yield*c();let d=ym(`Resources.link`)(function*(n,r){let a=yield*i.list();yield*n3(a,r);let o=yield*Nf;return yield*t(e=>R(function*(){let t=(yield*r3(n,e)).map(e=>e.resource);for(let i of t.filter(e=>!r.includes(e)))yield*e`DELETE FROM oauthClientResource WHERE clientId = ${n} AND resourceId = ${i}`,yield*B4(e,{clientId:n,resource:i});for(let t of r)yield*e`INSERT OR IGNORE INTO oauthClientResource (id, clientId, resourceId, createdAt)
515
+ VALUES (${crypto.randomUUID()}, ${n}, ${t}, ${new Date(o).toISOString()})`;yield*s(e,a,n)})),yield*r3(n,e)},o);return{link:d,get:ym(`Resources.get`)(function*({identifier:e}){return(yield*i.get(e))??(yield*QB.of(e))}),put:ym(`Resources.put`)(function*(e){let r=yield*abe(e),a=yield*i.get(r.identifier);yield*l(a);let o=yield*u,s=[...$4,...r.scopes];return a===void 0?(yield*t(e=>B4(e,{resource:r.identifier})),yield*U4(()=>n.api.adminCreateOAuthResource({headers:o,body:{identifier:r.identifier,name:r.name,allowedScopes:s}}),{refused:V4})):yield*U4(()=>n.api.adminUpdateOAuthResource({headers:o,params:u3(r.identifier),body:{name:r.name,allowedScopes:s}}),{refused:V4}),yield*c(),{resource:r,created:a===void 0}},o),delete:ym(`Resources.delete`)(function*({identifier:e}){yield*l(yield*i.get(e));let r=yield*u;return yield*U4(()=>n.api.adminDeleteOAuthResource({headers:r,params:u3(e)}),{missing:()=>QB.of(e)}),yield*t(t=>B4(t,{resource:e})),yield*c(),{deleted:!0}},o),setAccess:ym(`Resources.setAccess`)(function*({client_id:t,resources:n}){return yield*l3(t,e),{clientAccess:yield*d(t,n)}})}}))};const obe=tH(G(W({client_id:U,resource:U,scopes:VS(G(U)),approvedAt:sS(eC),refreshedAt:sS(eC)}))),sbe=tH(G(W({clientId:U,name:sS(U),redirectUris:VS(G(U)),tokenEndpointAuthMethod:sS(U),applicationType:sS(U),scopes:sS(VS(G(U))),grantTypes:sS(VS(G(U))),disabled:sS(Xx),clientDiscoveryId:sS(U),userId:sS(U)})));var f3=class e extends P()(`clankerauth/Clients`){static layer=bf(e,R(function*(){let{sql:e,transaction:t}=yield*aH,{auth:n}=yield*a3,{baseURL:r}=yield*Z4,i=yield*i3,a=yield*d3,o=ym(`Clients.exists`)(function*(e,t){if(!(yield*t`SELECT 1 FROM oauthClient WHERE clientId = ${e}`).length)return yield*z(ZB.of(e))}),s=ym(`Clients.revoke`)(function*(e,t,n){return yield*o(e,n),yield*B4(n,{clientId:e,resource:t}),{revoked:!0}}),c=ym(`Clients.connections`)(function*(){let t=new Date(yield*Nf).toISOString();return(yield*obe(yield*e`WITH live AS (
516
+ SELECT clientId, referenceId, scopes, createdAt FROM oauthRefreshToken
517
+ WHERE revoked IS NULL AND expiresAt > ${t}
518
+ ), held AS (
519
+ SELECT clientId, referenceId FROM oauthConsent
520
+ UNION SELECT clientId, referenceId FROM live
521
+ )
522
+ SELECT h.clientId AS client_id, r.identifier AS resource, c.updatedAt AS approvedAt,
523
+ COALESCE(c.scopes, (SELECT l.scopes FROM live l WHERE l.clientId = h.clientId
524
+ AND l.referenceId = h.referenceId ORDER BY l.createdAt DESC LIMIT 1)) AS scopes,
525
+ (SELECT MAX(l.createdAt) FROM live l WHERE l.clientId = h.clientId
526
+ AND l.referenceId = h.referenceId) AS refreshedAt
527
+ FROM held h
528
+ JOIN oauthResource r ON h.referenceId = ${R4} || r.identifier
529
+ LEFT JOIN oauthConsent c ON c.clientId = h.clientId AND c.referenceId = h.referenceId
530
+ ORDER BY client_id, resource`)).map(e=>({...e,scopes:e.scopes.filter(e=>!$4.includes(e))}))});return{connections:c,list:ym(`Clients.list`)(function*(){let{email:t}=yield*aV,n=yield*e`
531
+ SELECT clientId, name, redirectUris, tokenEndpointAuthMethod, applicationType, scopes,
532
+ grantTypes, disabled, clientDiscoveryId, userId
533
+ FROM oauthClient ORDER BY createdAt, clientId
534
+ `,a=(yield*sbe(n)).map(e=>({client_id:e.clientId,onboarding:e.clientDiscoveryId===null?c3(e)?`dcr`:`managed`:`cimd`,blocked:e.disabled===1,client_name:e.name??void 0,redirect_uris:e.redirectUris,token_endpoint_auth_method:e.tokenEndpointAuthMethod??void 0,application_type:e.applicationType,scope:e.scopes?.join(` `),grant_types:e.grantTypes??void 0})),o=yield*$f({resources:i.list(),clientAccess:i.access(),connections:c()});return{clients:a,resources:o.resources,clientAccess:o.clientAccess,connections:o.connections,email:t,issuer:`${r}/api/auth`}}),create:ym(`Clients.create`)(function*(e){let{providerHeaders:t}=yield*aV,r=yield*i.scopesFor(e.resources),o=yield*t,s=yield*U4(()=>n.api.adminCreateOAuthClient({headers:o,body:{client_name:e.client_name,redirect_uris:[...e.redirect_uris],token_endpoint_auth_method:e.token_endpoint_auth_method,application_type:e.application_type,grant_types:[`authorization_code`,`refresh_token`],scope:r.join(` `),skip_consent:!0}}),{refused:V4});return yield*a.link(s.client_id,e.resources).pipe(Dp(()=>U4(()=>n.api.deleteOAuthClient({headers:o,body:{client_id:s.client_id}})))),s}),update:ym(`Clients.update`)(function*(t){yield*l3(t.client_id,e);let{providerHeaders:r}=yield*aV,i=yield*r;return yield*U4(()=>n.api.updateOAuthClient({headers:i,body:{client_id:t.client_id,update:{client_name:t.client_name,redirect_uris:[...t.redirect_uris],application_type:t.application_type}}}),{refused:V4,missing:()=>ZB.of(t.client_id)})}),rotate:ym(`Clients.rotate`)(function*(t){yield*l3(t.client_id,e);let{providerHeaders:r}=yield*aV,i=yield*r;return yield*U4(()=>n.api.rotateClientSecret({headers:i,body:t}),{refused:V4,missing:()=>ZB.of(t.client_id)})}),revoke:({client_id:e,resource:n})=>t(t=>s(e,n,t)),delete:({client_id:e})=>t(t=>R(function*(){return yield*o(e,t),yield*z4(t,e,null),yield*t`DELETE FROM oauthClient WHERE clientId = ${e}`,{deleted:!0}})),block:({client_id:e,blocked:n})=>t(t=>R(function*(){return n?yield*s(e,void 0,t):yield*o(e,t),yield*t`UPDATE oauthClient SET disabled = ${+!!n}, updatedAt = ${yield*Nf} WHERE clientId = ${e}`,{blocked:n}}))}}))};const cbe=[`/`,`/resources`,`/keys`,`/login`,`/setup`,`/consent`],lbe=({readOnly:e,mcp:t})=>({readOnlyHint:e,destructiveHint:t.destructiveHint??!e,idempotentHint:t.idempotentHint??!1,openWorldHint:t.openWorldHint??!0}),p3=`~effect/ai/AiError/Reason`;var ube=class extends (/*#__PURE__*/ dC(`effect/ai/AiError/ToolParameterValidationError`)({_tag:/*#__PURE__*/ mS(`ToolParameterValidationError`),toolName:U,description:U})){[p3]=p3;get isRetryable(){return!0}get message(){return`Invalid parameters for tool '${this.toolName}': ${this.description}`}};const m3=`~effect/rpc/RpcMiddleware`,dbe=()=>(e,t)=>{let n=sr(),r;n!==0&&(cr(2),r=new globalThis.Error,cr(n));function i(){}let a=i;return Object.setPrototypeOf(i,Object.getPrototypeOf(P(e))),i.key=e,Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[m3]=m3,a.error=t?.error??qx,a.requiredForClient=t?.requiredForClient??!1,i},h3=(e,t)=>{let n=I(t);return Hx(e).pipe(woe({decode:hv(n),encode:uv()}),pS(n))},Z=e=>Hx(e).pipe(lS(Wx(Ux(e)),{decode:uv(),encode:pv(Wi(Bi))})),fbe=/*#__PURE__*/ K([U,CS]),g3=/*#__PURE__*/ K([U,CS]);var _3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(/*#__PURE__*/ nS(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ Z(g3)}),[q]))}))){},v3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){},y3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){};const pbe=U;({..._3.fields});var b3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({...v3.fields,nextCursor:/*#__PURE__*/ Z(pbe)}))){};const x3=/*#__PURE__*/ oS([`user`,`assistant`]);var S3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({audience:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),priority:/*#__PURE__*/ Z(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1}))),lastModified:/*#__PURE__*/ Z(U)}))){},C3=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/Icon`)({src:U,mimeType:/*#__PURE__*/ Z(U),sizes:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Z(/*#__PURE__*/ oS([`light`,`dark`]))})){},w3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),version:U,icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(C3)),description:/*#__PURE__*/ Z(U),websiteUrl:/*#__PURE__*/ Z(U)}))){},T3=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ClientCapabilities`)({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ tS(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ tS(/*#__PURE__*/ Kx([U,`/`,U]),_C)),roots:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Zx)})),sampling:/*#__PURE__*/ Z(/*#__PURE__*/ W({context:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({}))})),elicitation:/*#__PURE__*/ Z(/*#__PURE__*/ W({form:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),url:/*#__PURE__*/ Z(/*#__PURE__*/ W({}))}))})){},mbe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ tS(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ tS(/*#__PURE__*/ Kx([U,`/`,U]),_C)),logging:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),completions:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),prompts:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Zx)})),resources:/*#__PURE__*/ Z(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ Z(Zx),listChanged:/*#__PURE__*/ Z(Zx)})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Zx)}))}))){},E3=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/McpErrorBase`)({code:AS,message:U,data:/*#__PURE__*/ Z(Jx)})){};const D3=-32601,O3=-32602,k3=-32603,A3=-32020;var j3=class extends (/*#__PURE__*/ dC(`effect/ai/McpSchema/ParseError`)({...E3.fields,_tag:/*#__PURE__*/ mS(`ParseError`),code:/*#__PURE__*/ mS(-32700)})){},M3=class extends (/*#__PURE__*/ dC(`effect/ai/McpSchema/InvalidRequest`)({...E3.fields,_tag:/*#__PURE__*/ mS(`InvalidRequest`),code:/*#__PURE__*/ mS(-32600)})){},N3=class extends (/*#__PURE__*/ dC(`effect/ai/McpSchema/MethodNotFound`)({...E3.fields,_tag:/*#__PURE__*/ mS(`MethodNotFound`),code:/*#__PURE__*/ mS(D3)})){},P3=class extends (/*#__PURE__*/ dC(`effect/ai/McpSchema/InvalidParams`)({...E3.fields,_tag:/*#__PURE__*/ mS(`InvalidParams`),code:/*#__PURE__*/ mS(O3)})){},F3=class e extends (/*#__PURE__*/ dC(`effect/ai/McpSchema/InternalError`)({...E3.fields,_tag:/*#__PURE__*/ mS(`InternalError`),code:/*#__PURE__*/ mS(k3)})){static notImplemented=/*#__PURE__*/ new e({message:`Not implemented`})};const I3=/*#__PURE__*/ K([j3,M3,N3,P3,F3,E3]);var hbe=class extends (/*#__PURE__*/ J(`ping`,{success:/*#__PURE__*/ W({}),error:I3,payload:/*#__PURE__*/ cS(_3)})){},gbe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({...v3.fields,protocolVersion:U,capabilities:mbe,serverInfo:w3,instructions:/*#__PURE__*/ Z(U)}))){},_be=class extends (/*#__PURE__*/ J(`initialize`,{success:gbe,error:I3,payload:{..._3.fields,protocolVersion:U,capabilities:T3,clientInfo:w3}})){},L3=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...y3.fields,requestId:fbe,reason:/*#__PURE__*/ Z(U)}})){},R3=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...y3.fields,progressToken:g3,progress:CS,total:/*#__PURE__*/ Z(CS),message:/*#__PURE__*/ Z(U)}})){},vbe=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/Resource`)({uri:U,name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),mimeType:/*#__PURE__*/ Z(U),annotations:/*#__PURE__*/ Z(S3),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(C3)),size:/*#__PURE__*/ Z(AS),_meta:/*#__PURE__*/ Z(q)})){},z3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)}))){},ybe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({...z3.fields,text:U}))){},bbe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({...z3.fields,blob:qS}))){};({...b3.fields}),{...b3.fields},{...v3.fields},{..._3.fields};var B3=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ cS(y3)})){};({..._3.fields}),{..._3.fields};var V3=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...y3.fields,uri:U}})){},xbe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),required:/*#__PURE__*/ Z(Zx)}))){},Sbe=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/Prompt`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),arguments:/*#__PURE__*/ Z(/*#__PURE__*/ G(xbe)),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(C3)),_meta:/*#__PURE__*/ Z(q)})){},H3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({type:/*#__PURE__*/ mS(`text`),text:U,annotations:/*#__PURE__*/ Z(S3),_meta:/*#__PURE__*/ Z(q)}))){},U3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({type:/*#__PURE__*/ mS(`image`),data:qS,mimeType:U,annotations:/*#__PURE__*/ Z(S3),_meta:/*#__PURE__*/ Z(q)}))){},W3=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({type:/*#__PURE__*/ mS(`audio`),data:qS,mimeType:U,annotations:/*#__PURE__*/ Z(S3),_meta:/*#__PURE__*/ Z(q)}))){};const G3=/*#__PURE__*/ K([H3,U3,W3,class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({type:/*#__PURE__*/ mS(`resource`),resource:/*#__PURE__*/ K([ybe,bbe]),annotations:/*#__PURE__*/ Z(S3),_meta:/*#__PURE__*/ Z(q)}))){},class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({...vbe.fields,type:/*#__PURE__*/ mS(`resource_link`)}))){}]);({...b3.fields}),{...v3.fields},{..._3.fields};var K3=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ cS(y3)})){},Cbe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({title:/*#__PURE__*/ Z(U),readOnlyHint:/*#__PURE__*/ h3(Zx,Nt),destructiveHint:/*#__PURE__*/ h3(Zx,Mt),idempotentHint:/*#__PURE__*/ h3(Zx,Nt),openWorldHint:/*#__PURE__*/ h3(Zx,Mt)}))){};const q3=/*#__PURE__*/ nS(/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`object`),properties:/*#__PURE__*/ Z(/*#__PURE__*/ tS(U,q)),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),[q]),J3=q;var Y3=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/Tool`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),inputSchema:q3,outputSchema:/*#__PURE__*/ Z(J3),annotations:/*#__PURE__*/ Z(Cbe),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(C3)),_meta:/*#__PURE__*/ Z(q)})){};({...b3.fields});var X3=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/CallToolResult`)({...v3.fields,content:/*#__PURE__*/ G(G3),structuredContent:/*#__PURE__*/ Z(_C),isError:/*#__PURE__*/ Z(Zx)})){};({..._3.fields});var Z3=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ cS(y3)})){};const Q3=/*#__PURE__*/ oS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]);({..._3.fields});var $3=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:/*#__PURE__*/ W({...y3.fields,level:Q3,logger:/*#__PURE__*/ Z(U),data:Jx})})){};const e6=/*#__PURE__*/ K([H3,U3,W3,class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ToolUseContent`)({type:/*#__PURE__*/ mS(`tool_use`),id:U,name:U,input:/*#__PURE__*/ tS(U,Yx),_meta:/*#__PURE__*/ Z(q)})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ToolResultContent`)({type:/*#__PURE__*/ mS(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(G3),structuredContent:/*#__PURE__*/ Z(_C),isError:/*#__PURE__*/ Z(Zx),_meta:/*#__PURE__*/ Z(q)})){}]);var wbe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({role:x3,content:/*#__PURE__*/ K([e6,/*#__PURE__*/ G(e6)]),_meta:/*#__PURE__*/ Z(q)}))){},Tbe=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ToolChoice`)({mode:/*#__PURE__*/ Z(/*#__PURE__*/ oS([`auto`,`required`,`none`]))})){},Ebe=class extends (/*#__PURE__*/ gS()(/*#__PURE__*/ W({name:/*#__PURE__*/ Z(U)}))){},Dbe=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ModelPreferences`)({hints:/*#__PURE__*/ Z(/*#__PURE__*/ G(Ebe)),costPriority:/*#__PURE__*/ Z(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ Z(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ Z(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1})))})){},Obe=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/CreateMessageResult`)({role:x3,content:/*#__PURE__*/ K([e6,/*#__PURE__*/ G(e6)]),_meta:/*#__PURE__*/ Z(q),model:U,stopReason:/*#__PURE__*/ Z(U)})){},t6=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:Obe,error:I3,payload:{messages:/*#__PURE__*/ G(wbe),modelPreferences:/*#__PURE__*/ Z(/*#__PURE__*/ W(Dbe.fields)),systemPrompt:/*#__PURE__*/ Z(U),includeContext:/*#__PURE__*/ Z(/*#__PURE__*/ oS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ Z(CS),maxTokens:AS,stopSequences:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ Z(/*#__PURE__*/ tS(U,Yx)),tools:/*#__PURE__*/ Z(/*#__PURE__*/ G(/*#__PURE__*/ W(Y3.fields))),toolChoice:/*#__PURE__*/ Z(/*#__PURE__*/ W(Tbe.fields))}})){};({...v3.fields});var kbe=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/Root`)({uri:U,name:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)})){},n6=class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ListRootsResult`)({roots:/*#__PURE__*/ G(kbe)})){},r6=class extends (/*#__PURE__*/ J(`roots/list`,{success:n6,error:I3,payload:/*#__PURE__*/ cS(_3)})){};const Abe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Z(U),type:/*#__PURE__*/ mS(`object`),properties:/*#__PURE__*/ tS(U,/* @__PURE__ */ K([/* @__PURE__ */ K([class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/LegacyTitledEnum`)({type:/*#__PURE__*/ mS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),default:/*#__PURE__*/ Z(U)})){},/* @__PURE__ */ K([class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/UntitledSingleSelectEnum`)({type:/*#__PURE__*/ mS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/TitledSingleSelectEnum`)({type:/*#__PURE__*/ mS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),oneOf:/*#__PURE__*/ G(/*#__PURE__*/ W({const:U,title:U})),default:/*#__PURE__*/ Z(U)})){}]),/* @__PURE__ */ K([class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/UntitledMultiSelectEnum`)({type:/*#__PURE__*/ mS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(AS),maxItems:/*#__PURE__*/ Z(AS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ mS(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/TitledMultiSelectEnum`)({type:/*#__PURE__*/ mS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(AS),maxItems:/*#__PURE__*/ Z(AS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(/*#__PURE__*/ W({const:U,title:U}))}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){}])]),class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitationString`)({type:/*#__PURE__*/ mS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minLength:/*#__PURE__*/ Z(AS),maxLength:/*#__PURE__*/ Z(AS),format:/*#__PURE__*/ Z(/*#__PURE__*/ oS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitationNumber`)({type:/*#__PURE__*/ oS([`number`,`integer`]),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minimum:/*#__PURE__*/ Z(CS),maximum:/*#__PURE__*/ Z(CS),default:/*#__PURE__*/ Z(CS)})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitationBoolean`)({type:/*#__PURE__*/ mS(`boolean`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),default:/*#__PURE__*/ Z(Zx)})){}])),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),jbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitRequestFormParams`)({..._3.fields,mode:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(`form`)),message:U,requestedSchema:Abe})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitRequestURLParams`)({..._3.fields,mode:/*#__PURE__*/ Gx(`url`),message:U,elicitationId:U,url:U})){}]),Mbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitAcceptResult`)({...v3.fields,action:/*#__PURE__*/ Gx(`accept`),content:/*#__PURE__*/ Z(/*#__PURE__*/ tS(U,/*#__PURE__*/ K([U,CS,Zx,/*#__PURE__*/ G(U)])))})){},class extends (/*#__PURE__*/ uC(`@effect/ai/McpSchema/ElicitDeclineResult`)({...v3.fields,action:/*#__PURE__*/ oS([`cancel`,`decline`])})){}]);var i6=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Mbe,error:I3,payload:jbe})){},Nbe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};i6.payloadSchema;var a6=class extends (/*#__PURE__*/ jo(`McpReverseOperationUnsupported`)){},Pbe=class extends (/*#__PURE__*/ jo(`McpReverseOperationError`)){},o6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpRequestContext`)){},s6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpServerClient`)){},c6=class extends (/*#__PURE__*/ dbe()(`effect/ai/McpSchema/McpServerClientMiddleware`)){},Fbe=class extends (/*#__PURE__*/ _N(L3,R3,$3,V3,B3,Z3,K3,Nbe)){},l6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/EnabledWhen`)){};const u6={Complete:e=>({_tag:`Complete`,value:e}),InputRequired:e=>({_tag:`InputRequired`,...e})};var Ibe=class extends (/*#__PURE__*/ jo(`ResourceNotFound`)){},Lbe=class extends (/*#__PURE__*/ jo(`ToolNotFound`)){},Rbe=class extends (/*#__PURE__*/ jo(`InvalidToolInput`)){},zbe=class extends (/*#__PURE__*/ jo(`InvalidToolContinuation`)){},Bbe=class extends (/*#__PURE__*/ jo(`ToolExecutionError`)){},d6=class extends (/*#__PURE__*/ jo(`UnsupportedByProtocol`)){},Vbe=class extends (/*#__PURE__*/ jo(`PromptNotFound`)){};const f6=/*#__PURE__*/ Oo(),p6=/*#__PURE__*/ Oo(),Hbe=/*#__PURE__*/ I(()=>{let e=/* @__PURE__ */ new Map,t=[],n=[],r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{tools:{register:t=>I(()=>{e.set(t.descriptor.name,t)}),list:t=>I(()=>{let n=[];for(let r of e.values())r.isVisible(t)&&n.push(r.descriptor);return n}),call:(t,n)=>ap(()=>{let r=e.get(t.name);return r===void 0||!r.isVisible(n.protocol)?new Lbe({name:t.name}):r.handle(t,n)})},resources:{register:e=>I(()=>{let n=t.findIndex(t=>t.descriptor.uri===e.descriptor.uri);n===-1?t.push(e):t[n]=e}),registerTemplate:e=>I(()=>{let t=n.findIndex(t=>t.descriptor.uriTemplate===e.descriptor.uriTemplate);t===-1?n.push(e):n[t]=e}),list:e=>I(()=>t.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),listTemplates:e=>I(()=>n.filter(t=>t.isVisible(e)).map(e=>e.descriptor)),read:H(function*(e,r){let i=t.find(t=>t.descriptor.uri===e);if(i!==void 0&&i.isVisible(r.protocol))return yield*i.read(r);for(let t of n){let n=t.match(e);if(n!==void 0&&t.isVisible(r.protocol))return yield*t.read(e,n,r)}return yield*new Ibe({uri:e})})},prompts:{register:e=>I(()=>{r.set(e.descriptor.name,e)}),list:e=>I(()=>Array.from(r.values()).filter(t=>t.isVisible(e)).map(e=>e.descriptor)),get:H(function*(e,t,n){let i=r.get(e);return i===void 0||!i.isVisible(n.protocol)?yield*new Vbe({name:e}):yield*i.get(t,n)})},completions:{register:(e,t)=>I(()=>{i.set(e,t)}),complete:H(function*(e,t){let n=e.reference.type===`prompt`?`prompt/${e.reference.name}/${e.argument.name}`:`resource/${e.reference.uriTemplate}/${e.argument.name}`,r=i.get(n);if(r===void 0)return yield*new P3({message:`Unknown completion reference or argument`});let a=yield*r(e,t),o=ste(a.values,100);return{...a,values:o,hasMore:a.hasMore===!0||o.length<a.values.length}})},registrationPresence:I(()=>({tools:e.size>0,resources:t.length>0||n.length>0,prompts:r.size>0}))}}),Ube=/*#__PURE__*/ new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),m6={debug:{effect:`Debug`,order:0},info:{effect:`Info`,order:1},notice:{effect:`Info`,order:2},warning:{effect:`Warn`,order:3},error:{effect:`Error`,order:4},critical:{effect:`Fatal`,order:5},alert:{effect:`Fatal`,order:6},emergency:{effect:`Fatal`,order:7}},h6=e=>{let t=e.startsWith(`=?base64?`),n=e.endsWith(`?=`);if(!t||!n)return/^[\t\x20-\x7e]*$/.test(e)?e:void 0;let r=Oh(e.slice(9,-2));if(!Na(r))try{return Ube.decode(r.success)}catch{return}},g6=e=>({protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.initializePayload._meta}),_6=e=>({clientId:e.clientId,protocol:g6(e),requestContext:o6.of({clientId:e.clientId,protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata}),serverClient:e}),v6=e=>({clientId:e.clientId,protocol:{protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata},requestContext:e}),y6=(e,t)=>t._tag===`Complete`?F(t.value):z(new d6({protocolVersion:e,feature:`Client input`})),b6=e=>{let{content:t,structuredContent:n}=e;if(typeof n!=`string`||t.length!==1)return t;let[r]=t;return r.type===`text`&&r.text===JSON.stringify(n)?[{...r,text:n}]:t},x6=e=>rn(e)&&(e.type===`tool_use`||e.type===`tool_result`),S6=e=>rn(e)?e.tools!==void 0||e.toolChoice!==void 0?!0:Array.isArray(e.messages)?e.messages.some(e=>{if(!rn(e))return!1;let t=e.content;return Array.isArray(t)?t.some(x6):x6(t)}):!1:!1;var C6=class e extends (/*#__PURE__*/ jo(`ProtocolError`)){static fromTool(t){let n=HE(t).pipe(WE(`ToolNotFound`,e=>`Tool '${e.name}' not found`),WE(`UnsupportedByProtocol`,e=>`${e.feature} is not supported by MCP ${e.protocolVersion}`),GE({InvalidToolInput:e=>e.message,InvalidToolContinuation:e=>e.message,ToolExecutionError:e=>e.message}),JE);return new e({code:t._tag===`ToolExecutionError`?k3:O3,message:n})}static fromFeature(t){if(N(t,`_tag`)){if(t._tag===`PromptNotFound`&&N(t,`name`)&&Ut(t.name))return new e({code:O3,message:`Prompt '${t.name}' not found`});if(t._tag===`ResourceNotFound`&&N(t,`uri`)&&Ut(t.uri))return new e({code:-32002,message:`Resource '${t.uri}' not found`})}let n=Wbe(t);return Pa(n)?new e(n.success):new e({code:k3,message:`MCP feature handler failed`})}};const Wbe=/*#__PURE__*/ goe(/* @__PURE__ */ W({code:CS,message:U,data:/*#__PURE__*/ Hx(Yx)})),Gbe=e=>on(e,`McpReverseOperationUnsupported`),w6=e=>t=>Gbe(t)?t:new Pbe({operation:e,cause:t}),T6=(e,t,n)=>Lx(e)(n).pipe(B(Nx(t))),Kbe=(e,t,n)=>Lx(e)(n).pipe(B(Nx(t,{onExcessProperty:`error`}))),E6=/*#__PURE__*/ ym(function*(e,t){return p6.$match(t,{Cancelled:e=>({tag:L3._tag,payload:L3.payloadSchema.make({_meta:e.metadata,requestId:e.requestId,reason:e.reason})}),Progress:t=>({tag:R3._tag,payload:R3.payloadSchema.make({_meta:t.metadata,progressToken:t.progressToken,progress:t.progress,total:t.total,message:e.supportsProgressMessage?t.message:void 0})}),LoggingMessage:e=>({tag:$3._tag,payload:$3.payloadSchema.make({_meta:e.metadata,level:e.level,logger:e.logger,data:e.data})}),ResourceUpdated:e=>({tag:V3._tag,payload:V3.payloadSchema.make({_meta:e.metadata,uri:e.uri})}),ResourcesChanged:e=>({tag:B3._tag,payload:B3.payloadSchema.make({_meta:e.metadata})}),ToolsChanged:e=>({tag:Z3._tag,payload:Z3.payloadSchema.make({_meta:e.metadata})}),PromptsChanged:e=>({tag:K3._tag,payload:K3.payloadSchema.make({_meta:e.metadata})}),ElicitationComplete:()=>void 0})}),D6=e=>{switch(e._tag){case`ToolsChanged`:case`PromptsChanged`:case`ResourcesChanged`:case`ResourceUpdated`:return!0;default:return!1}},O6=e=>{let t=/* @__PURE__ */ new WeakMap,n=e=>{let n=t.get(e);if(n===void 0){let r=mC(e.payloadSchema);n={decode:Nx(r),encode:Ix(r)},t.set(e,n)}return n},r=(t,n,r)=>e.handlerRpcs===void 0||e.makeHandlers===void 0?L:n===void 0&&e.runtime._tag===`Stateful`?up(`MCP sessionful handler installation requires a lifecycle runtime`):r.install(e,e.handlerRpcs,e.makeHandlers(t,e.runtime._tag===`Stateful`?n:void 0,r.context)),i=t=>Ale(e.serverRequestRpcs,{spanPrefix:`McpServer/Client`}).pipe(V(n=>e.toReverseClient(t,n)));return{...e,payloadCodecs:n,installHandlers:r,makeReverseClient:i}},k6=e=>`@effect/mcp/${encodeURIComponent(e.protocolVersion)}/`,qbe=/*#__PURE__*/ H(function*(e){if(e.length===0)return yield*new hd(`MCP protocol declaration must contain at least one MCP protocol`);let t=Object.freeze(Array.from(e)),n=/* @__PURE__ */ new Map;for(let e of t){if(n.has(e.protocolVersion))return yield*new hd(`Duplicate MCP protocol version: ${e.protocolVersion}`);n.set(e.protocolVersion,e)}let r=t[0].clientRpcs.prefix(k6(t[0]));for(let e=1;e<t.length;e++)r=r.merge(t[e].clientRpcs.prefix(k6(t[e])));return{protocols:t,clientRpcs:r,select:e=>n.get(e)??t[0],protocolForInternalTag:e=>t.find(t=>e.startsWith(k6(t)))??t[0],routeClientRequest:(e,t)=>({...t,tag:`${k6(e)}${t.tag}`}),handlerTarget:(e,t)=>({context:t,install:H(function*(t,n,i){let a=yield*n.toHandlers(i);for(let i of n.requests.values()){let n=r.requests.get(`${k6(t)}${i._tag}`),o=a.mapUnsafe.get(i.key);if(n===void 0||o===void 0)return yield*up(`MCP handler registration invariant failed for ${t.protocolVersion}/${i._tag}`);e.set(n.key,o)}})})}}),A6=e=>({initializePayload:e.initializePayload,negotiatedProfile:e.negotiatedProfile,protocol:e.protocol,resourceSubscriptions:e.supportsResourceSubscriptions?/* @__PURE__ */ new Set:void 0,logLevel:{_tag:`Effect`,level:e.logLevel}}),Jbe=()=>{let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=(n,r)=>{let i=r[`mcp-session-id`];return i===void 0?t.get(n):e.get(i)};return{registerHttp:(t,n)=>{let r=A6(n);return e.set(t,r),r},registerConnection:(e,n)=>{let r=A6(n);return t.set(e,r),r},resolve:r,resolveSessionId:t=>e.get(t),terminateSession:t=>e.delete(t),setLogLevel:(e,t,n)=>I(()=>{let i=r(t,n);i!==void 0&&(i.logLevel={_tag:`Mcp`,level:e})}),subscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?z(new C6({code:D3,message:`Resource subscriptions are not supported`})):I(()=>i.add(e)).pipe(yp)},unsubscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?z(new C6({code:D3,message:`Resource subscriptions are not supported`})):I(()=>i.delete(e)).pipe(yp)},effectLogLevel:(e,t,n)=>{let i=r(e,t);return i?.logLevel._tag===`Mcp`?m6[i.logLevel.level].effect:i?.logLevel.level??n},canDeliver:(e,t,n,i)=>{let a=r(e,t);if(n._tag===`LoggingMessage`){let e=a?.logLevel;return e?._tag===`Mcp`?m6[n.level].order>=m6[e.level].order:rce(m6[n.level].effect,e?.level??i)}return n._tag!==`ResourceUpdated`||a?.resourceSubscriptions?.has(n.uri)===!0},markInitialized:e=>{n.add(e)},initializedClientIds:()=>n.values(),disconnect:e=>{t.delete(e),n.delete(e)}}},j6=`mcp-session-id`,M6=`mcp-protocol-version`,N6=`io.modelcontextprotocol/protocolVersion`,P6=`io.modelcontextprotocol/clientCapabilities`,F6=-32022,I6=e=>typeof e==`object`&&e?e:void 0,L6=e=>{let t=I6(e);return t!==void 0&&N6 in t?{present:!0,value:t[N6]}:{present:!1,value:void 0}},Ybe=e=>L6(I6(I6(e)?.params)?._meta).present,Xbe=e=>{switch(e){case`tools/call`:case`prompts/get`:return`name`;case`resources/read`:return`uri`;default:return}},R6=e=>({_tag:`Rejected`,status:400,error:{code:A3,message:e}}),z6=/*#__PURE__*/ _N(hbe),B6=e=>({_tag:`Stateful`,transport:e});var V6=class extends (/*#__PURE__*/ P()(`effect/ai/McpRuntime/ServerRuntime`)){};const H6=(e,t)=>e.find(e=>e.runtime._tag===`Stateful`&&e.protocolVersion===t)??e.find(e=>e.runtime._tag===`Stateful`),Zbe=/*#__PURE__*/ H(function*(e){let t=e.find(e=>e.runtime._tag===`Stateful`)===void 0?void 0:Jbe(),n=e.map(e=>e.protocolVersion),r,i;for(let t of e)if(t.runtime._tag===`Stateless`){if(r!==void 0)return yield*new hd(`MCP runtime supports at most one stateless protocol`);r=t.runtime,i=t}let a=yield*qbe(e),o=/* @__PURE__ */ new Set,s=e=>({code:F6,message:`Unsupported protocol version '${e}'`,data:{supported:n,requested:e}}),c=(e,r)=>{let i=e[M6],a=e[j6],o=a===void 0?void 0:t?.resolveSessionId(a);if(a!==void 0&&o===void 0)return{_tag:`Rejected`,status:404};if(!r&&i!==void 0){if(!n.includes(i))return{_tag:`Rejected`,status:400,error:s(i)};if(o?.protocol.runtime.transport.http.requiresVersionHeader===!0&&i!==o.protocol.protocolVersion)return R6(`MCP-Protocol-Version header '${i}' does not match negotiated protocol version '${o.protocol.protocolVersion}'`)}return{_tag:`Accepted`,binding:o,protocol:o?.protocol}},l=(e,n)=>{let r=e[M6],a=I6(n),o=I6(I6(a?.params)?._meta),l=L6(o),u=a?.id,d=a?.jsonrpc===`2.0`&&a.method===`initialize`&&(typeof u==`string`||typeof u==`number`),f=a?.jsonrpc===`2.0`&&a.method===`notifications/cancelled`&&u===void 0;if(l.present||(!d||t===void 0)&&i!==void 0&&(r===i.protocolVersion||t===void 0&&a?.jsonrpc===`2.0`&&typeof a.method==`string`&&(typeof u==`string`||typeof u==`number`))){if(r===void 0)return R6(`MCP-Protocol-Version header is required`);if(!f&&(o===void 0||typeof l.value!=`string`))return{_tag:`Rejected`,status:400,error:{code:O3,message:`Required request metadata is missing`}};if((!f||l.present)&&l.value!==r)return R6(`MCP-Protocol-Version header does not match request metadata`);if(!f&&I6(o?.[P6])===void 0)return{_tag:`Rejected`,status:400,error:{code:O3,message:`${P6} request metadata is required`}};if(i===void 0||r!==i.protocolVersion)return{_tag:`Rejected`,status:400,error:s(r)};let t=a?.method;if(typeof t!=`string`||e[`mcp-method`]!==t)return R6(`Mcp-Method header does not match request method`);let n=Xbe(t);if(n!==void 0){let t=I6(a?.params)?.[n],r=e[`mcp-name`];if(typeof t!=`string`||r===void 0||h6(r)!==t)return R6(`Mcp-Name header does not match request parameters`)}return{_tag:`Accepted`,binding:void 0,protocol:i}}return c(e,d)};return V6.of({protocols:a.protocols,clientRpcs:a.clientRpcs,selectProtocol:a.select,protocolForInternalTag:a.protocolForInternalTag,routeClientRequest:a.routeClientRequest,prepareRequest:H(function*(e,n,o){let c=I6(o.payload)?._meta,l=L6(c),u=typeof l.value==`string`?l.value:void 0,d=l.present?void 0:t?.resolve(e,n),f;if(l.present)f=a.protocols.find(e=>e.protocolVersion===u)??i??a.protocols[0];else if(d!==void 0)f=d.protocol;else if(o.tag===`initialize`){let e=o.payload?.protocolVersion,t=H6(a.protocols,e);if(t===void 0)return yield*new C6({code:F6,message:`initialize is not supported by the configured MCP protocols (requested '${e}')`});f=t}else f=o.tag===`ping`?H6(a.protocols,void 0)??a.protocols[0]:a.protocols[0];if(f.runtime._tag===`Stateful`)return{protocol:f,binding:d};if(o.isNotification&&o.tag===`notifications/cancelled`)return{protocol:f};if(r===void 0)return yield*up(`MCP stateless runtime invariant failed`);if(u!==void 0&&u!==f.protocolVersion)return yield*new C6(s(u));let p=yield*r.profileFromRequestMetadata(c),m={protocolVersion:p.protocolVersion,clientCapabilities:p.clientCapabilities,clientInfo:p.clientInfo,requestMetadata:p.requestMetadata},h=o6.of({clientId:e,protocolVersion:m.protocolVersion,clientCapabilities:m.clientCapabilities,clientInfo:m.clientInfo,requestMetadata:m.requestMetadata});return{protocol:f,profile:m,requestContext:h}}),resolveRequest:(e,n)=>t?.resolve(e,n),admitHttp:(e,r)=>{let i=(e,t,n=null)=>({_tag:`Rejected`,response:t===void 0?fA({status:e}):vA({jsonrpc:`2.0`,id:n,error:t},{status:e})});if(Na(r)){let t=e[M6];if(t!==void 0&&!n.includes(t))return i(400,s(t));let r=l(e,void 0);return r._tag===`Rejected`&&(r.error===void 0||r.error.code===-32020)?i(r.status,r.error):i(200,new j3({message:`Parse error`}))}let a=r.success;if(Array.isArray(a)){if(a.length===0)return i(400,new M3({message:`Invalid Request`}));let t=l(e,a);return t._tag===`Rejected`||a.some(Ybe)||a.some(e=>N(e,`method`)&&e.method===`initialize`)||t.binding?.protocol.runtime.transport.jsonRpc.acceptsBatches!==!0?i(400):{_tag:`Accepted`,acknowledge:!a.some(e=>N(e,`method`)&&N(e,`id`)),isSubscription:!1}}let o=N(a,`id`),c=o&&(typeof a.id==`string`||typeof a.id==`number`)?a.id:null,u=N(a,`jsonrpc`)&&a.jsonrpc===`2.0`,d=!o||typeof a.id==`string`||typeof a.id==`number`,f=u&&d&&N(a,`method`)&&typeof a.method==`string`,p=o&&(typeof a.id==`string`||typeof a.id==`number`||a.id===null),m=N(a,`result`),h=N(a,`error`),g=u&&p&&m!==h,_=l(e,a);if(_._tag===`Rejected`)return i(_.status,_.error,c);if(!f&&!g)return i(200,new M3({message:`Invalid Request`}),c);let v=N(a,`method`)&&a.method===`initialize`,y=e[j6]!==void 0;return v&&y?i(400,new M3({message:`initialize must not include an MCP-Session-Id header`}),c):!v&&!y&&_.protocol?.runtime._tag!==`Stateless`?i(400,t===void 0?void 0:new M3({message:`MCP-Session-Id header is required; send initialize to start a session`}),c):f&&_.protocol?.runtime._tag===`Stateless`&&!(_.protocol.handlerRpcs?.requests.has(a.method)??_.protocol.clientRpcs.requests.has(a.method))?i(404,new N3({message:`Method not found: ${a.method}`}),c):{_tag:`Accepted`,acknowledge:!f||!o,isSubscription:N(a,`method`)&&a.method===`subscriptions/listen`}},effectLogLevel:(e,n,r)=>t?.effectLogLevel(e,n,r)??r,disconnect:e=>t?.disconnect(e),terminateHttpSession:e=>ap(()=>{let n=e[j6];if(n===void 0)return F(fA({status:400}));let r=c(e,!1);if(r._tag===`Rejected`)return F(fA({status:r.status}));let i=r.binding;return t.terminateSession(n),vp(ep(o,e=>e(i),{discard:!0}),fA({status:204}))}),onSessionTerminated:e=>qp(I(()=>{o.add(e)}),()=>I(()=>{o.delete(e)})),deliveryClientIds:()=>t?.initializedClientIds()??[],canDeliver:(e,n,r,i)=>t?.canDeliver(e,n,r,i)??!0,installHandlers:H(function*(e){let r=/* @__PURE__ */ new Map,i={subscribeServerNotifications:e.subscribeServerNotifications,getListChangeRevision:e.getListChangeRevision,...e.sendNotification===void 0?{}:{sendNotification:e.sendNotification},...e.markSubscriptionCancelled===void 0?{}:{markSubscriptionCancelled:e.markSubscriptionCancelled},...e.terminateSubscription===void 0?{}:{terminateSubscription:e.terminateSubscription},supportedVersions:n,serverInfo:e.serverInfo,registrationPresence:e.core.registrationPresence},o=a.handlerTarget(r,i);for(let n of a.protocols){if(n.runtime._tag===`Stateless`){yield*n.installHandlers(e.core,void 0,o);continue}if(t===void 0)return yield*up(`MCP sessionful runtime invariant failed`);yield*o.install(n,z6,z6.of({ping:()=>F({})}));let r={initialize:H(function*(r,i,a){let o=yield*e.core.registrationPresence;return yield*fp(s=>{let c=ha(s.context,pM),l={completions:!0,logging:!0,...o.tools?{tools:{listChanged:!0}}:{},...o.resources?{resources:{listChanged:!0,subscribe:c===void 0}}:{},...o.prompts?{prompts:{listChanged:!0}}:{},...e.serverInfo.extensions?{extensions:e.serverInfo.extensions}:{}},u={initializePayload:_be.payloadSchema.make({protocolVersion:r,capabilities:i.clientCapabilities,clientInfo:i.clientInfo,_meta:i.requestMetadata}),negotiatedProfile:i,protocol:n,supportsResourceSubscriptions:c===void 0&&l.resources?.subscribe===!0,logLevel:e.defaultLogLevel};if(c!==void 0){let e=crypto.randomUUID();t.registerHttp(e,u),xM(c,(t,r)=>F(wA(r,{[j6]:e,[M6]:n.protocolVersion})))}else t.registerConnection(a,u);return F({capabilities:l,instructions:e.serverInfo.instructions,serverInfo:w3.make({name:e.serverInfo.name,version:e.serverInfo.version,description:e.serverInfo.description,websiteUrl:e.serverInfo.websiteUrl,icons:e.serverInfo.icons})})})}),setLogLevel:t.setLogLevel,subscribe:t.subscribe,unsubscribe:t.unsubscribe,clientNotification:H(function*(e,n){e._tag===`Initialized`&&t.markInitialized(n)})};yield*n.installHandlers(e.core,r,o)}return ra(r)})})}),U6=e=>bf(V6)(Zbe(e)),W6=e=>Hx(e).pipe(lS(Wx(Ux(e)),{decode:uv(),encode:pv(Wi(Bi))})),G6=q,Qbe=/*#__PURE__*/ K([U,CS]),K6=/*#__PURE__*/ K([U,CS]),q6=/*#__PURE__*/ oS([`user`,`assistant`]),J6=/*#__PURE__*/ oS([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Y6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ W6(/*#__PURE__*/ nS(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ W6(K6)}),[q]))}),X6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ W6(G6)}),Z6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ W6(G6)}),Q6=/*#__PURE__*/ W({...Y6.fields,cursor:/*#__PURE__*/ W6(U)}),$6=/*#__PURE__*/ W({...Z6.fields,nextCursor:/*#__PURE__*/ W6(U)}),$be=/*#__PURE__*/ W({extensions:/*#__PURE__*/ W6(/*#__PURE__*/ tS(/*#__PURE__*/ Kx([U,`/`,U]),_C)),experimental:/*#__PURE__*/ W6(/*#__PURE__*/ tS(U,G6)),roots:/*#__PURE__*/ W6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ W6(Zx)})),sampling:/*#__PURE__*/ W6(G6)}),exe=/*#__PURE__*/ W({extensions:/*#__PURE__*/ W6(/*#__PURE__*/ tS(/*#__PURE__*/ Kx([U,`/`,U]),_C)),experimental:/*#__PURE__*/ W6(/*#__PURE__*/ tS(U,G6)),logging:/*#__PURE__*/ W6(G6),prompts:/*#__PURE__*/ W6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ W6(Zx)})),resources:/*#__PURE__*/ W6(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ W6(Zx),listChanged:/*#__PURE__*/ W6(Zx)})),tools:/*#__PURE__*/ W6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ W6(Zx)}))}),e8=/*#__PURE__*/ W({code:AS,message:U,data:/*#__PURE__*/ W6(Jx)}),t8=/*#__PURE__*/ W({audience:/*#__PURE__*/ W6(/*#__PURE__*/ G(q6)),priority:/*#__PURE__*/ W6(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1})))}),txe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ W6(U),text:U}),nxe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ W6(U),blob:U}),rxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`text`),text:U,annotations:/*#__PURE__*/ W6(t8)}),ixe=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`image`),data:U,mimeType:U,annotations:/*#__PURE__*/ W6(t8)}),axe=/*#__PURE__*/ W({uri:U,name:U,description:/*#__PURE__*/ W6(U),mimeType:/*#__PURE__*/ W6(U),size:/*#__PURE__*/ W6(CS),annotations:/*#__PURE__*/ W6(t8)}),oxe=/*#__PURE__*/ W({uriTemplate:U,name:U,description:/*#__PURE__*/ W6(U),mimeType:/*#__PURE__*/ W6(U),annotations:/*#__PURE__*/ W6(t8)}),n8=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ W6(U),required:/*#__PURE__*/ W6(Zx)}),sxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ W6(U),arguments:/*#__PURE__*/ W6(/*#__PURE__*/ G(n8))}),cxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ W6(U),inputSchema:/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`object`),properties:/*#__PURE__*/ W6(/*#__PURE__*/ tS(U,G6)),required:/*#__PURE__*/ W6(/*#__PURE__*/ G(U))})}),r8=/*#__PURE__*/ W({hints:/*#__PURE__*/ W6(/*#__PURE__*/ G(/* @__PURE__ */ W({name:/*#__PURE__*/ W6(U)}))),costPriority:/*#__PURE__*/ W6(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ W6(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ W6(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1})))}),lxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`ref/prompt`),name:U}),i8=/*#__PURE__*/ W({uri:U,name:/*#__PURE__*/ W6(U)});({...Z6.fields}),{...$6.fields},{...$6.fields},{...Z6.fields},{...$6.fields},{...Z6.fields},{...$6.fields},{...Z6.fields},{...Z6.fields};const uxe=/*#__PURE__*/ W({...Z6.fields,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U),total:/*#__PURE__*/ W6(CS),hasMore:/*#__PURE__*/ W6(Zx)})}),dxe=/*#__PURE__*/ W({...Z6.fields,roots:/*#__PURE__*/ G(i8)});var a8=class extends (/*#__PURE__*/ J(`ping`,{success:Z6,error:e8,payload:/*#__PURE__*/ cS(Y6)})){};({...Y6.fields}),{...Y6.fields};var o8=class extends (/*#__PURE__*/ J(`logging/setLevel`,{success:Z6,error:e8,payload:{...Y6.fields,level:J6}})){};({...Y6.fields}),{...Y6.fields};var s8=class extends (/*#__PURE__*/ J(`resources/subscribe`,{success:Z6,error:e8,payload:{...Y6.fields,uri:U}})){},c8=class extends (/*#__PURE__*/ J(`resources/unsubscribe`,{success:Z6,error:e8,payload:{...Y6.fields,uri:U}})){};({...Y6.fields}),{...Y6.fields};var l8=class extends (/*#__PURE__*/ J(`roots/list`,{success:dxe,error:e8,payload:/*#__PURE__*/ cS(Y6)})){},u8=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...X6.fields,requestId:Qbe,reason:/*#__PURE__*/ W6(U)}})){};({...X6.fields});var d8=class extends (/*#__PURE__*/ J(`notifications/initialized`,{payload:/*#__PURE__*/ cS(X6)})){},f8=class extends (/*#__PURE__*/ J(`notifications/roots/list_changed`,{payload:/*#__PURE__*/ cS(X6)})){},p8=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...X6.fields,level:J6,logger:/*#__PURE__*/ W6(U),data:Jx}})){},m8=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...X6.fields,uri:U}})){},h8=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ cS(X6)})){},g8=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ cS(X6)})){},_8=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ cS(X6)})){};const v8=W6,fxe=/*#__PURE__*/ W({...exe.fields,completions:/*#__PURE__*/ v8(/*#__PURE__*/ W({}))}),pxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`audio`),data:U,mimeType:U,annotations:/*#__PURE__*/ v8(t8)}),y8=/*#__PURE__*/ W({title:/*#__PURE__*/ v8(U),readOnlyHint:/*#__PURE__*/ v8(Zx),destructiveHint:/*#__PURE__*/ v8(Zx),idempotentHint:/*#__PURE__*/ v8(Zx),openWorldHint:/*#__PURE__*/ v8(Zx)});({...cxe.fields}),{...Z6.fields},{...Z6.fields},{...$6.fields},{...Z6.fields},{...Z6.fields},{...Y6.fields},{...Y6.fields},{...Y6.fields},{...Y6.fields};var b8=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...X6.fields,progressToken:K6,progress:CS,total:/*#__PURE__*/ v8(CS),message:/*#__PURE__*/ v8(U)}})){};const x8=`2025-06-18`,S8=W6,C8=q,w8=/*#__PURE__*/ S8(C8),T8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ S8(U),version:U}),E8=/*#__PURE__*/ W({...$be.fields,elicitation:/*#__PURE__*/ S8(/*#__PURE__*/ W({}))}),D8=/*#__PURE__*/ W({audience:/*#__PURE__*/ S8(/*#__PURE__*/ G(q6)),priority:/*#__PURE__*/ S8(/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1})))}),O8=/*#__PURE__*/ W({...axe.fields,title:/*#__PURE__*/ S8(U),annotations:/*#__PURE__*/ S8(D8),_meta:w8}),k8=/*#__PURE__*/ W({...oxe.fields,title:/*#__PURE__*/ S8(U),annotations:/*#__PURE__*/ S8(D8),_meta:w8}),A8=/*#__PURE__*/ K([/* @__PURE__ */ W({...txe.fields,_meta:w8}),/* @__PURE__ */ W({...nxe.fields,_meta:w8})]),mxe=/*#__PURE__*/ W({...n8.fields,title:/*#__PURE__*/ S8(U)}),j8=/*#__PURE__*/ W({...sxe.fields,title:/*#__PURE__*/ S8(U),arguments:/*#__PURE__*/ S8(/*#__PURE__*/ G(mxe)),_meta:w8}),M8=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`resource`),resource:A8,annotations:/*#__PURE__*/ S8(D8),_meta:w8}),hxe=/*#__PURE__*/ W({...O8.fields,type:/*#__PURE__*/ Gx(`resource_link`)}),N8=/*#__PURE__*/ W({...rxe.fields,annotations:/*#__PURE__*/ S8(D8),_meta:w8}),P8=/*#__PURE__*/ W({...ixe.fields,annotations:/*#__PURE__*/ S8(D8),_meta:w8}),F8=/*#__PURE__*/ W({...pxe.fields,annotations:/*#__PURE__*/ S8(D8),_meta:w8}),I8=/*#__PURE__*/ K([N8,P8,F8,M8,hxe]),L8=/*#__PURE__*/ K([N8,P8,F8]),gxe=/*#__PURE__*/ W({role:q6,content:I8}),_xe=/*#__PURE__*/ W({role:q6,content:L8}),vxe=/*#__PURE__*/ W({...fxe.fields}),R8=/*#__PURE__*/ W({...Z6.fields,protocolVersion:U,capabilities:vxe,serverInfo:T8,instructions:/*#__PURE__*/ S8(U)});var z8=class extends (/*#__PURE__*/ J(`initialize`,{success:R8,error:e8,payload:{...Y6.fields,protocolVersion:U,capabilities:E8,clientInfo:T8}})){};const B8=/*#__PURE__*/ nS(/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`object`),properties:/*#__PURE__*/ S8(/*#__PURE__*/ tS(U,C8)),required:/*#__PURE__*/ S8(/*#__PURE__*/ G(U))}),[q]),V8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ S8(U),description:/*#__PURE__*/ S8(U),inputSchema:B8,outputSchema:/*#__PURE__*/ S8(B8),annotations:/*#__PURE__*/ S8(y8),_meta:w8}),H8=/*#__PURE__*/ W({...Z6.fields,content:/*#__PURE__*/ G(I8),structuredContent:/*#__PURE__*/ S8(C8),isError:/*#__PURE__*/ S8(Zx)}),yxe=/*#__PURE__*/ W({...Z6.fields,role:q6,content:L8,model:U,stopReason:/*#__PURE__*/ S8(U)});var U8=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:yxe,error:e8,payload:{...Y6.fields,messages:/*#__PURE__*/ G(_xe),modelPreferences:/*#__PURE__*/ S8(r8),systemPrompt:/*#__PURE__*/ S8(U),includeContext:/*#__PURE__*/ S8(/*#__PURE__*/ oS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ S8(CS),maxTokens:CS,stopSequences:/*#__PURE__*/ S8(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ S8(C8)}})){};const W8=/*#__PURE__*/ W({...lxe.fields,title:/*#__PURE__*/ S8(U)}),G8=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`ref/resource`),uri:U}),K8=uxe;var q8=class extends (/*#__PURE__*/ J(`completion/complete`,{success:K8,error:e8,payload:{...Y6.fields,ref:/*#__PURE__*/ K([W8,G8]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ S8(/*#__PURE__*/ W({arguments:/*#__PURE__*/ S8(/*#__PURE__*/ tS(U,U))}))}})){};const J8=/*#__PURE__*/ W({...$6.fields,resources:/*#__PURE__*/ G(O8)}),Y8=/*#__PURE__*/ W({...$6.fields,resourceTemplates:/*#__PURE__*/ G(k8)}),X8=/*#__PURE__*/ W({...Z6.fields,contents:/*#__PURE__*/ G(A8)}),Z8=/*#__PURE__*/ W({...$6.fields,prompts:/*#__PURE__*/ G(j8)}),Q8=/*#__PURE__*/ W({...Z6.fields,description:/*#__PURE__*/ S8(U),messages:/*#__PURE__*/ G(gxe)}),$8=/*#__PURE__*/ W({...$6.fields,tools:/*#__PURE__*/ G(V8)});var bxe=class extends (/*#__PURE__*/ J(`resources/list`,{success:J8,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},xxe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:Y8,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},e5=class extends (/*#__PURE__*/ J(`resources/read`,{success:X8,error:e8,payload:{...Y6.fields,uri:U}})){},Sxe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:Z8,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},Cxe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:Q8,error:e8,payload:{...Y6.fields,name:U,arguments:/*#__PURE__*/ S8(/*#__PURE__*/ tS(U,U))}})){},wxe=class extends (/*#__PURE__*/ J(`tools/list`,{success:$8,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},t5=class extends (/*#__PURE__*/ J(`tools/call`,{success:H8,error:e8,payload:{...Y6.fields,name:U,arguments:/*#__PURE__*/ S8(C8)}})){};const Txe=/*#__PURE__*/ W({...Z6.fields,action:/*#__PURE__*/ oS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ S8(/*#__PURE__*/ tS(U,/*#__PURE__*/ K([U,CS,Zx])))}),Exe=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`object`),properties:/*#__PURE__*/ tS(U,/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`string`),title:/*#__PURE__*/ S8(U),description:/*#__PURE__*/ S8(U),minLength:/*#__PURE__*/ S8(AS),maxLength:/*#__PURE__*/ S8(AS),format:/*#__PURE__*/ S8(/*#__PURE__*/ oS([`email`,`uri`,`date`,`date-time`]))}),/* @__PURE__ */ W({type:/*#__PURE__*/ oS([`number`,`integer`]),title:/*#__PURE__*/ S8(U),description:/*#__PURE__*/ S8(U),minimum:/*#__PURE__*/ S8(CS),maximum:/*#__PURE__*/ S8(CS)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`boolean`),title:/*#__PURE__*/ S8(U),description:/*#__PURE__*/ S8(U),default:/*#__PURE__*/ S8(Zx)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`string`),title:/*#__PURE__*/ S8(U),description:/*#__PURE__*/ S8(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ S8(/*#__PURE__*/ G(U))})])),required:/*#__PURE__*/ S8(/*#__PURE__*/ G(U))});var n5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Txe,error:e8,payload:{...Y6.fields,message:U,requestedSchema:Exe}})){},Dxe=class extends (/*#__PURE__*/ _N(a8,z8,q8,o8,Cxe,Sxe,bxe,xxe,e5,s8,c8,t5,wxe)){},r5=class extends (/*#__PURE__*/ _N(u8,b8,d8,f8)){},Oxe=class extends (/*#__PURE__*/ _N(a8,U8,l8,n5)){},kxe=class extends (/*#__PURE__*/ _N(u8,b8,p8,m8,h8,g8,_8)){};const i5=/*#__PURE__*/ (/* @__PURE__ */ Dxe.omit(`ping`).middleware(c6).add(a8)).merge(r5),a5=/*#__PURE__*/ i5.omit(`ping`),Axe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||rn(e.properties)&&Object.values(e.properties).every(rn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Ut);return t&&n},jxe=e=>({protocolVersion:x8,clientCapabilities:T3.make(e.capabilities),clientInfo:w3.make(e.clientInfo),requestMetadata:e._meta}),o5=(e,t)=>new a6({operation:e,protocolVersion:x8,reason:t}),s5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(o5(t,`Client did not advertise the ${n} capability`)),c5=/*#__PURE__*/ H(function*(e){return HE(e).pipe(UE({type:KE(`text`,`resource_link`)},e=>e),UE({type:KE(`image`,`audio`)},e=>({type:e.type,mimeType:e.mimeType,data:Dh(e.data),annotations:e.annotations,_meta:e._meta})),UE({type:`resource`},e=>{let t=e.resource;return`text`in t?M8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):M8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:Dh(t.blob)},annotations:e.annotations,_meta:e._meta})}),JE)}),Mxe=e=>`text`in e?{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,text:e.text}:{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,blob:Dh(e.blob)},Nxe=e=>e===void 0||Pxe(e)?e:void 0,Pxe=e=>rn(e),Fxe=/*#__PURE__*/ O6({protocolVersion:x8,runtime:/*#__PURE__*/ B6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:i5,clientNotificationRpcs:r5,serverRequestRpcs:Oxe,serverNotificationRpcs:kxe,handlerRpcs:a5,makeHandlers:(e,t)=>a5.of({initialize:(e,{client:n})=>t.initialize(x8,jxe(e),n.id).pipe(V(e=>R8.make({protocolVersion:x8,capabilities:{experimental:e.capabilities.experimental,extensions:e.capabilities.extensions,logging:e.capabilities.logging?{}:void 0,completions:e.capabilities.completions?{}:void 0,prompts:e.capabilities.prompts,resources:e.capabilities.resources,tools:e.capabilities.tools},serverInfo:e.serverInfo,instructions:e.instructions}))),"logging/setLevel":({level:e},{client:n,headers:r})=>t.setLogLevel(e,n.id,r).pipe(vp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(f6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(f6.Progress({progressToken:e.progressToken,progress:e.progress,total:e.total,message:e.message,metadata:e._meta}),n.id,r),"notifications/roots/list_changed":(e,{client:n,headers:r})=>t.clientNotification(f6.RootsChanged(),n.id,r),"resources/list":t=>s6.use(t=>e.resources.list(g6(t))).pipe(V(e=>J8.make({resources:e}))),"resources/templates/list":t=>s6.use(t=>e.resources.listTemplates(g6(t))).pipe(V(e=>Y8.make({resourceTemplates:e}))),"resources/read":H(function*({uri:t}){let n=yield*s6,r=yield*e.resources.read(t,_6(n)).pipe(Tp(C6.fromFeature));return X8.make({contents:r.contents.map(Mxe),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(vp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(vp({})),"prompts/list":t=>s6.use(t=>e.prompts.list(g6(t))).pipe(V(e=>Z8.make({prompts:e}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*s6,i=yield*e.prompts.get(n,t??{},_6(r)).pipe(Tp(C6.fromFeature));if(i._tag===`InputRequired`)return yield*C6.fromFeature(new d6({protocolVersion:x8,feature:`prompt input requirements`}));let a=i.value,o=yield*ep(a.messages,e=>c5(e.content).pipe(V(t=>({role:e.role,content:t})),Tp(C6.fromTool)));return Q8.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*s6,r=yield*e.completions.complete({reference:t.ref.type===`ref/prompt`?{type:`prompt`,name:t.ref.name,title:t.ref.title}:{type:`resourceTemplate`,uriTemplate:t.ref.uri},argument:t.argument,context:t.context?.arguments===void 0?void 0:{arguments:t.context.arguments},metadata:t._meta},_6(n)).pipe(Tp(C6.fromFeature));return K8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*s6,n=yield*e.tools.list(g6(t));return $8.make({tools:n.map(e=>V8.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:Axe(e.outputSchema)?e.outputSchema:void 0,annotations:e.annotations===void 0?void 0:y8.make({title:e.annotations.title,readOnlyHint:e.annotations.readOnlyHint,destructiveHint:e.annotations.destructiveHint,idempotentHint:e.annotations.idempotentHint,openWorldHint:e.annotations.openWorldHint}),_meta:e._meta}))})}),"tools/call":H(function*(t){let n=yield*s6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},_6(n)).pipe(B(e=>y6(x8,e)),Tp(C6.fromTool)),i=yield*ep(b6(r),c5).pipe(Tp(C6.fromTool)),a=Nxe(r.structuredContent);return H8.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*s5(e,`roots/list`,`roots`);let r=yield*T6(r6.payloadSchema,l8.payloadSchema,n).pipe(Tp(()=>o5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(Tp(w6(`roots/list`)));return new n6({roots:i})}),createMessage:H(function*(n){yield*s5(e,`sampling/createMessage`,`sampling`);let r=yield*Kbe(t6.payloadSchema,U8.payloadSchema,n).pipe(Tp(()=>o5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(Tp(w6(`sampling/createMessage`)));return yield*T6(U8.successSchema,t6.successSchema,i).pipe(Tp(()=>o5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*s5(e,`elicitation/create`,`elicitation`);let r=n.mode===`form`?soe(n,[`mode`]):n,i=yield*Nx(n5.payloadSchema,{onExcessProperty:`error`})(r).pipe(Tp(()=>o5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(Tp(w6(`elicitation/create`)));return yield*T6(n5.successSchema,i6.successSchema,a).pipe(Tp(()=>o5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>E6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Nx(u8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),l5=`2025-11-25`,Q=W6,u5=q,d5=/*#__PURE__*/ Q(u5),f5=/*#__PURE__*/ W({src:U,mimeType:/*#__PURE__*/ Q(U),sizes:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Q(/*#__PURE__*/ oS([`light`,`dark`]))}),p5=/*#__PURE__*/ W({...T8.fields,description:/*#__PURE__*/ Q(U),websiteUrl:/*#__PURE__*/ Q(U),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(f5))}),Ixe=/*#__PURE__*/ W({...E8.fields,sampling:/*#__PURE__*/ Q(/*#__PURE__*/ W({context:/*#__PURE__*/ Q(u5),tools:/*#__PURE__*/ Q(u5)})),elicitation:/*#__PURE__*/ Q(/*#__PURE__*/ W({form:/*#__PURE__*/ Q(u5),url:/*#__PURE__*/ Q(u5)}))}),m5=/*#__PURE__*/ W({...D8.fields,lastModified:/*#__PURE__*/ Q(U)}),h5=/*#__PURE__*/ W({...O8.fields,annotations:/*#__PURE__*/ Q(m5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(f5))}),g5=/*#__PURE__*/ W({...k8.fields,annotations:/*#__PURE__*/ Q(m5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(f5))}),_5=/*#__PURE__*/ W({...j8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(f5))}),v5=/*#__PURE__*/ W({...N8.fields,annotations:/*#__PURE__*/ Q(m5)}),y5=/*#__PURE__*/ W({...P8.fields,annotations:/*#__PURE__*/ Q(m5)}),b5=/*#__PURE__*/ W({...F8.fields,annotations:/*#__PURE__*/ Q(m5)}),x5=/*#__PURE__*/ W({...M8.fields,annotations:/*#__PURE__*/ Q(m5)}),S5=/*#__PURE__*/ K([v5,y5,b5,/* @__PURE__ */ W({...h5.fields,type:/*#__PURE__*/ Gx(`resource_link`)}),x5]),Lxe=/*#__PURE__*/ W({role:q6,content:S5}),C5=/*#__PURE__*/ W({...V8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(f5))}),w5=/*#__PURE__*/ W({...H8.fields,content:/*#__PURE__*/ G(S5)});var Rxe=class extends (/*#__PURE__*/ J(`tools/call`,{success:w5,error:e8,payload:t5.payloadSchema})){};const T5=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`tool_use`),id:U,name:U,input:u5,_meta:d5}),E5=/*#__PURE__*/ K([v5,y5,b5,T5,/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(S5),structuredContent:/*#__PURE__*/ Q(u5),isError:/*#__PURE__*/ Q(Zx),_meta:d5})]),D5=/*#__PURE__*/ W({role:q6,content:/*#__PURE__*/ K([E5,/*#__PURE__*/ G(E5)]),_meta:d5}),O5=/*#__PURE__*/ W({mode:/*#__PURE__*/ Q(/*#__PURE__*/ oS([`auto`,`required`,`none`]))}),zxe=/*#__PURE__*/ W({...Z6.fields,...D5.fields,model:U,stopReason:/*#__PURE__*/ Q(U)});var k5=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:zxe,error:e8,payload:{...U8.payloadSchema.fields,messages:/*#__PURE__*/ G(D5),maxTokens:AS,tools:/*#__PURE__*/ Q(/*#__PURE__*/ G(C5)),toolChoice:/*#__PURE__*/ Q(O5)}})){};const A5=/*#__PURE__*/ W({...i8.fields,_meta:d5}),Bxe=/*#__PURE__*/ W({...Z6.fields,roots:/*#__PURE__*/ G(A5)});var j5=class extends (/*#__PURE__*/ J(`roots/list`,{success:Bxe,error:e8,payload:/*#__PURE__*/ cS(Y6)})){};const M5=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minLength:/*#__PURE__*/ Q(AS),maxLength:/*#__PURE__*/ Q(AS),format:/*#__PURE__*/ Q(/*#__PURE__*/ oS([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Q(U)}),N5=/*#__PURE__*/ W({type:/*#__PURE__*/ oS([`number`,`integer`]),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minimum:/*#__PURE__*/ Q(CS),maximum:/*#__PURE__*/ Q(CS),default:/*#__PURE__*/ Q(CS)}),P5=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`boolean`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),default:/*#__PURE__*/ Q(Zx)}),F5=/*#__PURE__*/ W({const:U,title:U}),I5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Q(U)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),oneOf:/*#__PURE__*/ G(F5),default:/*#__PURE__*/ Q(U)})]),L5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(AS),maxItems:/*#__PURE__*/ Q(AS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(AS),maxItems:/*#__PURE__*/ Q(AS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(F5)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))})]),R5=/*#__PURE__*/ W({type:/*#__PURE__*/ Gx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),default:/*#__PURE__*/ Q(U)}),Vxe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Q(U),type:/*#__PURE__*/ Gx(`object`),properties:/*#__PURE__*/ tS(U,/* @__PURE__ */ K([/* @__PURE__ */ K([R5,I5,L5]),M5,N5,P5])),required:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),Hxe=/*#__PURE__*/ K([/* @__PURE__ */ W({...Y6.fields,mode:/*#__PURE__*/ Q(/*#__PURE__*/ Gx(`form`)),message:U,requestedSchema:Vxe}),/* @__PURE__ */ W({...Y6.fields,mode:/*#__PURE__*/ Gx(`url`),message:U,elicitationId:U,url:U})]),Uxe=/*#__PURE__*/ W({...Z6.fields,action:/*#__PURE__*/ oS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ Q(/*#__PURE__*/ tS(U,/*#__PURE__*/ K([U,CS,Zx,/*#__PURE__*/ G(U)])))});var z5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Uxe,error:e8,payload:Hxe})){},Wxe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};const B5=/*#__PURE__*/ W({...R8.fields,serverInfo:p5});var Gxe=class extends (/*#__PURE__*/ J(`initialize`,{success:B5,error:e8,payload:{...z8.payloadSchema.fields,capabilities:Ixe,clientInfo:p5}})){};const V5=/*#__PURE__*/ W({...$6.fields,resources:/*#__PURE__*/ G(h5)}),H5=/*#__PURE__*/ W({...$6.fields,resourceTemplates:/*#__PURE__*/ G(g5)}),U5=/*#__PURE__*/ W({...$6.fields,prompts:/*#__PURE__*/ G(_5)}),W5=/*#__PURE__*/ W({...Q8.fields,messages:/*#__PURE__*/ G(Lxe)}),G5=/*#__PURE__*/ W({...$6.fields,tools:/*#__PURE__*/ G(C5)});var Kxe=class extends (/*#__PURE__*/ J(`resources/list`,{success:V5,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},qxe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:H5,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},Jxe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:U5,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},Yxe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:W5,error:e8,payload:{...Y6.fields,name:U,arguments:/*#__PURE__*/ Q(/*#__PURE__*/ tS(U,U))}})){},Xxe=class extends (/*#__PURE__*/ J(`tools/list`,{success:G5,error:e8,payload:/*#__PURE__*/ cS(Q6)})){},Zxe=class extends (/*#__PURE__*/ _N(a8,Gxe,q8,o8,Yxe,Jxe,Kxe,qxe,e5,s8,c8,Rxe,Xxe)){},K5=class extends (/*#__PURE__*/ _N(u8,b8,d8,f8)){},Qxe=class extends (/*#__PURE__*/ _N(a8,k5,j5,z5)){},$xe=class extends (/*#__PURE__*/ _N(u8,b8,p8,m8,h8,g8,_8,Wxe)){};const q5=/*#__PURE__*/ (/* @__PURE__ */ Zxe.omit(`ping`).middleware(c6).add(a8)).merge(K5),J5=/*#__PURE__*/ q5.omit(`ping`),eSe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||rn(e.properties)&&Object.values(e.properties).every(rn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Ut);return t&&n},Y5=(e,t)=>new a6({operation:e,protocolVersion:l5,reason:t}),X5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(Y5(t,`Client did not advertise the ${n} capability`)),tSe=e=>e.stopReason===`toolUse`||(`type`in e.content?e.content.type===`tool_use`||e.content.type===`tool_result`:e.content.some(e=>e.type===`tool_use`||e.type===`tool_result`)),nSe=(e,t)=>{let n=e.clientCapabilities.elicitation;return n===void 0?!1:t===`form`?n.form!==void 0||n.url===void 0:n.url!==void 0},Z5=/*#__PURE__*/ H(function*(e){return HE(e).pipe(UE({type:KE(`text`,`resource_link`)},e=>e),UE({type:KE(`image`,`audio`)},e=>({type:e.type,mimeType:e.mimeType,data:Dh(e.data),annotations:e.annotations,_meta:e._meta})),UE({type:`resource`},e=>{let t=e.resource;return`text`in t?x5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):x5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:Dh(t.blob)},annotations:e.annotations,_meta:e._meta})}),JE)}),rSe=e=>e===void 0||iSe(e)?e:void 0,iSe=e=>rn(e),aSe=/*#__PURE__*/ O6({protocolVersion:l5,runtime:/*#__PURE__*/ B6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:q5,clientNotificationRpcs:K5,serverRequestRpcs:Qxe,serverNotificationRpcs:$xe,handlerRpcs:J5,makeHandlers:(e,t)=>J5.of({initialize:(e,{client:n})=>t.initialize(l5,{protocolVersion:l5,clientCapabilities:T3.make(e.capabilities),clientInfo:w3.make(e.clientInfo),requestMetadata:e._meta},n.id).pipe(V(e=>B5.make({protocolVersion:l5,capabilities:{experimental:e.capabilities.experimental,extensions:e.capabilities.extensions,logging:e.capabilities.logging?{}:void 0,completions:e.capabilities.completions?{}:void 0,prompts:e.capabilities.prompts,resources:e.capabilities.resources,tools:e.capabilities.tools},serverInfo:e.serverInfo,instructions:e.instructions}))),"logging/setLevel":({level:e},{client:n,headers:r})=>t.setLogLevel(e,n.id,r).pipe(vp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(f6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(f6.Progress({progressToken:e.progressToken,progress:e.progress,total:e.total,message:e.message,metadata:e._meta}),n.id,r),"notifications/roots/list_changed":(e,{client:n,headers:r})=>t.clientNotification(f6.RootsChanged(),n.id,r),"resources/list":()=>s6.use(t=>e.resources.list(g6(t))).pipe(V(e=>V5.make({resources:e.map(e=>h5.make(e))}))),"resources/templates/list":()=>s6.use(t=>e.resources.listTemplates(g6(t))).pipe(V(e=>H5.make({resourceTemplates:e.map(e=>g5.make(e))}))),"resources/read":H(function*({uri:t}){let n=yield*s6,r=yield*e.resources.read(t,_6(n)).pipe(Tp(C6.fromFeature));return X8.make({contents:r.contents.map(e=>`text`in e?{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,text:e.text}:{uri:e.uri,mimeType:e.mimeType,_meta:e._meta,blob:Dh(e.blob)}),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(vp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(vp({})),"prompts/list":()=>s6.use(t=>e.prompts.list(g6(t))).pipe(V(e=>U5.make({prompts:e.map(e=>_5.make(e))}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*s6,i=yield*e.prompts.get(n,t??{},_6(r)).pipe(Tp(C6.fromFeature));if(i._tag===`InputRequired`)return yield*C6.fromFeature(new d6({protocolVersion:l5,feature:`prompt input requirements`}));let a=i.value,o=yield*ep(a.messages,e=>Z5(e.content).pipe(V(t=>({role:e.role,content:t})),Tp(C6.fromTool)));return W5.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*s6,r=yield*e.completions.complete({reference:t.ref.type===`ref/prompt`?{type:`prompt`,name:t.ref.name,title:t.ref.title}:{type:`resourceTemplate`,uriTemplate:t.ref.uri},argument:t.argument,context:t.context?.arguments===void 0?void 0:{arguments:t.context.arguments},metadata:t._meta},_6(n)).pipe(Tp(C6.fromFeature));return K8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*s6,n=yield*e.tools.list(g6(t));return G5.make({tools:n.map(e=>C5.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:eSe(e.outputSchema)?e.outputSchema:void 0,icons:e.icons,annotations:e.annotations===void 0?void 0:y8.make({title:e.annotations.title,readOnlyHint:e.annotations.readOnlyHint,destructiveHint:e.annotations.destructiveHint,idempotentHint:e.annotations.idempotentHint,openWorldHint:e.annotations.openWorldHint}),_meta:e._meta}))})}),"tools/call":H(function*(t){let n=yield*s6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},_6(n)).pipe(B(e=>y6(l5,e)),xp([`InvalidToolInput`,`ToolExecutionError`],e=>F(X3.make({content:[H3.make({type:`text`,text:e.message})],isError:!0}))),Tp(C6.fromTool)),i=yield*ep(b6(r),Z5).pipe(Tp(C6.fromTool)),a=rSe(r.structuredContent);return w5.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*X5(e,`roots/list`,`roots`);let r=yield*T6(r6.payloadSchema,j5.payloadSchema,n).pipe(Tp(()=>Y5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(Tp(w6(`roots/list`)));return new n6({roots:i})}),createMessage:H(function*(n){if(yield*X5(e,`sampling/createMessage`,`sampling`),S6(n)&&e.clientCapabilities.sampling?.tools==null)return yield*Y5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`);if((n.includeContext===`thisServer`||n.includeContext===`allServers`)&&e.clientCapabilities.sampling?.context==null)return yield*Y5(`sampling/createMessage`,`Client did not advertise the sampling.context capability`);let r=yield*T6(t6.payloadSchema,k5.payloadSchema,n).pipe(Tp(()=>Y5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(Tp(w6(`sampling/createMessage`)));return tSe(i)&&e.clientCapabilities.sampling?.tools==null?yield*Y5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`):yield*T6(k5.successSchema,t6.successSchema,i).pipe(Tp(()=>Y5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*X5(e,`elicitation/create`,`elicitation`);let r=n.mode===`url`?`url`:`form`;if(!nSe(e,r))return yield*Y5(`elicitation/create`,`Client did not advertise the elicitation.${r} capability`);let i=yield*T6(i6.payloadSchema,z5.payloadSchema,n).pipe(Tp(()=>Y5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(Tp(w6(`elicitation/create`)));return yield*T6(z5.successSchema,i6.successSchema,a).pipe(Tp(()=>Y5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>e._tag===`ElicitationComplete`?F({tag:`notifications/elicitation/complete`,payload:{elicitationId:e.elicitationId}}):E6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Nx(u8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),Q5=`2026-07-28`,$=W6,$5=/*#__PURE__*/ $(q),e7=/*#__PURE__*/ K([U,AS]),t7=e7,n7=q6,r7=J6,i7=p5,oSe=/*#__PURE__*/ nS(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,q)),roots:/*#__PURE__*/ $(/*#__PURE__*/ W({})),sampling:/*#__PURE__*/ $(/*#__PURE__*/ W({context:/*#__PURE__*/ $(q),tools:/*#__PURE__*/ $(q)})),elicitation:/*#__PURE__*/ $(/*#__PURE__*/ W({form:/*#__PURE__*/ $(q),url:/*#__PURE__*/ $(q)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,q))}),[q]),sSe=/*#__PURE__*/ nS(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,q)),logging:/*#__PURE__*/ $(q),completions:/*#__PURE__*/ $(q),prompts:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Zx)})),resources:/*#__PURE__*/ $(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ $(Zx),listChanged:/*#__PURE__*/ $(Zx)})),tools:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Zx)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,q))}),[q]),a7=/*#__PURE__*/ nS(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ $(t7),"io.modelcontextprotocol/protocolVersion":U,"io.modelcontextprotocol/clientInfo":/*#__PURE__*/ $(i7),"io.modelcontextprotocol/clientCapabilities":oSe,"io.modelcontextprotocol/logLevel":/*#__PURE__*/ $(r7)}),[q]),o7=/*#__PURE__*/ W({_meta:a7}),s7=/*#__PURE__*/ W({_meta:/*#__PURE__*/ $(/* @__PURE__ */ nS(/*#__PURE__*/ W({"io.modelcontextprotocol/subscriptionId":/*#__PURE__*/ $(e7)}),[q]))}),c7=/*#__PURE__*/ nS(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":i7}),[q]),l7={_meta:c7,resultType:/*#__PURE__*/ Gx(`complete`)},u7=/*#__PURE__*/ W({code:AS,message:U,data:/*#__PURE__*/ $(_C)}),cSe=m5,d7=/*#__PURE__*/ W({...h5.fields,size:/*#__PURE__*/ $(AS),annotations:/*#__PURE__*/ $(cSe)}),f7=g5,lSe=A8,p7=v5,m7=y5,h7=b5,g7=/*#__PURE__*/ K([p7,m7,h7,/* @__PURE__ */ W({...d7.fields,type:/*#__PURE__*/ Gx(`resource_link`)}),x5]),_7=_5,uSe=/*#__PURE__*/ W({role:n7,content:g7}),dSe=/*#__PURE__*/ nS(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ Gx(`object`)}),[q]),fSe=/*#__PURE__*/ nS(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U)}),[q]),pSe=y8,v7=/*#__PURE__*/ W({...C5.fields,inputSchema:dSe,outputSchema:/*#__PURE__*/ $(fSe),annotations:/*#__PURE__*/ $(pSe)}),y7=/*#__PURE__*/ K([p7,m7,h7,T5,/* @__PURE__ */ W({type:/*#__PURE__*/ Gx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(g7),structuredContent:/*#__PURE__*/ $(_C),isError:/*#__PURE__*/ $(Zx),_meta:$5})]),b7=/*#__PURE__*/ W({role:n7,content:/*#__PURE__*/ K([y7,/*#__PURE__*/ G(y7)]),_meta:$5}),mSe=/*#__PURE__*/ nS(/*#__PURE__*/ W({name:/*#__PURE__*/ $(U)}),[q]),x7=/*#__PURE__*/ CS.check(/*#__PURE__*/ OS({minimum:0,maximum:1})),hSe=/*#__PURE__*/ W({...r8.fields,hints:/*#__PURE__*/ $(/*#__PURE__*/ G(mSe)),costPriority:/*#__PURE__*/ $(x7),speedPriority:/*#__PURE__*/ $(x7),intelligencePriority:/*#__PURE__*/ $(x7)}),gSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Gx(`sampling/createMessage`),params:/*#__PURE__*/ W({messages:/*#__PURE__*/ G(b7),modelPreferences:/*#__PURE__*/ $(hSe),systemPrompt:/*#__PURE__*/ $(U),includeContext:/*#__PURE__*/ $(/*#__PURE__*/ oS([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ $(CS),maxTokens:AS,stopSequences:/*#__PURE__*/ $(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ $(q),tools:/*#__PURE__*/ $(/*#__PURE__*/ G(v7)),toolChoice:/*#__PURE__*/ $(O5)})}),_Se=/*#__PURE__*/ W({...b7.fields,model:U,stopReason:/*#__PURE__*/ $(U)}),vSe=A5,ySe=/*#__PURE__*/ W({method:/*#__PURE__*/ Gx(`roots/list`),params:/*#__PURE__*/ $(/*#__PURE__*/ W({_meta:$5}))}),bSe=/*#__PURE__*/ W({roots:/*#__PURE__*/ G(vSe)}),xSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Gx(`elicitation/create`),params:/* @__PURE__ */ K([/* @__PURE__ */ W({mode:/*#__PURE__*/ $(/*#__PURE__*/ Gx(`form`)),message:U,requestedSchema:/* @__PURE__ */ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ Gx(`object`),properties:/*#__PURE__*/ tS(U,/* @__PURE__ */ K([/* @__PURE__ */ K([R5,I5,L5]),M5,N5,P5])),required:/*#__PURE__*/ $(/*#__PURE__*/ G(U))})}),/* @__PURE__ */ W({mode:/*#__PURE__*/ Gx(`url`),message:U,url:U})])}),SSe=/*#__PURE__*/ W({action:/*#__PURE__*/ oS([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,/*#__PURE__*/ K([U,CS,Zx,/*#__PURE__*/ G(U)])))}),CSe=/*#__PURE__*/ K([gSe,ySe,xSe]),wSe=/*#__PURE__*/ K([_Se,bSe,SSe]),S7=/*#__PURE__*/ tS(U,CSe),TSe=/*#__PURE__*/ tS(U,wSe),C7={_meta:c7,resultType:/*#__PURE__*/ Gx(`input_required`)},w7=/*#__PURE__*/ K([/*#__PURE__*/ nS(/*#__PURE__*/ W({...C7,inputRequests:S7,requestState:/*#__PURE__*/ $(U)}),[q]),/*#__PURE__*/ nS(/*#__PURE__*/ W({...C7,inputRequests:/*#__PURE__*/ $(S7),requestState:U}),[q])]),T7={...o7.fields,inputResponses:/*#__PURE__*/ $(TSe),requestState:/*#__PURE__*/ $(U)},E7={...l7,ttlMs:/*#__PURE__*/ AS.check(/*#__PURE__*/ DS(0)),cacheScope:/*#__PURE__*/ oS([`public`,`private`])},D7={...o7.fields,cursor:/*#__PURE__*/ $(U)},O7={...l7,nextCursor:/*#__PURE__*/ $(U)},k7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...E7,supportedVersions:/*#__PURE__*/ G(U),capabilities:sSe,instructions:/*#__PURE__*/ $(U)}),[q]);var ESe=class extends (/*#__PURE__*/ J(`server/discover`,{success:k7,error:u7,payload:o7})){};const A7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...O7,...E7,resources:/*#__PURE__*/ G(d7)}),[q]);var DSe=class extends (/*#__PURE__*/ J(`resources/list`,{success:A7,error:u7,payload:D7})){};const j7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...O7,...E7,resourceTemplates:/*#__PURE__*/ G(f7)}),[q]);var OSe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:j7,error:u7,payload:D7})){};const M7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...E7,contents:/*#__PURE__*/ G(lSe)}),[q]);var kSe=class extends (/*#__PURE__*/ J(`resources/read`,{success:/*#__PURE__*/ K([M7,w7]),error:u7,payload:{...T7,uri:U}})){};const N7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...O7,...E7,prompts:/*#__PURE__*/ G(_7)}),[q]);var ASe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:N7,error:u7,payload:D7})){};const P7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...l7,description:/*#__PURE__*/ $(U),messages:/*#__PURE__*/ G(uSe)}),[q]);var jSe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:/*#__PURE__*/ K([P7,w7]),error:u7,payload:{...T7,name:U,arguments:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,U))}})){};const F7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...O7,...E7,tools:/*#__PURE__*/ G(v7)}),[q]);var MSe=class extends (/*#__PURE__*/ J(`tools/list`,{success:F7,error:u7,payload:D7})){};const I7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...l7,content:/*#__PURE__*/ G(g7),structuredContent:/*#__PURE__*/ $(_C),isError:/*#__PURE__*/ $(Zx)}),[q]);var NSe=class extends (/*#__PURE__*/ J(`tools/call`,{success:/*#__PURE__*/ K([I7,w7]),error:u7,payload:{...T7,name:U,arguments:/*#__PURE__*/ $(q)}})){};const PSe=W8,FSe=G8,L7=/*#__PURE__*/ nS(/*#__PURE__*/ W({...l7,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U).check(/*#__PURE__*/ NS(100)),total:/*#__PURE__*/ $(AS),hasMore:/*#__PURE__*/ $(Zx)})}),[q]);var ISe=class extends (/*#__PURE__*/ J(`completion/complete`,{success:L7,error:u7,payload:{...o7.fields,ref:/*#__PURE__*/ K([PSe,FSe]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ $(/*#__PURE__*/ W({arguments:/*#__PURE__*/ $(/*#__PURE__*/ tS(U,U))}))}})){};const R7=/*#__PURE__*/ W({toolsListChanged:/*#__PURE__*/ $(Zx),promptsListChanged:/*#__PURE__*/ $(Zx),resourcesListChanged:/*#__PURE__*/ $(Zx),resourceSubscriptions:/*#__PURE__*/ $(/*#__PURE__*/ G(U))}),z7=/*#__PURE__*/ nS(/*#__PURE__*/ W({_meta:/* @__PURE__ */ nS(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":i7,"io.modelcontextprotocol/subscriptionId":e7}),[q]),resultType:/*#__PURE__*/ Gx(`complete`)}),[q]);var LSe=class extends (/*#__PURE__*/ J(`subscriptions/listen`,{success:z7,error:u7,payload:{...o7.fields,notifications:R7}})){},B7=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...s7.fields,requestId:e7,reason:/*#__PURE__*/ $(U)}})){},RSe=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...s7.fields,progressToken:t7,progress:CS,total:/*#__PURE__*/ $(CS),message:/*#__PURE__*/ $(U)}})){},zSe=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...s7.fields,level:r7,logger:/*#__PURE__*/ $(U),data:_C}})){},V7=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...s7.fields,uri:U}})){},H7=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ cS(s7)})){},U7=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ cS(s7)})){},W7=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ cS(s7)})){},G7=class extends (/*#__PURE__*/ J(`notifications/subscriptions/acknowledged`,{payload:{...s7.fields,notifications:R7}})){},K7=class extends (/*#__PURE__*/ _N(ESe,ISe,jSe,ASe,DSe,OSe,kSe,LSe,NSe,MSe)){},q7=class extends (/*#__PURE__*/ _N(B7)){},BSe=class extends (/*#__PURE__*/ K7.merge(q7)){},VSe=class extends (/*#__PURE__*/ _N()){},HSe=class extends (/*#__PURE__*/ _N(B7,RSe,zSe,V7,H7,U7,W7,G7)){};const USe=/*#__PURE__*/ tS(U,q),WSe=/*#__PURE__*/ Nx(a7),GSe=/*#__PURE__*/ Nx(B7.payloadSchema),KSe=/*#__PURE__*/ Mx(_C),J7=/*#__PURE__*/ Lx(i7),Y7=e=>{let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t},qSe=(e,t)=>{if(Qt(t))return e===void 0;if(e===void 0)return!1;let n=h6(e);return n!==void 0&&HE(t).pipe(UE(Fce,e=>n===e),UE(Lce,e=>n===String(e)),UE(Ice,e=>Number.isSafeInteger(e)&&n.trim().length>0&&Number(n)===e),qE(()=>!1))},JSe=/*#__PURE__*/ H(function*(e){let t=yield*WSe(e);return{protocolVersion:Q5,clientCapabilities:t[`io.modelcontextprotocol/clientCapabilities`],clientInfo:t[`io.modelcontextprotocol/clientInfo`],requestMetadata:t}}),X7=(e,t)=>{let n=e._meta;return{...rn(n)?n:{},"io.modelcontextprotocol/serverInfo":t}},Z7=(e,t)=>Y7({_meta:{"io.modelcontextprotocol/serverInfo":t},resultType:`input_required`,inputRequests:e.inputRequests,requestState:e.requestState}),Q7=/*#__PURE__*/ Nx(/*#__PURE__*/ K([I7,w7])),$7=/*#__PURE__*/ H(function*(e,t){let n=yield*J7(t);return e._tag===`Complete`?yield*Q7({...Y7(e.value),_meta:X7(e.value,n),resultType:`complete`}):yield*Q7(Z7(e,n))}),YSe=(e,t)=>{let n={};for(let r of Object.values(e??{}))HE(r).pipe(UE({method:`roots/list`},()=>{t.roots===void 0&&(n.roots={})}),UE({method:`sampling/createMessage`},e=>{let r=n.sampling??{};S6(e.params)&&t.sampling?.tools===void 0&&(r.tools={}),(e.params.includeContext===`thisServer`||e.params.includeContext===`allServers`)&&t.sampling?.context===void 0&&(r.context={}),(t.sampling===void 0||Object.keys(r).length>0)&&(n.sampling=r)}),UE({method:`elicitation/create`},e=>{let r=e.params.mode===`url`?`url`:`form`,i=t.elicitation;i!==void 0&&(r===`url`?i.url!==void 0:i.form!==void 0||Object.keys(i).length===0)||((n.elicitation??={})[r]={})}),JE);return n},e9=e=>Y7({uri:e.uri,mimeType:e.mimeType,_meta:e._meta,...`text`in e?{text:e.text}:{blob:Dh(e.blob)}}),t9=/*#__PURE__*/ VE().pipe(/*#__PURE__*/ UE({type:/*#__PURE__*/ KE(`text`,`resource_link`)},e=>e),/*#__PURE__*/ UE({type:/*#__PURE__*/ KE(`image`,`audio`)},e=>Y7({type:e.type,mimeType:e.mimeType,data:Dh(e.data),annotations:e.annotations,_meta:e._meta})),/*#__PURE__*/ UE({type:`resource`},e=>Y7({type:`resource`,resource:e9(e.resource),annotations:e.annotations,_meta:e._meta})),JE),XSe=e=>d7.make(e),ZSe=e=>f7.make(e),QSe=e=>T6(Sbe,_7,e),$Se=e=>T6(Y3,v7,e),n9={ttlMs:0,cacheScope:`private`},r9=/*#__PURE__*/ H(function*(e,t){let n=yield*J7(t);return{...Y7(e),_meta:X7(e,n),resultType:`complete`}}),eCe=/*#__PURE__*/ VE().pipe(/*#__PURE__*/ WE(`ResourceNotFound`,e=>new C6({code:-32602,message:`Resource '${e.uri}' not found`,data:{uri:e.uri}})),/*#__PURE__*/ WE(`ToolNotFound`,`InvalidToolInput`,`InvalidToolContinuation`,`ToolExecutionError`,`UnsupportedByProtocol`,C6.fromTool),/*#__PURE__*/ qE(C6.fromFeature)),i9=e=>{let t=eCe(e);return u7.make({code:t.code,message:t.message,...KSe(t.data)?{data:t.data}:{}})},a9=/*#__PURE__*/ H(function*(e,t){let n=yield*Hp(pM);return Ii(n)&&xM(n.value,(t,n)=>F(OA(n,e))),yield*t}),tCe=e=>GSe(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta}))),o9=e=>new a6({operation:e,protocolVersion:Q5,reason:`MCP 2026-07-28 carries server input requests in multi round-trip results`}),s9=/* @__PURE__ */ O6({protocolVersion:Q5,runtime:{_tag:`Stateless`,transport:{jsonRpc:{acceptsBatches:!1},http:{}},profileFromRequestMetadata:JSe},clientRpcs:BSe,clientNotificationRpcs:q7,serverRequestRpcs:VSe,serverNotificationRpcs:HSe,handlerRpcs:/* @__PURE__ */ K7.merge(q7),makeHandlers:(e,t,n)=>{let r=Nx(USe),i=Nx(k7),a=Nx(A7),o=Nx(j7),s=Nx(M7),c=Nx(N7),l=Nx(P7),u=Nx(K([P7,w7])),d=Nx(L7),f=Nx(F7),p=n.sendNotification,m=p!==void 0,h=n.serverInfo.extensions===void 0?void 0:tte(n.serverInfo.extensions,e=>rn(e)),g=V(n.registrationPresence,e=>{let t={completions:{},logging:{}};return h!==void 0&&(t.extensions=h),e.tools&&(t.tools={listChanged:m}),e.resources&&(t.resources={listChanged:m,subscribe:m}),e.prompts&&(t.prompts={listChanged:m}),{supportedVersions:n.supportedVersions,capabilities:t,serverInfo:n.serverInfo}}),_=o6.useSync(v6),v=H(function*(e){let t=yield*o6,n=e.inputResponses===void 0?void 0:yield*r(e.inputResponses).pipe(Ep);return v6(o6.of({...t,inputResponses:n,requestState:e.requestState}))}),y=H(function*(e,t){let n=YSe(e.inputRequests,t);if(Object.keys(n).length!==0)return yield*a9(400,new C6({code:-32021,message:`The request requires client capabilities that were not declared`,data:{requiredCapabilities:n}}))});return{"subscriptions/listen":H(function*(e,{client:t,requestId:r}){if(p===void 0)return yield*new C6({code:-32601,message:`Method not found: subscriptions/listen`});let i=yield*n.registrationPresence,a=yield*ef(yield*Gp),o=n.getListChangeRevision?.()??0,s=yield*Zd(n.subscribeServerNotifications,a),c={...i.tools&&e.notifications.toolsListChanged===!0?{toolsListChanged:!0}:{},...i.prompts&&e.notifications.promptsListChanged===!0?{promptsListChanged:!0}:{},...i.resources&&e.notifications.resourcesListChanged===!0?{resourcesListChanged:!0}:{},...i.resources&&e.notifications.resourceSubscriptions!==void 0?{resourceSubscriptions:e.notifications.resourceSubscriptions}:{}},l={"io.modelcontextprotocol/subscriptionId":r},u=new Set(c.resourceSubscriptions),d=yield*zC(64),f=yield*Id();yield*R(function*(){for(;;){let e=yield*Hoe(s);if(e.listChangeRevision!==void 0&&e.listChangeRevision<=o||e.targetClientId!==void 0&&e.targetClientId!==t.id)continue;let n=e.notification,r=HE(n).pipe(GE({ToolsChanged:()=>c.toolsListChanged===!0?U7:void 0,PromptsChanged:()=>c.promptsListChanged===!0?W7:void 0,ResourcesChanged:()=>c.resourcesListChanged===!0?H7:void 0,ResourceUpdated:e=>u.has(e.uri)?V7:void 0}),JE);if(r===void 0)continue;let i={tag:r._tag,payload:r.payloadSchema.make({_meta:{...n.metadata,...l},...n._tag===`ResourceUpdated`?{uri:n.uri}:{}})};if(!(yield*BC(d,i)))break}}).pipe(af(a),mp(ap(()=>n.markSubscriptionCancelled?.(t.id,r)??L)),mp(Ud(f,void 0)),fm),yield*p(Q5,t.id,{tag:G7._tag,payload:G7.payloadSchema.make({_meta:l,notifications:c})});let m=am($C(d).pipe(B(e=>p(Q5,t.id,e))));yield*Qre(m,Ld(f)),yield*n.terminateSubscription?.(`2026-07-28`,t.id,r,`Pending notification limit exceeded`)??L;let h=yield*J7(n.serverInfo);return z7.make({_meta:{...l,"io.modelcontextprotocol/serverInfo":h},resultType:`complete`})},Tp(i9)),"server/discover":H(function*(e){let t=yield*g,r=yield*r9({...n9,supportedVersions:Array.from(t.supportedVersions),capabilities:t.capabilities,instructions:n.serverInfo.instructions},n.serverInfo);return yield*i(r)},Tp(i9)),"resources/list":H(function*(t){let r=yield*_,i=yield*e.resources.list(r.protocol),o=yield*r9({...n9,resources:i.map(XSe)},n.serverInfo);return yield*a(o)},Tp(i9)),"resources/templates/list":H(function*(t){let r=yield*_,i=yield*e.resources.listTemplates(r.protocol),a=yield*r9({...n9,resourceTemplates:i.map(ZSe)},n.serverInfo);return yield*o(a)},Tp(i9)),"resources/read":H(function*(t){let r=yield*v(t),i=yield*e.resources.read(t.uri,r),a=i.contents.map(e9),o=yield*r9({...n9,contents:a,_meta:i._meta},n.serverInfo);return yield*s(o)},Tp(i9)),"prompts/list":H(function*(t){if(!(yield*n.registrationPresence).prompts)return yield*a9(404,new C6({code:D3,message:`Method not found`}));let r=yield*_,i=yield*e.prompts.list(r.protocol),a=yield*ep(i,QSe),o=yield*r9({...n9,prompts:a},n.serverInfo);return yield*c(o)},Tp(i9)),"prompts/get":H(function*(t){let r=yield*v(t),i=yield*e.prompts.get(t.name,t.arguments??{},r);if(i._tag===`InputRequired`){yield*y(i,r.protocol.clientCapabilities);let e=yield*J7(n.serverInfo);return yield*u(Z7(i,e))}let a=i.value,o=a.messages.map(e=>({role:e.role,content:t9(e.content)})),s=yield*r9({description:a.description,messages:o,_meta:a._meta},n.serverInfo);return yield*l(s)},Tp(i9)),"completion/complete":H(function*(t){let r=yield*_,i=yield*e.completions.complete({reference:t.ref.type===`ref/prompt`?{type:`prompt`,name:t.ref.name,title:t.ref.title}:{type:`resourceTemplate`,uriTemplate:t.ref.uri},argument:t.argument,context:t.context?.arguments===void 0?void 0:{arguments:t.context.arguments},metadata:t._meta},r),a=yield*r9({completion:Y7({values:Array.from(i.values),total:i.total,hasMore:i.hasMore}),_meta:i.metadata},n.serverInfo);return yield*d(a)},Tp(i9)),"tools/list":H(function*(t){let r=yield*_,i=yield*e.tools.list(r.protocol),a=yield*ep(i,$Se),o=yield*r9({...n9,tools:a},n.serverInfo);return yield*f(o)},Tp(i9)),"tools/call":H(function*(t){let r=yield*v(t),i=(yield*e.tools.list(r.protocol)).find(e=>e.name===t.name),a=yield*Hp(pM);if(i!==void 0&&Ii(a)){let e=[{schema:i.inputSchema,argument:t.arguments,path:``}];for(;e.length>0;){let{schema:t,argument:n,path:r}=e.pop();if(!rn(t))continue;let i=t[`x-mcp-header`];if(typeof i==`string`){let e=`mcp-param-${i.toLowerCase()}`;if(!qSe(a.value.headers[e],n))return yield*a9(400,new C6({code:A3,message:`${e} does not match argument '${r}'`}))}if(rn(t.properties))for(let[i,a]of Object.entries(t.properties))e.push({schema:a,argument:rn(n)&&Object.hasOwn(n,i)?n[i]:void 0,path:r===``?i:`${r}.${i}`})}}let o=yield*e.tools.call({name:t.name,arguments:t.arguments??{}},r).pipe(xp([`ToolExecutionError`,`InvalidToolInput`],e=>F(u6.Complete(X3.make({content:[H3.make({type:`text`,text:e.message})],isError:!0})))));if(o._tag===`InputRequired`)return yield*y(o,r.protocol.clientCapabilities),yield*$7(o,n.serverInfo);let s=o.value,c=s.content.map(t9);return yield*$7(u6.Complete({content:c,structuredContent:s.structuredContent,isError:s.isError,_meta:s._meta}),n.serverInfo)},Tp(i9)),"notifications/cancelled":H(function*(e){return yield*L})}},toReverseClient:()=>({listRoots:()=>z(o9(`roots/list`)),createMessage:()=>z(o9(`sampling/createMessage`)),elicit:()=>z(o9(`elicitation/create`))}),projectNotification:e=>D6(e)?F(void 0):E6({supportsProgressMessage:!0},e),normalizeCancellation:tCe}),nCe=aSe,rCe=Fxe,c9=/*#__PURE__*/ new WeakMap,l9=/*#__PURE__*/ Ea(`effect/ai/McpServer/RequestNotificationQueue`,{defaultValue:()=>void 0}),u9=e=>e._tag===`Progress`||e._tag===`LoggingMessage`,iCe=/*#__PURE__*/ Fbe.omit(`notifications/elicitation/complete`),d9=/*#__PURE__*/ Mx(Q3),aCe=e=>{switch(e.tag){case`notifications/cancelled`:return p6.Cancelled({requestId:e.payload.requestId,reason:e.payload.reason,metadata:e.payload._meta});case`notifications/progress`:return p6.Progress({progressToken:e.payload.progressToken,progress:e.payload.progress,total:e.payload.total,message:e.payload.message,metadata:e.payload._meta});case`notifications/message`:return p6.LoggingMessage({level:e.payload.level,logger:e.payload.logger,data:e.payload.data,metadata:e.payload._meta});case`notifications/resources/updated`:return p6.ResourceUpdated({uri:e.payload.uri,metadata:e.payload._meta});case`notifications/resources/list_changed`:return p6.ResourcesChanged({metadata:e.payload?._meta});case`notifications/tools/list_changed`:return p6.ToolsChanged({metadata:e.payload?._meta});case`notifications/prompts/list_changed`:return p6.PromptsChanged({metadata:e.payload?._meta});default:return}},f9=(e,t)=>{let n=Wp(e,o6,t.requestContext),r=t.requestContext.requestMetadata,i=N(r,`io.modelcontextprotocol/logLevel`)?r[`io.modelcontextprotocol/logLevel`]:void 0;return d9(i)&&(n=Wp(n,Kd,m6[i].effect)),t.serverClient===void 0?n:Wp(n,s6,t.serverClient)};var p9=class e extends (/*#__PURE__*/ P()(`effect/ai/McpServer`)){static make=/*#__PURE__*/ R(function*(){let t=yield*Hbe,n=Ga(),r=[],i=[],a=[],o=yield*LC(),s={consumers:0,listChangeRevision:0,requestEndpoints:0},c=()=>s.consumers===0&&s.requestEndpoints>0,l=/* @__PURE__ */ new Map,u=(yield*Co).makeDispatcher(),d=yield*aN(iCe,{spanPrefix:`McpServer/Notifications`,onFromClient:e=>Id().pipe(B(t=>fp(n=>{let r=e.message;if(r._tag!==`Request`)return L;let i=aCe(r);if(i===void 0)return L;let a={notification:i,delivered:t,requestContext:ha(n.context,o6),requestHeaders:ha(n.context,pM)?.headers},f=ap(()=>d.write({clientId:0,requestId:r.id,_tag:`Exit`,exit:Ed})),p=va(n.context,l9);if(p!==void 0&&a.requestContext!==void 0&&u9(i))return VC(p,a),mp(Ld(t),f);if(c())return f;let m=!1;if(r.tag.includes(`list_changed`)){let e=++s.listChangeRevision,t=l.get(r.tag);t===void 0?(a.listChangeRevision=e,m=!0,l.set(r.tag,a),u.scheduleTask(()=>{l.delete(r.tag),VC(o,a)},0)):t.listChangeRevision=e}else m=!0,VC(o,a);return m&&a.requestContext!==void 0&&s.consumers>0?mp(Ld(t),f):f})))}),f=e.of({notifications:d.client,notifyElicitationComplete:({clientId:e,elicitationId:t})=>c()?L:Id().pipe(B(n=>BC(o,{notification:p6.ElicitationComplete({elicitationId:t}),targetClientId:e,delivered:n}).pipe(mp(ap(()=>s.consumers>0?Ld(n):L))))),get tools(){return n},addTool:e=>R(function*(){let r=n.findIndex(({tool:t})=>t.name===e.tool.name);r===-1?n.push(e):n[r]=e;let i=ha(e.annotations,l6);yield*t.tools.register({descriptor:new Y3({...e.tool,title:e.tool.title??e.tool.annotations?.title}),isVisible:e=>i===void 0||i({protocolVersion:e.protocolVersion,capabilities:e.clientCapabilities,clientInfo:e.clientInfo}),handle:(t,n)=>f9(e.handle(t.arguments),n).pipe(qre({InternalError:t=>z(new Bbe({name:e.tool.name,message:t.message})),InvalidParams:t=>z(new(n.requestContext.requestState===void 0&&n.requestContext.inputResponses===void 0?Rbe:zbe)({name:e.tool.name,message:t.message}))}),V(e=>on(e,`InputRequired`)?u6.InputRequired(e):u6.Complete(e)))}),yield*d.client[`notifications/tools/list_changed`]({})}),callTool:e=>R(function*(){let n=yield*s6,r=yield*t.tools.call(e,_6(n)).pipe(Tp(e=>new P3({message:e._tag===`ToolNotFound`?`Tool '${e.name}' not found`:e.message})));return r._tag===`InputRequired`?yield*new P3({message:`Client input is not supported by this MCP protocol`}):r.value}),get resources(){return r},get resourceTemplates(){return i},addResource:e=>R(function*(){let n=r.findIndex(({resource:t})=>t.uri===e.resource.uri);n===-1?r.push(e):r[n]=e,yield*t.resources.register({descriptor:e.resource,isVisible:t=>{let n=ha(e.annotations,l6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},read:t=>f9(e.handle,t)}),yield*d.client[`notifications/resources/list_changed`]({})}),addResourceTemplate:({annotations:e,completions:n,handle:r,routerPath:a,template:o})=>R(function*(){let s=i.findIndex(({template:e})=>e.uriTemplate===o.uriTemplate);s===-1?i.push({template:o,annotations:e}):i[s]={template:o,annotations:e};let c=pCe();c.add(a,!0),yield*t.resources.registerTemplate({descriptor:o,isVisible:t=>{let n=ha(e,l6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},match:e=>{let t=c.find(e);if(t===void 0)return;let n=[];for(let e of Object.keys(t.params))n[Number(e)]=t.params[e];return n},read:(e,t,n)=>f9(r(e,Array.from(t)),n)});for(let[e,r]of Object.entries(n))yield*t.completions.register(`resource/${o.uriTemplate}/${e}`,(e,t)=>f9(r(e.argument.value,e.context),t).pipe(V(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*d.client[`notifications/resources/list_changed`]({})}),findResource:e=>R(function*(){let n=yield*s6;return yield*t.resources.read(e,_6(n)).pipe(xp(`ResourceNotFound`,e=>z(new P3({message:`Resource '${e.uri}' not found`}))))}),get prompts(){return a},addPrompt:e=>R(function*(){let n=a.findIndex(({prompt:t})=>t.name===e.prompt.name);n===-1?a.push(e):a[n]=e,yield*t.prompts.register({descriptor:e.prompt,isVisible:t=>{let n=ha(e.annotations,l6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},get:(t,n)=>f9(e.handle(t),n).pipe(V(e=>on(e,`InputRequired`)?u6.InputRequired(e):u6.Complete(e)))});for(let[n,r]of Object.entries(e.completions))yield*t.completions.register(`prompt/${e.prompt.name}/${n}`,(e,t)=>f9(r(e.argument.value,e.context),t).pipe(V(e=>({values:e.completion.values,total:e.completion.total,hasMore:e.completion.hasMore,metadata:e._meta}))));yield*d.client[`notifications/prompts/list_changed`]({})}),getPromptResult:H(function*({arguments:e,name:n}){let r=yield*s6,i=yield*t.prompts.get(n,e??{},_6(r)).pipe(xp(`PromptNotFound`,()=>new P3({message:`Prompt '${n}' not found`})));return i._tag===`Complete`?i.value:yield*new P3({message:`Client input is not supported by this MCP protocol`})}),completion:H(function*(e){let n=yield*s6,r=e.ref,i=yield*t.completions.complete({reference:r.type===`ref/resource`?{type:`resourceTemplate`,uriTemplate:r.uri}:{type:`prompt`,name:r.name},argument:e.argument,context:e.context},_6(n));return{_meta:i.metadata,completion:{values:i.values,total:i.total,hasMore:i.hasMore}}})});return c9.set(f,{core:t,notifications:o,notificationDelivery:s}),f});static layer=/*#__PURE__*/ bf(e)(e.make)};const m9=`mcp-session-id`,h9=/*#__PURE__*/ new WeakMap,g9=/*#__PURE__*/ new WeakMap,_9=e=>`${typeof e}:${e}`;var v9=class extends Do{};const y9=/*#__PURE__*/ H(function*(e,t,n,r){let i=yield*mN,a=yield*p9,o=yield*Kd,s=n===`http`,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map,d=e=>{l.delete(e),c.delete(e),t.disconnect(e)},f=(e,t,n)=>i.send(e,{_tag:`Exit`,requestId:t,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:n}]}}),p=(e,t)=>{let n=u.get(e);if(n===void 0)return;let r=n.filter(e=>e!==t);r.length===0?u.delete(e):u.set(e,r)},m=yield*Loe(),h=(e,n,r)=>ap(()=>{let a=t.selectProtocol(e),o=a.serverNotificationRpcs.requests.get(r.tag);return o===void 0?up(`MCP protocol ${e} does not define server notification ${r.tag}`):a.payloadCodecs(o).encode(r.payload).pipe(Ep,B(e=>i.send(n,{_tag:`Request`,id:``,tag:r.tag,payload:e,headers:[],isNotification:!0})))}),g=(e,t)=>{let n=l.get(e),r=_9(t),i=n?.get(r);return i!==void 0&&(n.set(r,{...i,cancelled:!0}),!0)},_=(e,t,n,r)=>ap(()=>g(t,n)?s?i.end(t):h(e,t,{tag:`notifications/cancelled`,payload:{requestId:n,reason:r}}):L),v,{core:y,notificationDelivery:b,notifications:x}=c9.get(a),S=r?.handlers??(yield*t.installHandlers({core:y,subscribeServerNotifications:Boe(m),getListChangeRevision:()=>b.listChangeRevision,...!i.supportsNotifications||e.allowSubscriptions===!1?{}:{sendNotification:h,markSubscriptionCancelled:(e,t)=>I(()=>{g(e,t)}),terminateSubscription:_},defaultLogLevel:o,serverInfo:e})),ee=yield*use({lookup:H(function*(e){let n=t.selectProtocol(e.profile.protocolVersion),r,a=yield*sN.make(H(function*(t){let n=0;return r=e=>t(n,e),{send(t,r,a){if(n=t,r._tag===`Request`){let t=_9(r.id),n=u.get(t)??[];return n.push(e),u.set(t,n),i.send(e.clientId,{_tag:`Request`,id:r.id,tag:r.tag,payload:r.payload,headers:[]}).pipe(Xp(()=>I(()=>p(t,e))))}return r._tag===`Interrupt`?(p(_9(r.requestId),e),h(e.profile.protocolVersion,e.clientId,{tag:`notifications/cancelled`,payload:{requestId:r.requestId}})):L},supportsAck:!0,supportsTransferables:!1,supportsStructuredClone:!1,codecFor:i.codecFor}}));return{client:yield*n.makeReverseClient(e.profile).pipe(Wp(sN,a)),write:r}}),idleTimeToLive:1e4}),C=c6.of((e,{client:n,headers:r,payload:i,rpc:a})=>{let s=t.resolveRequest(n.id,r);if(!a._tag.endsWith(`/initialize`)&&!s){let e=xC(),t=ha(e.context,pM);return t&&xM(t,()=>F(fA({status:r[m9]===void 0?400:404}))),up(/* @__PURE__ */ Error(`Mcp-Session-Id does not exist`))}let l=s?.initializePayload??i,u=c.get(n.id),d=s?.protocol??u?.protocol??t.protocolForInternalTag(a._tag);if(!mCe(d.protocolVersion)||d.protocolVersion===`2026-07-28`)return up(`Unsupported selected MCP protocol version: ${d.protocolVersion}`);let f=s?.negotiatedProfile??{protocolVersion:d.protocolVersion,clientCapabilities:l.capabilities,clientInfo:l.clientInfo};u!==void 0&&(u.profile=f);let p=o6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,requestMetadata:l._meta});return Wp(Wp(Wp(e,s6,s6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,initializePayload:l,requestMetadata:rn(i)&&rn(i._meta)?i._meta:void 0,getClient:RT(ee,new v9({clientId:n.id,profile:f})).pipe(V(({client:e})=>e))})),o6,p),Kd,t.effectLogLevel(n.id,r,o))}),te=mN.of({...i,send:(e,t)=>{if(t._tag===`Exit`){let r=l.get(e),a=_9(t.requestId),o=r?.get(a);if(r!==void 0&&r.delete(a)&&r.size===0&&l.delete(e),o?.cancelled===!0)return n===`custom`?L:(o.httpPost!==void 0&&o.httpPost.expected--,h9.set(t,t.requestId),i.send(e,t));if(t.exit._tag===`Failure`&&!t.exit.cause.some(e=>e._tag===`Fail`))return i.send(e,{_tag:`Exit`,requestId:t.requestId,exit:{_tag:`Failure`,cause:[{_tag:`Fail`,error:new F3({message:`Internal error`})}]}})}return i.send(e,t)},run:e=>(v=e,i.run((n,r)=>{let i=xC(),a=r,o=s?ha(i.context,pM):void 0;switch(o!==void 0&&a._tag!==`Eof`&&xM(o,(e,t)=>F(t.status===200&&t.body._tag===`Uint8Array`&&t.body.contentLength===0?fA({headers:kg(t.headers,`content-type`),status:202}):t)),a._tag){case`Request`:{if(o!==void 0&&a.isNotification!==!0){let e=g9.get(o)??{expected:0};e.expected++,g9.set(o,e)}let r=s?_a(xC().context,pM).headers:wg(a.headers),u=a.tag===`notifications/cancelled`&&typeof a.payload==`object`&&a.payload!==null&&`requestId`in a.payload&&(typeof a.payload.requestId==`string`||typeof a.payload.requestId==`number`)?l.get(n)?.get(_9(a.payload.requestId)):void 0,p=u===void 0?t.prepareRequest(n,r,a):F(u.prepared);return R(function*(){let u=yield*p,m=c.get(n);s&&m===void 0&&(yield*$d(_a(i.context,Jd),I(()=>d(n))));let h=u.binding,_=u.protocol;if(c.set(n,{protocol:_,profile:u.profile??m?.profile,sessionHeaders:s&&r[m9]!==void 0?wg({[m9]:r[m9]}):m?.sessionHeaders}),a.tag===`invalid/json-rpc-batch`)return yield*f(n,a.id,new M3({message:`JSON-RPC batches are not supported`}));o!==void 0&&h!==void 0&&xM(o,(e,i)=>F(t.resolveRequest(n,r)===void 0?fA({status:404}):SA(i,`mcp-protocol-version`,h.protocol.protocolVersion)));let v=t.routeClientRequest(_,a),y=t.clientRpcs.requests.get(v.tag),b=_.clientNotificationRpcs.requests.has(a.tag);if(y&&b&&a.isNotification){if(!h&&_.runtime._tag===`Stateful`){o&&xM(o,()=>F(fA({status:r[m9]===void 0?400:404})));return}let t=_.payloadCodecs(y).decode(a.payload);return yield*R(function*(){let i=yield*t;if(a.tag===`notifications/cancelled`){let t=yield*_.normalizeCancellation(i),r=_9(t.requestId),a=n;if(s){if(h===void 0)return;let e=Array.from(l).find(([,e])=>e.get(r)?.prepared.binding===h);if(e===void 0)return;a=e[0]}return g(a,t.requestId)?yield*e(a,{_tag:`Interrupt`,requestId:t.requestId}):void 0}let o=S.mapUnsafe.get(y.key),c=o?o.handler(i,{rpc:y,requestId:XM(a.id),client:new GM(n),headers:r}):L;return yield*u.requestContext===void 0?c:Wp(c,o6,u.requestContext)}).pipe(Ap)}if(!y||b)return a.isNotification?void 0:yield*f(n,a.id,new N3({message:`Method not found: ${a.tag}`}));let x=yield*gp(_.payloadCodecs(y).decode(a.payload));if(Na(x))return yield*a.isNotification?L:f(n,a.id,new P3({message:`Invalid method parameters`}));if(a.isNotification!==!0){let e=l.get(n)??/* @__PURE__ */ new Map;e.set(_9(a.id),{requestId:XM(a.id),prepared:u,cancelled:!1,httpPost:o===void 0?void 0:g9.get(o)}),l.set(n,e)}let ee=e(n,v);return yield*u.requestContext===void 0?ee:Wp(ee,o6,u.requestContext)}).pipe(bp(e=>a.isNotification?L:f(n,a.id,on(e,`ProtocolError`)?C6.fromFeature(e):new P3({message:`Invalid request metadata`}))))}case`Ping`:case`Ack`:case`Interrupt`:return e(n,a);case`Eof`:return s||d(n),e(n,a);case`Pong`:case`Exit`:case`Chunk`:case`ClientProtocolError`:case`Defect`:{let e=a._tag===`Exit`?_9(a.requestId):void 0,r=s?t.resolveRequest(n,_a(xC().context,pM).headers):void 0,i=(e===void 0?void 0:u.get(e))?.find(e=>s?e.profile===r?.negotiatedProfile:e.clientId===n);if(a._tag===`Exit`&&i===void 0)return L;i!==void 0&&e!==void 0&&p(e,i);let o=i?.clientId??n,l=c.get(o),d=l?.protocol??t.protocols[0],f=i?.profile??l?.profile??{protocolVersion:d.protocolVersion,clientCapabilities:{},clientInfo:{name:`unknown`,version:`unknown`}};return RT(ee,new v9({clientId:o,profile:f})).pipe(B(({write:e})=>e(a)),Kp)}}}))});s&&(yield*t.onSessionTerminated(e=>{let t=[];for(let[n,r]of l)for(let{prepared:i,requestId:a}of r.values())i.binding===e&&g(n,a)&&t.push(v(n,{_tag:`Interrupt`,requestId:a}));return $f(t,{discard:!0})})),r===void 0&&(yield*qp(I(()=>{b.consumers++}),()=>I(()=>{b.consumers--})));let ne=/* @__PURE__ */ new Map;return yield*$C(r?.notifications??x).pipe(B(H(function*(e){let{delivered:n,listChangeRevision:r,notification:i,targetClientId:a,requestContext:l,requestHeaders:u}=e;D6(i)&&(yield*zoe(m,{notification:i,targetClientId:a,listChangeRevision:r}));let d=yield*te.clientIds;for(let e of c.keys())d.has(e)||(c.delete(e),t.disconnect(e));let f=u9(i),p=f&&l!==void 0?[l.clientId]:a===void 0?s?c.keys():t.deliveryClientIds():[a],h=[],g=!1;for(let e of p){if(a!==void 0&&e!==a)continue;if(!d.has(e)){t.disconnect(e);continue}if(!te.supportsNotifications)continue;let r=f&&l!==void 0?t.selectProtocol(l.protocolVersion):c.get(e)?.protocol;if(!r)continue;let s=ne.get(e),p=e===(a??l?.clientId);g||=p;let m=p?n:Fd();ne.set(e,m);let _=R(function*(){s!==void 0&&(yield*Ld(s));let n=yield*r.projectNotification(i);if(n===void 0||i._tag===`Progress`&&r.runtime._tag===`Stateless`&&l?.requestMetadata?.progressToken!==i.progressToken)return;if(i._tag===`LoggingMessage`&&r.runtime._tag===`Stateless`){let t=l?.requestMetadata,n=N(t,`io.modelcontextprotocol/logLevel`)?t[`io.modelcontextprotocol/logLevel`]:void 0;if(l?.clientId!==e||!d9(n)||Q3.literals.indexOf(i.level)<Q3.literals.indexOf(n))return}else if(!t.canDeliver(e,(l?.clientId===e?u:void 0)??c.get(e)?.sessionHeaders??Cg,i,o))return;let a=r.serverNotificationRpcs.requests.get(n.tag);if(!a)return;let d=yield*r.payloadCodecs(a).encode(n.payload);yield*te.send(e,{_tag:`Request`,id:``,tag:n.tag,payload:d,headers:[],isNotification:!0})}).pipe(Ap,Yp(I(()=>{Wd(m,Ed),ne.get(e)===m&&ne.delete(e)})));h.push(_)}g||(yield*Ud(n,void 0)),yield*$f(h,{concurrency:`unbounded`,discard:!0}).pipe(fm({startImmediately:!0}))})),Ap,am,fm),yield*Ile(t.clientRpcs,{spanPrefix:`McpServer`,disableFatalDefects:!0}).pipe(Wp(mN,te),Wp(c6,C),zp(S))},Kp),oCe=(e,t)=>Cf(R(function*(){let n=yield*V6;yield*fm(y9(e,n,t))})).pipe(jf(p9.layer)),sCe=e=>{let t=U6(e.protocols);return oCe(e,`http`).pipe(Af(lCe(e)),Af(t),Af(Tle()))},cCe=e=>Cf(R(function*(){let t=yield*V6,n=t.protocols.find(e=>e.runtime._tag===`Stateful`);if(n!==void 0)return yield*new hd(`McpServer.layerHttpRequestScoped does not support the sessionful MCP protocol ${n.protocolVersion}`);let r=yield*p9,{core:i,notificationDelivery:a}=c9.get(r),o=yield*t.installHandlers({core:i,subscribeServerNotifications:up(`Subscriptions are disabled for request-scoped MCP servers`),getListChangeRevision:()=>a.listChangeRevision,defaultLogLevel:yield*Kd,serverInfo:e});yield*qp(I(()=>{a.requestEndpoints++}),()=>I(()=>{a.requestEndpoints--})),yield*b9(e,R(function*(){let{httpEffect:n,protocol:i}=yield*hN().pipe(Wp(eN,x9)),a=yield*LC();return yield*y9(e,t,`http`,{notifications:a,handlers:o}).pipe(Wp(mN,i),Wp(p9,r),fm({startImmediately:!0})),yield*Wp(n,l9,a)}))})).pipe(jf(p9.layer),Af(U6(e.protocols))),lCe=e=>bf(mN)(R(function*(){let{httpEffect:t,protocol:n}=yield*hN().pipe(Wp(eN,x9));return yield*b9(e,t),n})),b9=/*#__PURE__*/ H(function*(e,t){let n=yield*V6,r=yield*CM,i=e.allowSessionTermination===!0&&n.protocols.some(e=>e.runtime._tag===`Stateful`),a=F(fA({status:403})),o=t=>n=>C9(n,e.allowedOrigins)?t(n):a,s=F(fA({status:405,headers:{allow:i?`POST, DELETE`:`POST`}})),c=o(()=>s);for(let t of[`GET`,`PUT`,`PATCH`,`OPTIONS`])yield*r.add(t,e.path,c);yield*r.add(`DELETE`,e.path,i?o(e=>n.terminateHttpSession(e.headers)):c),yield*r.add(`POST`,e.path,r=>{if(!C9(r,e.allowedOrigins))return F(fA({status:403}));if(w9(r.headers[`content-type`])[0]!==`application/json`)return F(fA({status:415}));let i=w9(r.headers.accept);return!i.includes(`application/json`)||!i.includes(`text/event-stream`)?F(fA({status:406})):R(function*(){let e=yield*gp(B(r.text,Px(HS))),i=n.admitHttp(r.headers,e);if(i._tag===`Rejected`)return i.response;let a=e=>{let t=e.body._tag===`Uint8Array`&&e.body.body.subarray(0,-1).includes(10);return i.isSubscription||e.body._tag===`Stream`||t?fCe(e,i.isSubscription):e};return i.acknowledge?yield*Sp(V(t,a),()=>F(fA({status:202}))):yield*B(t,e=>e.body._tag!==`Uint8Array`||e.body.body.length>0?F(a(e)):g9.get(r)?.expected===0?F(xA(YT,{contentType:`text/event-stream`})):up(/* @__PURE__ */ Error(`MCP request ended without writing its response`)))})})}),x9=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ dCe();return eN.of({contentType:e.contentType,includesFraming:!0,codecFor:e.codecFor,makeUnsafe:()=>{let t=e.makeUnsafe();return{decode:t.decode,encode:e=>{let n=t.encode(e);return typeof n==`string`?`${n}\n`:n}}}})})(),uCe=/*#__PURE__*/ Mx(/*#__PURE__*/ hS(`Cause`,{data:/*#__PURE__*/ Soe([/*#__PURE__*/ hS(`Fail`,{error:/*#__PURE__*/ voe(I3)})])})),S9=e=>Array.isArray(e)?e.map(S9):!rn(e)||!N(e,`error`)?e:uCe(e.error)?{...e,error:e.error.data[0].error}:e;function dCe(e){let t=tN(e);return eN.of({...t,makeUnsafe:()=>{let e=t.makeUnsafe(),n=/* @__PURE__ */ new Set;return{decode:e.decode,encode:t=>{if(rn(t)){let e=h9.get(t);e!==void 0&&(h9.delete(t),n.add(e))}let r=e.encode(t);if(typeof r!=`string`||n.size===0&&!r.includes(`"_tag":"Cause"`))return r;let i=JSON.parse(r);if(n.size>0){let e=e=>!(rn(e)&&!N(e,`method`)&&(typeof e.id==`string`||typeof e.id==`number`)&&n.delete(e.id));if(Array.isArray(i)){let t=i.filter(e);if(t.length===0)return;i=t}else if(!e(i))return}return JSON.stringify(S9(i))}}}})}const fCe=(e,t)=>{let n=new TextEncoder,r=new TextDecoder,i=e=>n.encode(r.decode(e).trimEnd().split(`
535
+ `).map(e=>`data: ${e}\n\n`).join(``)),a={status:e.status,statusText:e.statusText,headers:kg(e.headers,`content-type`),cookies:e.cookies,contentType:`text/event-stream`};if(e.body._tag===`Stream`){let r=e.body.stream.pipe(eE(i));if(!t)return xA(r,a);let o=xse(`15 seconds`).pipe(jse(1),eE(()=>n.encode(`: keepalive
536
+
537
+ `)));return xA(nE(r,o,{haltStrategy:`left`}),a)}return e.body._tag===`Uint8Array`?mA(i(e.body.body),a):SA(e,`content-type`,`text/event-stream`)},C9=(e,t)=>{let n=e.headers.origin;return n===void 0||(t??[]).includes(n)},w9=e=>e===void 0?[]:e.split(`,`).flatMap(e=>{let[t,...n]=e.split(`;`),r=n.map(e=>e.trim().toLowerCase()).find(e=>e.startsWith(`q=`));if(r!==void 0){let e=Number(r.slice(2));if(!Number.isFinite(e)||e<=0||e>1)return[]}return[t.trim().toLowerCase()]}),pCe=()=>{let e=tA({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(t,n)=>{e.on(`GET`,`/${t}`,n)},find:t=>e.find(`GET`,`/${t}`)}},mCe=e=>e===`2024-11-05`||e===`2025-03-26`||e===`2025-06-18`||e===`2025-11-25`||e===`2026-07-28`,T9=s9,hCe=[s9,nCe,rCe],gCe=Mx(JI),_Ce=Mx(G(JI)),E9=e=>XI(NI(e)),D9=e=>{let t=NI(e),n=XI(t);if(n!==void 0)return{kind:n,many:!1};if(!Nv(t)||t.encoding!==void 0)return;let[r,...i]=new Set([...t.elements,...t.rest].map(E9));return r===void 0||i.length>0?void 0:{kind:r,many:!0}},vCe=e=>{let t=e.context?.isOptional===!0,n=NI(e);if(t&&Fv(n)&&n.types.length===2){let[e,...t]=n.types.filter(e=>!Sie(e)),r=e===void 0||t.length>0?void 0:E9(e);return r===void 0?void 0:{kind:r,many:!1}}let r=D9(n);return r===void 0||t&&r.many?void 0:r},O9=e=>{let t=NI(e.ast),n=D9(t);if(n!==void 0)return{fields:[{name:void 0,...n}],rest:void 0};if(!Pv(t)||t.encoding!==void 0)return{fields:[],rest:e};let r=t.propertySignatures.flatMap(({name:e,type:t})=>{let n=vCe(t);return n===void 0?[]:[{name:String(e),...n}]});if(r.length===0)return{fields:r,rest:e};let i=new Set(r.map(({name:e})=>e)),a=t.propertySignatures.filter(({name:e})=>!i.has(e)),{identifier:o,...s}=t.annotations??{};return{fields:r,rest:a.length===0&&t.indexSignatures.length===0?void 0:Bx(new ly(a,t.indexSignatures,s))}},yCe=e=>[...kv(e)?e.typeParameters:[],...Nv(e)?[...e.elements,...e.rest]:[],...Pv(e)?[...e.propertySignatures,...e.indexSignatures].map(({type:e})=>e):[],...Fv(e)?e.types:[],...Iv(e)?[e.thunk()]:[],...(e.encoding??[]).map(({to:e})=>e)],bCe=e=>{let t=/* @__PURE__ */ new Set,n=[e];for(let e=n.pop();e!==void 0;e=n.pop())if(!t.has(e)){if(t.add(e),YI(e))return!0;n.push(...yCe(e))}return!1},xCe=(e,{rest:t})=>[e.input,...e.error,...t===void 0?[]:[t]].some(({ast:e})=>bCe(e)),SCe=(e,t)=>e.fields.flatMap(({name:e,kind:n,many:r})=>{let i=e===void 0?t:N(t,e)?t[e]:void 0;return(r?_Ce(i)?i:[]:gCe(i)?[i]:[]).map(t=>({kind:n,field:e,value:t}))}),CCe=Mx(q3),k9=(e,t)=>{let n=pC(e,{onExcessProperty:t?`error`:`ignore`}),[r,i]=Ut(n.schema.$ref)?Jb(n.schema.$ref)??[]:[],a=r===`$defs`&&i!==void 0?n.definitions[i]:n.schema;return a===void 0||Object.keys(n.definitions).length===0?a:{...a,$defs:n.definitions}},wCe=e=>{let t=e.map(([e])=>e).filter(e=>!CCe(k9(mC(e.input),!0))).map(({name:e})=>e);if(t.length>0)throw Error(`MCP tool input must be one object with keys, such as a struct: ${t.join(`, `)}`);let n=e.filter(([e,t])=>xCe(e,t)).map(([{name:e}])=>e);if(n.length>0)throw Error(`MCP media must be the success or an array of it, or a top-level field of a struct success, one, optional or a required array: ${n.join(`, `)}`)},TCe=e=>new X3({isError:!0,content:[{type:`text`,text:e}]}),A9=e=>e===void 0?[]:[{type:`text`,text:JSON.stringify(e)}],ECe=({kind:e,field:t,value:n})=>({type:e,data:n.data,mimeType:n.mimeType,...t===void 0?{}:{_meta:{"effect-actions/field":t}}}),DCe=(e,t)=>V(Nx(q3)(k9(mC(e.input),!0)),n=>new Y3({name:e.name,description:e.description,inputSchema:n,outputSchema:t,annotations:{...e.mcp.title===void 0?{}:{title:e.mcp.title},...lbe(e)},_meta:e.mcp._meta===void 0?void 0:{...e.mcp._meta}})),OCe=H(function*(e,t){let n=yield*p9,r=yield*GI(e),i=yield*Lp(),a=e=>Cm(e).pipe(mp(Sce(e)),vp(TCe(`Tool execution failed due to an internal server error.`))),o=e=>sd(e)?a(e):cp(e);for(let[e,a]of r){let r=O9(e.success),s=r.fields.length===0?void 0:r,c=s===void 0?mC(e.success):s.rest===void 0?void 0:mC(s.rest),l=c===void 0?void 0:yield*Nx(J3)(k9(c,!1)).pipe(Ep),u=yield*DCe(e,l).pipe(Ep),d=Nx(mC(e.input),KI),f=e=>{let t=Ix(mC(e));return e=>Ep(t(e))},p=f(e.success),m=f(K(II(e))),h=t===void 0||e.caller===SI?a:e=>kB(lfe(t,a(e))),g=new Set(s?.fields.map(({name:e})=>e)),_=(e,t)=>{if(s===void 0)return new X3({isError:!1,structuredContent:e,content:A9(e)});let n=SCe(s,t).map(ECe);if(c===void 0)return new X3({isError:!1,content:n});let r=nn(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!g.has(e))):e;return new X3({isError:!1,structuredContent:r,content:[...A9(r),...n]})};yield*n.addTool({tool:u,annotations:la(),handle:t=>iie({tool:e.name,parameters:t??{}}).pipe(mp(()=>d(t??{})),Tp(({message:t})=>new P3({message:new ube({toolName:e.name,description:t}).message})),B(e=>h(e).pipe(Ip({onFailure:e=>V(m(e),e=>new X3({isError:!0,content:A9(e)})),onSuccess:e=>V(p(e),t=>_(t,e))}))),Sp(o),Up(e=>Ca(i,e)))})}}),kCe=(e,t,n=yf,r)=>{MI(`MCP tool`,e.flatMap(e=>e.actions));let i=e.flatMap(e=>e.actions.map(e=>[e,O9(e.success)]));wCe(i);let a=new Set(i.map(([{name:e}])=>e)),o=R(function*(){let t=(yield*p9).tools.flatMap(({tool:e})=>a.has(e.name)?[e.name]:[]);if(t.length>0)return yield*up(/* @__PURE__ */ Error(`Duplicate MCP tool: ${t.join(`, `)}, claimed by an action and a native feature`));yield*OCe(e,r)});return Cf(o).pipe(Af(n),Af(t),Sre,WI(e))},ACe=/* @__PURE__ */ new Set([`server/discover`,`tools/list`,`notifications/cancelled`]),jCe=e=>{let t=new Set(e.filter(({caller:e})=>e===SI).flatMap(({name:e})=>[e,`=?base64?${Dh(e)}?=`]));return e=>{if(t.size===0||e[`mcp-protocol-version`]!==T9.protocolVersion)return!0;let n=e[`mcp-method`];if(n===void 0)return!0;if(ACe.has(n))return!1;if(n!==`tools/call`)return!0;let r=e[`mcp-name`];return r===void 0||!t.has(r)}},MCe=e=>Pp(e.json,{onFailure:()=>!0,onSuccess:t=>!N(t,`method`)||t.method===e.headers[`mcp-method`]});function NCe(e,{actions:t,features:n,path:r=`/mcp`,authentication:i,requestScoped:a,allowSubscriptions:o=n!==void 0,...s}){let c=UI(VI(e),t),l=c.flatMap(e=>e.actions);CI(l,i);let u=kCe(c,a===!0?cCe({...s,path:r,protocols:[T9]}):sCe({...s,path:r,protocols:hCe,allowSessionTermination:!0,allowSubscriptions:o}),n,i);if(i===void 0)return u;let d=jCe(l),f=MM(V(tL(i),e=>t=>B(pM,n=>n.method!==`POST`||d(n.headers)?e.http(t,!1):B(MCe(n),n=>e.http(t,n)))));return u.pipe(Af(f.layer))}var PCe=`0.26.0`;const FCe=(e,t)=>rp(()=>RW({key:e,data:t})),ICe=(e,t)=>rp(()=>zW({key:e,data:t})),LCe=async(e,t)=>(await Promise.all([KG(e.authCookies.sessionToken.name,t,e.secret),KG(e.authCookies.dontRememberToken.name,`true`,e.secret)])).map(e=>e.split(`;`)[0]).join(`; `),RCe=(e,t)=>ym(`OwnerAccount.providerSession`)(function*(n){let r=new Date((yield*Nf)+6e4),i=yield*qp(U4(()=>e.internalAdapter.createSession(n,!0,{expiresAt:r},!0)),t=>np(()=>e.internalAdapter.deleteSession(t.token))),a=yield*U4(()=>LCe(e,i.token));return new Headers({origin:t,cookie:a})}),zCe=tH(W({id:U}));var j9=class e extends P()(`clankerauth/OwnerAccount`){static layer=bf(e,R(function*(){let{sql:e}=yield*aH,{auth:t,context:n}=yield*a3,{baseURL:r}=yield*Z4,i=yield*Sw(1),a=RCe(n,r),o=ym(`OwnerAccount.find`)(function*(){let t=yield*e`SELECT id FROM user LIMIT 1`;if(t.length)return(yield*zCe(t[0])).id});return{find:o,create:ym(`OwnerAccount.create`)(function*(e){if(yield*o())return yield*z(tV.of());let{headers:n}=yield*U4(()=>t.api.signUpEmail({body:{name:`Owner`,email:e.email.trim(),password:e.password},returnHeaders:!0}),{refused:V4,conflict:tV.of});return n.getSetCookie()},e=>i.withPermit(e)),caller:(e,t,n)=>({userId:e,email:t,writable:n,providerHeaders:a(e)})}}))},M9=class extends P()(`clankerauth/ResponseCookies`){};const BCe=V(j9,e=>({setupStatus:()=>e.find().pipe(V(e=>({required:!e}))),setupOwner:ym(`Administration.setup`)(function*(t){let n=yield*e.create(t);return yield*(yield*M9).add(n),{created:!0}})}));var N9=class extends jo(`Unauthorized`){constructor(e={}){super({message:e.message??`Authentication required`}),Object.defineProperty(this,"cause",{value:e.cause})}},P9=class extends fC()(`ProviderUnavailable`,{operation:U},{httpApiStatus:503}){constructor(e){super({operation:e.operation}),Object.defineProperty(this,"cause",{value:e.cause})}},F9=class extends jo(`InsufficientScope`){},VCe=class extends fC()(`ConfigurationError`,{message:U}){};const I9=vo(1),L9=(e,t)=>Rp(n=>yk(e).execute(t).pipe(Wp(PN,{...ha(n,PN),redirect:`manual`}),Tp(e=>new P9({operation:`http.request`,cause:e})),$re(e=>e.status<300||e.status>=400,e=>new P9({operation:`http.redirect`,cause:{status:e.status}})))),HCe=W({keys:G(W({kty:U,crv:Hx(U),x:Hx(U),kid:Hx(U),alg:Hx(U),use:Hx(U),key_ops:Hx(G(U))}))}),UCe=W({sub:IS,client_id:IS,scope:U,iat:CS,exp:CS}),WCe=W({list:U}),GCe=zde.pipe(eS({exp:CS})),KCe=()=>({jwks:/* @__PURE__ */ new Map,keyLists:/* @__PURE__ */ new Map}),R9=e=>new N9({cause:e}),qCe=vo(1),z9=_o(5),B9=ym(`Verifier.make`)(function*(e){let t=yield*fk,n=JSON.stringify([e.issuer,e.resource]),r=yield*dp({try:()=>({jwks:new URL(`${e.issuer}/jwks`).href,keyList:new URL(`/api/keyList`,e.issuer).href}),catch:()=>new VCe({message:`Invalid issuer URL`})}),i=ym(`Verifier.jwks`)(function*(){let e=yield*L9(t,jO(r.jwks));return e.status===200?(yield*KO(HCe)(e).pipe(Tp(e=>new P9({operation:`jwks.decode`,cause:e})))).keys.map(({key_ops:e,...t})=>e?{...t,key_ops:[...e]}:t):yield*new P9({operation:`jwks.fetch`,cause:{status:e.status}})},Kp),a=R(function*(){let t=e.store.jwks.get(e.issuer),n=yield*Nf;if(t!==void 0){let e=`keys`in t?qCe:z9;if(n-t.readAt<yo(e))return`keys`in t?t.keys:yield*new P9({operation:t.failure})}let r=yield*gp(i()),a=yield*Nf;return(Pa(r)||(e.store.jwks.get(e.issuer)?.readAt??-1/0)<n)&&e.store.jwks.set(e.issuer,Pa(r)?{readAt:a,keys:r.success}:{readAt:a,failure:r.failure.operation}),Pa(r)?r.success:yield*r.failure}),o=ym(`Verifier.signingKey`)(function*(e){let t={keys:[...yield*a]};return yield*rp({try:()=>dI(t)({alg:`EdDSA`,kid:e}),catch:R9})}),s=ym(`Verifier.signed`)(function*(t,n){let r=yield*dp({try:()=>gI(t),catch:R9});if(r.alg!==`EdDSA`||r.kid===void 0)return yield*R9();let i=yield*o(r.kid),a=yield*Nf,{payload:s}=yield*rp({try:()=>nI(t,i,{issuer:e.issuer,audience:e.resource,algorithms:[`EdDSA`],typ:n,currentDate:new Date(a)}),catch:R9});return s}),c=ym(`Verifier.jwt`)(function*(e){let t=yield*s(e,`at+jwt`);if(t.cnf!==void 0)return yield*R9();let n=yield*Nx(UCe)(t).pipe(Tp(R9));return{subject:n.sub,scopes:n.scope.split(` `).filter(Boolean),actor:{kind:`client`,clientId:n.client_id},expiresAt:n.exp*1e3}}),l=ym(`Verifier.keyList`)(function*(){let n=MO(r.keyList).pipe(UO({resource:e.resource})),i=yield*L9(t,n);if(i.status!==200)return yield*new P9({operation:`key-list.fetch`,cause:{status:i.status}});let{list:a}=yield*KO(WCe)(i).pipe(Tp(e=>new P9({operation:`key-list.decode`,cause:e}))),o=e=>new P9({operation:`key-list.verify`,cause:e}),c=yield*s(a,vI).pipe(xp(`Unauthorized`,e=>z(o(e)))),l=yield*Nx(GCe)(c).pipe(Tp(o));return{readAt:yield*Nf,expiresAt:l.exp*1e3,entries:new Map(l.keys.map(e=>[e.id,e.sealed]))}},Kp),u=R(function*(){let t=e.store.keyLists.get(n),r=yield*Nf;if(t!==void 0&&r-t.readAt<yo(z9))return t.failure===void 0?void 0:yield*new P9({operation:t.failure});let i=yield*gp(l().pipe(jp({duration:`3 seconds`,orElse:()=>z(new P9({operation:`key-list.timeout`}))}))),a=yield*Nf,o=e.store.keyLists.get(n),s=o?.failure!==void 0;if(Pa(i)){e.store.keyLists.set(n,{readAt:a,failure:void 0,held:i.success}),s&&(yield*wm(`clankerauth key list reads have recovered`));return}if((o?.readAt??-1/0)>=r)return yield*i.failure;let{operation:c}=i.failure;return e.store.keyLists.set(n,{readAt:a,failure:c,held:o?.held}),s||(yield*Sm(`clankerauth key list reads are failing; a held list decides until it expires`,{operation:c})),yield*i.failure}),d=R(function*(){let t=yield*gp(u),r=e.store.keyLists.get(n)?.held;return r!==void 0&&r.expiresAt>(yield*Nf)?r:yield*Na(t)?t.failure:new P9({operation:`key-list.expired`})}),f=ym(`Verifier.apiKey`)(function*(t){let r=n=>rp({try:()=>Hde(t,e.resource,n.entries),catch:R9}),i=yield*Nf,a=e.store.keyLists.get(n)?.held,o=a!==void 0&&i-a.readAt<yo(I9)&&a.expiresAt>i?a:yield*d,s=(yield*r(o))??(yield*B(d,e=>e===o?F(void 0):r(e)));return s===void 0||s.expiresAt!==null&&s.expiresAt<=(yield*Nf)?yield*R9():{subject:s.ownerId,scopes:s.scopes,actor:{kind:`key`,keyId:s.keyId},expiresAt:s.expiresAt??void 0}});return{verifyToken:ym(`Verifier.verifyToken`)(function*(t){let n=yield*t.startsWith(`clankerauth_`)?e.apiKeys===!1?z(R9()):f(t):c(t),r=e.requiredScopes?.find(e=>!n.scopes.includes(e));return r===void 0?n:yield*new F9({scope:r,actor:n.actor})})}}),JCe=ym(`AdministrationResource.make`)(function*(){let{auth:e}=yield*a3,{baseURL:t}=yield*Z4,n=`${t}/api/auth`,r=lV(t);return{protectedResource:{resource:r,authorizationServers:[n],scopesSupported:[uV.read,uV.write,...$4],scopesRequired:[uV.read,uV.write]},verifier:yield*B9({issuer:n,resource:r,store:KCe(),apiKeys:!1}).pipe(zp(FN.pipe(Af(_f(NN,(t,n)=>{let r=new Request(t,n);return r.headers.set(I4,`127.0.0.1`),e.handler(r)})))))}});QI(`whoami`,{description:`The verified subject, issuer and scopes behind this request's credential.`,readOnly:!0,caller:class extends P()(`@clankerauth/CurrentPrincipal`){},success:W({subject:IS,issuer:IS,scopes:G(U)})});const V9=(e,t)=>{let n=`Requires ${e}.`;return t.kind===`client`?new OI({message:n,scopes:[e]}):new OI({message:n})},YCe=(e,t)=>t===void 0||e.scopes.includes(t)?void 0:V9(t,e.actor),H9=e=>e instanceof N9?new EI({message:e.message}):e instanceof F9?V9(e.scope,e.actor):e,U9=(e,t)=>Tp(e.verifyToken(_g(t)),H9);ym(`Resource.layer`)(function*(e,{scopes:t,required:n},r){let i=new URL(`/`,r.publicUrl).href,a={resource:i,authorizationServers:[r.issuer],scopesSupported:t,scopesRequired:[n]},o=r.discovery===!1?void 0:a,s=yield*B9({issuer:r.issuer,resource:i,store:r.store,requiredScopes:[n],apiKeys:r.apiKeys}),c=e=>jp(e,{duration:`5 seconds`,orElse:()=>z(new P9({operation:`verify.timeout`}))}),l={verifyToken:e=>c(s.verifyToken(e))},u=ym(`Resource.principal`)(function*(e,t){let n=MB(e);if(Fi(n))return yield*new EI({message:`A bearer token is required.`});let r=yield*U9(l,n.value),i=YCe(r,t);return i===void 0?r:yield*i}),d=ym(`Resource.admit`)(function*(t,n){let r=yield*gp(u(t,n));if(Pa(r))return{ok:!0,principal:r.success};let i=jA(zB(r.failure,{authentication:e,protectedResource:o,authorization:t}));return{ok:!1,refusal:{status:i.status,headers:Object.fromEntries(i.headers),body:yield*np(()=>i.text())}}});return{resource:i,issuer:r.issuer,protectedResource:o,verifier:l,admit:d,watch:(e,t)=>am(R(function*(){let n=yield*u(e,t),r=yield*Nf,i=Math.max(0,(n.expiresAt??1/0)-r);return n.actor.kind===`key`?yield*Mp(Math.min(i,yo(I9))):(yield*Mp(i),yield*H9(new N9))}))}});const XCe=e=>JB(e,V(a3,e=>()=>R(function*(){let t=yield*pM,n=new Headers(t.headers),r=yield*U4(()=>e.auth.api.getSession({headers:n}),{unavailable:H4});return r?{providerHeaders:F(n),userId:r.user.id,email:r.user.email,writable:!0}:yield*new EI({message:`Owner session required`})}))),ZCe=tH(W({id:U,email:U})),QCe=e=>JB(cV,R(function*(){let{sql:t}=yield*aH,n=yield*j9,r=()=>new EI({message:`Owner authorization required`});return i=>R(function*(){let a=yield*U9(e.verifier,i).pipe(xp(`ProviderUnavailable`,()=>z(new XB({message:`Request could not be completed`}))));if(a.actor.kind!==`client`)return yield*r();let o=a.scopes.includes(uV.write);if(!o&&!a.scopes.includes(uV.read))return yield*new OI({message:`Insufficient scope`,scopes:[uV.read]});let s=yield*t`SELECT u.id, u.email FROM user u
538
+ JOIN oauthClient c ON c.clientId = ${a.actor.clientId}
539
+ WHERE u.id = ${a.subject} AND c.disabled IS NOT 1`;if(!s[0])return yield*r();let c=yield*ZCe(s[0]);return n.caller(c.id,c.email,o)})}),{protectedResource:e.protectedResource}),$Ce=e=>e.readOnly?L:B(aV,({writable:e})=>e?L:z(new OI({message:`This action requires the ${uV.write} scope`,scopes:[uV.write]}))),ewe=MM()(e=>R(function*(){let t=[],n=yield*Wp(e,M9,{add:e=>I(()=>t.push(...e))});return t.length?EA(n,Kh(t)):n}));function twe(e){return Tf(R(function*(){let{context:t}=yield*a3,n=yield*f3,r=yield*d3,i=yield*BCe,a=yield*s3,o=eL(WV,{listClients:n.list,createClient:n.create,updateClient:n.update,deleteClient:n.delete,revokeClient:n.revoke,blockClient:n.block,rotateClientSecret:n.rotate,setClientAccess:r.setAccess,getResource:r.get,putResource:r.put,deleteResource:r.delete,listApiKeys:a.list,createApiKey:a.create,updateApiKey:a.update,deleteApiKey:a.delete},{authorize:$Ce}),s=eL(HV,{setupStatus:i.setupStatus,setupOwner:i.setupOwner,keyList:({resource:e})=>a.keyList(e)}),c=yield*JCe(),l=oV(t.authCookies.sessionToken.name),u=KV(l),d=Df(gB(u,o).pipe(Af(XCe(l))),EM(`GET`,`/openapi.json`,vA(qR(u.api))),gB(u,s).pipe(Af(ewe.layer))),f=Df(NCe(o,{name:`clankerauth-admin`,version:PCe,allowedOrigins:e,instructions:`Owner administration. Listing needs ${uV.read} or ${uV.write}; every other action changes authorization policy and needs ${uV.write}. Create and rotate actions return secrets once.`,authentication:cV}),gB(qV,o)).pipe(Af(QCe(c)));return Df(d,f)}))}const W9=`clankerauth_forward`,G9=(e,t)=>vA({error:t},{status:e}),nwe=e=>Tf(R(function*(){let t=yield*Z4,{auth:n,context:r}=yield*a3,i=yield*i3,a=n=>{if(!URL.canParse(n))return;let r=new URL(n);return!r.username&&!r.password&&q4(r,t.allowInsecureHttp)&&K4(r.hostname,e)?r:void 0},o=_g(t.secret),s=new URL(`/login`,t.baseURL),c={domain:e,path:`/`,httpOnly:!0,secure:t.baseURL.startsWith(`https:`),sameSite:`lax`},l=r.authCookies.sessionToken.name,u=(e,n)=>{let r=new URL(e,t.baseURL);return r.searchParams.set(`rd`,n.href),r},d=e=>U4(()=>n.api.getSession({headers:new Headers({cookie:e})}),{unavailable:H4}),f=R(function*(){let e=yield*pM,{headers:r}=e,s=r[`x-forwarded-proto`],c=r[`x-forwarded-host`],f=s&&c?a(`${s}://${c}${r[`x-forwarded-uri`]??`/`}`):void 0;if(!f)return G9(400,`invalid_forwarded_request`);let p=new URL(e.url,t.baseURL).searchParams.get(`resource`),m=p&&(yield*i.application(p));if(!m)return G9(403,`unknown_resource`);let h=e.cookies[W9],g=h?yield*Kre(ICe(o,h)):Ni(),_=Ii(g)?yield*d(`${l}=${g.value}`):null;if(!_)return r[`sec-fetch-mode`]===`navigate`?pA(u(`/forward-auth/continue`,f)):G9(401,`unauthenticated`);let v=Math.floor((yield*Nf)/1e3),{token:y}=yield*U4(()=>n.api.signDocument({body:{typ:`at+jwt`,payload:{sub:_.user.id,aud:m.identifier,client_id:`forward-auth`,scope:m.scopes.join(` `),iat:v,exp:v+900}}}));return fA({status:204,headers:{authorization:`Bearer ${y}`}})}),p=R(function*(){let e=yield*pM,n=new URL(e.url,t.baseURL).searchParams.get(`rd`),r=n?a(n):void 0;if(!r)return G9(400,`invalid_return_url`);let i=e.cookies[l];if(!(i&&(yield*d(e.headers.cookie??``)))||!i)return pA(u(`/login`,u(`/forward-auth/continue`,r)));let s=yield*FCe(o,i);return yield*pA(r).pipe(TA(W9,s,c))}),m=R(function*(){let e=yield*pM,r=new URL(e.url,t.baseURL).searchParams.get(`rd`),i=r&&a(r)||s,{headers:o}=yield*U4(()=>n.api.signOut({headers:new Headers({cookie:e.headers.cookie??``}),returnHeaders:!0}),{refused:V4,unavailable:H4});return yield*EA(pA(i),Kh(o.getSetCookie())).pipe(TA(W9,``,{...c,maxAge:0}))});return Df(EM(`GET`,`/forward-auth`,bp(f,G4)),EM(`GET`,`/forward-auth/continue`,bp(p,G4)),EM(`GET`,`/forward-auth/logout`,bp(m,G4)))})),rwe=/* @__PURE__ */ new Set([`/sign-in/email`,`/sign-out`,`/get-session`,`/change-password`,`/jwks`,`/oauth2/register`,`/oauth2/authorize`,`/oauth2/token`,`/oauth2/consent`,`/oauth2/continue`,`/oauth2/public-client`,`/oauth2/introspect`,`/oauth2/revoke`,`/.well-known/oauth-authorization-server`]),iwe=/* @__PURE__ */ new Set([`/.well-known/oauth-protected-resource`,`/jwks`,`/oauth2/register`,`/oauth2/token`,`/oauth2/revoke`,`/oauth2/introspect`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),awe=/* @__PURE__ */ new Set([`/jwks`,`/.well-known/oauth-protected-resource`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),owe=new Set(cbe),swe=/^\/assets\/[a-zA-Z0-9_.-]+\.(js|css|woff2)$/,K9=(e,t=200)=>vA(e,{status:t}),q9=K9({error:`Not found`},404),J9=[`Authorization`,`Content-Type`,`Accept`,`Mcp-Protocol-Version`,`Mcp-Method`,`Mcp-Name`],cwe=new Set(J9.map(e=>e.toLowerCase())),lwe=(e=lt(new URL(`dist/`,import.meta.resolve(`@clankerauth/web/package.json`))))=>Tf(R(function*(){let t=yield*Z4,{auth:n}=yield*a3,{sql:r}=yield*aH,i=yield*i3,a=[.../* @__PURE__ */ new Set([t.baseURL,...t.mcpAllowedOrigins])],o=R(function*(){let e=yield*pM,r=new URL(e.url,t.baseURL),a=r.pathname.replace(/^\/api\/auth/,``);if(!rwe.has(a)&&a!==`/.well-known/oauth-authorization-server/api/auth`)return q9;if(a===`/oauth2/authorize`){let t=e.method===`GET`?r.searchParams.getAll(`resource`):new URLSearchParams(yield*e.text).getAll(`resource`);if(t.length!==1||!(yield*i.get(t[0]??``)))return K9({error:`invalid_target`,error_description:Q4},400)}let o=e.method===`GET`||e.method===`HEAD`?void 0:yield*e.arrayBuffer,s=yield*U4(()=>n.handler(new Request(r,{method:e.method,headers:e.headers,body:o})));return FA(s)}).pipe(bp(G4)),s=TM(n=>R(function*(){let r=yield*HA;yield*n.add(`*`,`/*`,R(function*(){let n=yield*pM;if(n.method!==`GET`&&n.method!==`HEAD`)return q9;let i=new URL(n.url,t.baseURL).pathname,a=owe.has(i)?`index.html`:swe.test(i)?i.slice(1):void 0;return a?yield*r.fileResponse(st(e,a),{contentType:a.endsWith(`.js`)?`text/javascript`:a.endsWith(`.css`)?`text/css`:a.endsWith(`.woff2`)?`font/woff2`:`text/html; charset=utf-8`}).pipe(bp(()=>F(q9))):q9}))})),c=MM(e=>Rye({baseURL:t.baseURL,trustProxy:t.trustProxy})(R(function*(){let n=yield*pM,r=new URL(n.url,t.baseURL).pathname,i=r.replace(/^\/api\/auth/,``),o=r===`/mcp`,s=n.headers.origin,c=s!==void 0&&a.includes(s),l=iwe.has(i),u;if(o&&s!==void 0&&!c)u=K9({error:`Invalid origin`},403);else if(o&&n.method===`OPTIONS`){let e=n.headers[`access-control-request-method`],t=(n.headers[`access-control-request-headers`]??``).split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);u=c&&e===`POST`&&t.every(e=>cwe.has(e))?fA({status:204}):K9({error:`MCP preflight rejected`},403)}else u=l&&n.method===`OPTIONS`?fA({status:204}):yield*e;l&&(u=u.pipe(wA({"access-control-allow-origin":`*`,"access-control-allow-methods":`GET, POST, OPTIONS`,"access-control-allow-headers":`Authorization, Content-Type, DPoP`,"access-control-expose-headers":`WWW-Authenticate, DPoP-Nonce`}),CA(`access-control-allow-credentials`))),o&&(u=u.pipe(SA(`vary`,u.headers.vary?`${u.headers.vary}, Origin`:`Origin`),CA(`access-control-allow-credentials`)),c&&s!==void 0&&(u=u.pipe(wA({"access-control-allow-origin":s,"access-control-expose-headers":`WWW-Authenticate, Mcp-Protocol-Version`})),n.method===`OPTIONS`&&u.status>=200&&u.status<300&&(u=u.pipe(wA({"access-control-allow-methods":`POST`,"access-control-allow-headers":J9.join(`, `)})))));let d=n.method!==`GET`||u.status!==200?`no-store`:r.startsWith(`/assets/`)?`public, max-age=31536000, immutable`:awe.has(i)?`public, max-age=300`:`no-store`;return u=u.pipe(wA({"cache-control":d,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`,"x-frame-options":`DENY`,"content-security-policy":`default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`})),t.baseURL.startsWith(`https:`)&&(u=u.pipe(SA(`strict-transport-security`,`max-age=31536000`))),u})),{global:!0}),l=MM(e=>rm(e));return Df(twe(a),t.cookieDomain===void 0?yf:nwe(t.cookieDomain),EM(`GET`,`/healthz`,r`SELECT 1`.pipe(vp(K9({status:`ok`})),bp(G4))),EM(`*`,`/api/auth/*`,o),EM(`*`,`/.well-known/*`,o),s).pipe(Af(l.layer),Af(c),Af(Fue))})),uwe=ym(`Http.nodeHandler`)(function*(e){let t=yield*ule(lwe(e));return yield*Nue(t,{scope:yield*Gp})}),dwe=(e,t)=>{let n=Tf(V(Z4,({database:e})=>aH.layer(e)));return Df(j9.layer,f3.layer,s3.layer).pipe(jf(d3.layer),jf(a3.layer),jf(i3.layer),jf(n),jf(Of(e,t)))},Y9=`credentials.json`,X9=W({email:U,password:U,secret:U,clientId:Ux(U),clientSecret:Ux(U)}),fwe=Nx(VS(X9)),pwe=zx(X9),Z9=(e,t)=>B(lE,n=>n.writeFileString(ot(e,Y9),`${JSON.stringify(pwe(t),null,2)}\n`,{mode:384})),mwe=ym(`Dev.identity`)(function*(e,t){let n={email:`owner@example.internal`,password:tt(24).toString(`base64url`),secret:tt(32).toString(`hex`)};if(!t)return n;let r=yield*lE,i=ot(e,Y9);return(yield*r.exists(i))?yield*fwe(yield*r.readFileString(i)):(yield*Z9(e,n),n)}),Q9=e=>Error(`Disposable issuer provisioning failed`,{cause:e}),$9=ym(`Dev.ownerSession`)(function*(e,t,n,r){if(t===void 0)return yield*z(/* @__PURE__ */ Error(`A forward-auth session needs a cookieDomain; the issuer serves none`));let i=yield*fk,a=yield*i.execute(MO(`${e}/api/auth/sign-in/email`,{headers:{origin:e}}).pipe(UO(n)));if(yield*a.text,a.status!==200)return yield*z(/* @__PURE__ */ Error(`Owner sign-in failed with HTTP ${a.status}`));let o=new URL(`/`,r).href,s=yield*i.get(`${e}/forward-auth/continue?rd=${encodeURIComponent(o)}`,{headers:{cookie:og(a.cookies)}});yield*s.text;let c=rg(a.cookies,s.cookies);return{cookie:og(c),cookies:Object.entries(sg(c)).map(([e,t])=>({name:e,value:t}))}}),hwe=Df(jN,FN,_f(PN,{redirect:`manual`})),gwe=H(function*(e){let t=yield*lE,n=lt(new URL(`./web/`,import.meta.url));if(!(yield*t.exists(ot(n,`index.html`))))return yield*z(/* @__PURE__ */ Error(`The @gjermundgaraba/clankerauth-dev installation is missing its bundled dashboard assets`));let r=e.dataDir,i=r===void 0?yield*t.makeTempDirectoryScoped({prefix:`clankerauth-disposable-`}):yield*vp(t.makeDirectory(st(r),{recursive:!0,mode:448}),st(r)),a=yield*Pye(e.port??0,`127.0.0.1`),{port:o}=a,s=e.cookieDomain===void 0?`http://127.0.0.1:${o}`:`http://clankerauth.${e.cookieDomain}:${o}`,c=yield*mwe(i,r!==void 0),l=yield*X4({baseURL:s,secret:hg(c.secret),database:ot(i,`issuer.sqlite`),host:`127.0.0.1`,port:o,mcpAllowedOrigins:[],trustProxy:!1,allowInsecureHttp:e.cookieDomain!==void 0,cookieDomain:e.cookieDomain}),u=yield*yre(dwe(_f(Z4,l),F4.layerWith(e.cimdTransport))),d=va(u,j9),f=yield*ef(yield*Gp),p=yield*uwe(n).pipe(zp(u),Wp(Jd,f));yield*a.serve((t,n)=>{try{e.onRequest?.({method:t.method??`GET`,url:new URL(t.url??`/`,`http://127.0.0.1:${t.socket.localPort}`)}),p(t,n)}catch{n.headersSent?n.destroy():n.writeHead(500).end(`Request failed`)}});let m={email:c.email,password:c.password},h=va(u,f3),g=va(u,d3),_=va(u,s3),v=e=>rm(Kp(R(function*(){let t=yield*d.find();return t===void 0?yield*up(/* @__PURE__ */ Error(`Owner setup failed`)):yield*e(t).pipe(Wp(aV,d.caller(t,m.email,!0)))}))).pipe(Tp(Q9));(yield*d.find())||(yield*d.create(m).pipe(Tp(Q9))),yield*v(()=>ep(e.resources,e=>g.put(e),{discard:!0}));let y=yield*v(()=>R(function*(){if(c.clientId!==void 0&&c.clientSecret!==void 0){let{clients:e}=yield*h.list();if(e.some(e=>e.client_id===c.clientId))return{client_id:c.clientId,client_secret:c.clientSecret}}return yield*h.create({client_name:e.client.name,redirect_uris:[e.client.redirect],resources:e.client.resources,token_endpoint_auth_method:`client_secret_basic`,application_type:`native`})})),b=y.client_secret;if(b===void 0)return yield*z(/* @__PURE__ */ Error(`Disposable issuer did not return client credentials`));r!==void 0&&(yield*Z9(i,{...c,clientId:y.client_id,clientSecret:b}));let x=e.cookieDomain===void 0?void 0:s;return{details:{issuer:`${s}/api/auth`,clientId:y.client_id,clientSecret:b,owner:m,url:s,port:o,directory:i},apiKey:e=>v(()=>V(_.create({name:e.name??`development`,permissions:e.permissions,expiresAt:null}),e=>e.key)),ownerSession:e=>$9(s,x,m,e),ownerToken:ym(`Dev.ownerToken`)(function*(e){let{cookie:t}=yield*$9(s,x,m,e.appOrigin),n=yield*fk,r=new URL(e.appOrigin),i=new URL(`/forward-auth`,s);i.searchParams.set(`resource`,e.resource);let a=yield*n.get(i,{headers:{cookie:t,"x-forwarded-proto":r.protocol.slice(0,-1),"x-forwarded-host":r.host,"x-forwarded-uri":`/`}});yield*a.text;let o=a.headers.authorization;return a.status!==204||o===void 0?yield*z(/* @__PURE__ */ Error(`Forward auth issued no token (HTTP ${a.status})`)):o.replace(/^Bearer /iu,``)})}});async function _we(e){let t=Xd(),n=e=>hm(e.pipe(Wp(Jd,t),zp(hwe)),{onFiberStart:SC(t)}),r=_m($p(nf(t,Ed)));try{let t=await n(gwe(e));return{...t.details,apiKey:e=>n(t.apiKey(e)),ownerSession:e=>n(t.ownerSession(e)),ownerToken:e=>n(t.ownerToken(e)),close:()=>hm(r)}}catch(e){throw await hm(r),e}}export{JV as n,_we as t};