@gjermundgaraba/clankerauth-dev 0.26.2 → 0.26.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_NOTICES.txt +11 -218
- package/dist/{access-CoaNEa0I.mjs → access-CGVwFSPz.mjs} +1 -1
- package/dist/dist-BOFIkVzq.mjs +17 -0
- package/dist/{dist-Dse7wyrJ.mjs → dist-BwJIqVtn.mjs} +1 -1
- package/dist/{factory-tEOeUNZI.mjs → factory-Cf28yuX6.mjs} +3 -3
- package/dist/{get-id-field-CHlYHt3y.mjs → get-id-field-DvYh1rwM.mjs} +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{kysely-adapter-BxenTacV.mjs → kysely-adapter-CAYiOhH_.mjs} +1 -1
- package/dist/{organization-FxrB4RLj.mjs → organization-B_0UJJOj.mjs} +1 -1
- package/dist/{schema-check-6AE7KkNs.mjs → schema-check-DYtufmXq.mjs} +1 -1
- package/dist/{schemas-CYWNDEcx.mjs → schemas-lRZfTY17.mjs} +1 -1
- package/dist/src-BIRfonJg.mjs +539 -0
- package/dist/web/assets/index-Bj2lPl11.css +1 -0
- package/dist/web/assets/index-wQZ9O_DU.js +2300 -0
- package/dist/web/index.html +2 -2
- package/package.json +4 -4
- package/dist/dist-BtO0lgmD.mjs +0 -17
- package/dist/src-mhYy55vF.mjs +0 -539
- package/dist/web/assets/index-kuPpbPut.js +0 -2300
- package/dist/web/assets/index-sZpVl70Z.css +0 -1
|
@@ -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-BOFIkVzq.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,G as _,H as v,I as y,J as b,K as x,L as S,M as ee,N as C,O as te,P as w,R as ne,S as T,T as re,U as ie,V as ae,W as oe,X as se,Y as ce,_ as le,a as ue,b as de,d as fe,f as pe,g as me,h as he,i as ge,k as _e,l as ve,m as ye,o as be,p as xe,q as Se,s as Ce,t as we,u as eee,v as Te,w as Ee,x as De,y as Oe,z as tee}from"./get-id-field-DvYh1rwM.mjs";import{A as ke,C as Ae,D as je,E as Me,F as Ne,I as Pe,L as Fe,M as E,N as D,O as Ie,P as O,S as k,T as nee,_ as Le,a as Re,b as ze,c as Be,d as Ve,f as He,g as Ue,h as We,i as Ge,j as Ke,k as qe,l as Je,m as Ye,n as Xe,o as Ze,p as Qe,r as $e,s as et,t as tt,u as nt,v as A,w as rt,x as it,y as at}from"./schemas-lRZfTY17.mjs";import{a as ot,c as ree,l as iee,o as aee,r as oee,s as see}from"./schema-check-DYtufmXq.mjs";import{n as cee,r as lee}from"./factory-Cf28yuX6.mjs";import{n as uee}from"./access-CGVwFSPz.mjs";import*as st from"node:crypto";import{randomBytes as ct,scrypt as lt}from"node:crypto";import*as ut from"node:path";import dt,{dirname as ft,join as pt,resolve as mt}from"node:path";import*as ht from"node:url";import{fileURLToPath as gt}from"node:url";import _t,*as vt from"node:os";import*as yt from"node:child_process";import{Duplex as bt,PassThrough as xt,Readable as St,pipeline as Ct}from"node:stream";import{IncomingMessage as wt,createServer as dee}from"node:http";import{isIP as Tt}from"node:net";import*as Et from"node:fs";import Dt,{mkdirSync as fee}from"node:fs";import{request as pee}from"node:https";import*as mee from"node:stream/promises";import{pipeline as hee}from"node:stream/promises";import*as Ot from"node:zlib";import*as kt from"node:readline";import{DatabaseSync as gee}from"node:sqlite";import At from"node:fs/promises";import{lookup as _ee}from"node:dns/promises";const jt=(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}}},Mt={pipe(){return jt(this,arguments)}},Nt=/*#__PURE__*/ function(){function e(){}return e.prototype=Mt,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,Pt=e=>()=>e,Ft=/*#__PURE__*/ Pt(!0),It=/*#__PURE__*/ Pt(!1),Lt=/*#__PURE__*/ Pt(void 0),Rt=Lt;function zt(e,...t){return jt(e,t)}function Bt(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 Vt(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 Ht(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 Ut=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},Wt=/*#__PURE__*/ new WeakSet,Gt=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let Kt=0;const qt=()=>{Kt++};function Jt(e){return typeof e==`string`}function Yt(e){return typeof e==`number`}function Xt(e){return typeof e==`boolean`}function Zt(e){return typeof e==`symbol`}function Qt(e){return Jt(e)||Yt(e)||Zt(e)}function $t(e){return typeof e==`function`}function en(e){return e===void 0}function tn(e){return e!==void 0}function nn(e){return e!==null}function rn(e){return e==null}function vee(e){return e!=null}function yee(e){return!1}function an(e){return!0}function on(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sn(e){return on(e)}function cn(e){return typeof e==`object`&&!!e||$t(e)}const N=/*#__PURE__*/ j(2,(e,t)=>cn(e)&&t in e),ln=/*#__PURE__*/ j(2,(e,t)=>N(e,`_tag`)&&e._tag===t);function bee(e){return e instanceof Error}function xee(e){return N(e,Symbol.iterator)||Jt(e)}const un=`~effect/Hash`,dn=e=>{switch(typeof e){case`number`:return _n(e);case`bigint`:return vn(e.toString(10));case`string`:return vn(e);case`function`:case`object`:if(e===null)break;if(e instanceof Date)return Number.isNaN(e.getTime())?vn(`Invalid Date`):vn(e.toISOString());if(e instanceof RegExp)return vn(e.toString());{if(Wt.has(e))return fn(e);let t=Dn.get(e);if(t!==void 0)return t;if(On.has(e))return qt(),vn(`[Circular]`);On.add(e);let n=Kt,r;try{r=`~effect/Hash`in e?e[un]():typeof e==`function`?fn(e):e instanceof DataView?Sn(Gt(e)):Array.isArray(e)||ArrayBuffer.isView(e)?Sn(e):e instanceof Map?Cn(e):e instanceof Set?Tn(e):bn(e)}finally{On.delete(e)}return n===Kt&&Dn.set(e,r),r}}return hn(pn(vn(String(e))))},fn=e=>(En.has(e)||En.set(e,hn(Math.random()*4294967296|0)),En.get(e)),pn=e=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),mn=/*#__PURE__*/ j(2,(e,t)=>pn(Math.imul(e,2654435761)+Math.imul(t,2246822507))),hn=e=>e&3221225471|e>>>1&1073741824,gn=/*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)),_n=e=>{let t=e|0;return t===e?hn(t):(gn.setFloat64(0,e===e?e:NaN),hn(mn(gn.getInt32(0),gn.getInt32(4))))},vn=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return hn(t)},yn=(e,t)=>{let n=12289;for(let r of t)n^=mn(dn(r),dn(e[r]));return hn(n)},bn=e=>yn(e,Ut(e)),xn=(e,t)=>n=>{let r=e;for(let e of n)r^=t(e);return hn(r)},Sn=e=>{let t=6151;for(let n of e)t=mn(t,dn(n));return hn(t)},Cn=/*#__PURE__*/ xn(/*#__PURE__*/ vn(`Map`),([e,t])=>mn(dn(e),dn(t))),wn=/*#__PURE__*/ vn(`Set`),Tn=/*#__PURE__*/ xn(wn,e=>mn(wn,dn(e))),En=/*#__PURE__*/ new WeakMap,Dn=/*#__PURE__*/ new WeakMap,On=/*#__PURE__*/ new WeakSet,kn=`~effect/Equal`;function An(){return arguments.length===1?e=>jn(e,arguments[0]):jn(arguments[0],arguments[1])}function jn(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`||Wt.has(e)||Wt.has(t)?!1:Mn(e,t):!1}function Mn(e,t){let n=Pn.length;for(let r=n;r-->0;)if(Pn[r]===e&&Fn[r]===t)return!0;if(n)return Nn(e,t);let r=In.get(e);r||In.set(e,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return i===void 0&&r.set(t,i=Nn(e,t)),i}function Nn(e,t){Pn.push(e),Fn.push(t);try{return Ln(e,t)}finally{Pn.pop(),Fn.pop()}}const Pn=[],Fn=[],In=/*#__PURE__*/ new WeakMap;function Ln(e,t){if(dn(e)!==dn(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=Vn(e);if(n!==Vn(t)||typeof e==`function`&&!n)return!1;if(n)return e[kn](t);if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:Rn(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?zn(Gt(e),Gt(t)):zn(e,t)}return e instanceof Map?!(t instanceof Map)||e.size!==t.size?!1:Bn(e,t,Cee,wee):e instanceof Set?!(t instanceof Set)||e.size!==t.size?!1:Bn(e,t,dn,jn):See(e,t)}function Rn(e,t){for(let n=0;n<e.length;n++)if(!jn(e[n],t[n]))return!1;return!0}function zn(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 See(e,t){let n=Ut(e),r=Ut(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!jn(e[i],t[i]))return!1;return!0}function Bn(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 Cee=e=>dn(e[0]),wee=(e,t)=>jn(e[0],t[0])&&jn(e[1],t[1]),Vn=e=>N(e,kn),Tee=()=>An,Hn=/*#__PURE__*/ Symbol.for(`~effect/Redactable`),Eee=e=>N(e,Hn);function Un(e){return Eee(e)?Wn(e):e}function Wn(e){return e[Hn](globalThis[`~effect/Fiber/currentFiber`]?.context??Dee)}const Gn=`~effect/Fiber/currentFiber`,Kn=/*#__PURE__*/ new Map,Dee={"~effect/Context":{},base:Kn,depth:0,mapUnsafe:Kn,pipe(){return jt(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 Oee;r.add(e);let l;if(Hn in e)l=c(Wn(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=kee(e);else if(!t?.ignoreToString&&N(e,`toString`)&&typeof e.toString==`function`&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Aee(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=>`${Jn(t)}:${c(Xn(e,t),n)}`).join(`,`)}}`;l=o(e,r)}else{let r=`{\n${t.map(t=>`${a(n+1)}${Jn(t)}: ${c(Xn(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 Oee=`[Circular]`;function Jn(e){return typeof e==`string`?JSON.stringify(e):String(e)}function Yn(e){return e.map(e=>`[${Jn(e)}]`).join(``)}function kee(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Aee(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function Xn(e,t){try{return e[t]}catch{return`[property access threw]`}}function Zn(e,t){let n=[];return JSON.stringify(e,function(e,t){let r=Object.getOwnPropertyDescriptor(this,e)?.value,i=N(r,Hn)?Un(r):Un(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),!jee(a)||Mee(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:Un(n)}});return n.push(o),o},t?.space)??`null`}function jee(e){for(let t of Object.getOwnPropertyNames(e))if(Object.getOwnPropertyDescriptor(e,t)?.get!==void 0)return!0;return!1}function Mee(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 Qn=/*#__PURE__*/ Symbol.for(`nodejs.util.inspect.custom`),$n=e=>{try{return e=Un(e),N(e,`toJSON`)&&$t(e.toJSON)&&e.toJSON.length===0?e.toJSON():Array.isArray(e)?e.map($n):e}catch{return`[toJSON threw]`}},Nee=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Zn(e,{space:t}):qn(e,{space:t})}catch{return String(e)}},er={toJSON(){return $n(this)},[Qn](){return this.toJSON()},toString(){return qn(this.toJSON())}};var tr=class{[Qn](){return this.toJSON()}toString(){return qn(this.toJSON())}};const Pee=/*#__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})(),nr=()=>Error.stackTraceLimit,rr=e=>{Pee&&(Error.stackTraceLimit=e)};var ir=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 ar=/*#__PURE__*/ (()=>{let e=`~effect/Utils/internal`,t={[e]:e=>e()},n={[e]:e=>{try{return e()}finally{}}},r=nr();if(r===0)return n[e];rr(2);let i=t[e](()=>/* @__PURE__ */ Error());return rr(r),i.stack?.includes(e)===!0?t[e]:n[e]})();function or(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function sr(e,t){for(let n of Reflect.ownKeys(t))Object.prototype.propertyIsEnumerable.call(t,n)&&or(e,n,t[n])}const cr=`~effect/Effect`,lr=`~effect/Exit`,ur={_A:M,_E:M,_R:M},dr=`${cr}/identifier`,fr=`${cr}/args`,pr=`${cr}/evaluate`,mr=`${cr}/successCont`,hr=`${cr}/failureCont`,gr=`${cr}/ensureCont`,_r=/*#__PURE__*/ Symbol.for(`effect/Effect/Yield`),vr={pipe(){return jt(this,arguments)},toJSON(){return{...this}},toString(){return qn(this.toJSON(),{ignoreToString:!0,space:2})},[Qn](){return this.toJSON()}},yr={[cr]:ur,...vr,[Symbol.iterator](){return new ir(this)},toJSON(){return{_id:`Effect`,op:this[dr],...`~effect/Effect/args`in this?{args:this[fr]}:void 0}}},br=e=>N(e,cr),xr=e=>N(e,lr),Sr=`~effect/Cause`,Cr=`~effect/Cause/Reason`,wr=e=>N(e,Sr),Tr=e=>N(e,Cr);var Er=class{constructor(e){this[Sr]=Sr,this.reasons=e}pipe(){return jt(this,arguments)}toJSON(){return{_id:`Cause`,failures:this.reasons.map(e=>e.toJSON())}}toString(){return`Cause(${qn(this.reasons)})`}[Qn](){return this.toJSON()}[kn](e){return wr(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>An(t,e.reasons[n]))}[un](){return Sn(this.reasons)}};const Dr=/*#__PURE__*/ new WeakMap;var Or=class{[Cr];annotations;_tag;constructor(e,t,n){if(this[Cr]=Cr,this._tag=e,t!==kr&&typeof n==`object`&&n&&t.size>0){let e=Dr.get(n);e&&(t=new Map([...e,...t])),Dr.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 jt(this,arguments)}toString(){return qn(this)}[Qn](){return this.toString()}};const kr=/*#__PURE__*/ new Map;var Ar=class extends Or{constructor(e,t=kr){super(`Fail`,t,e),this.error=e}toString(){return`Fail(${qn(this.error)})`}toJSON(){return{_tag:`Fail`,error:this.error}}[kn](e){return zr(e)&&An(this.error,e.error)&&An(this.annotations,e.annotations)}[un](){return mn(vn(this._tag))(mn(dn(this.error))(dn(this.annotations)))}};const jr=e=>new Er(e),Mr=(e,t)=>{let n=/* @__PURE__ */ new Map,r=[];for(let i of e.concat(t)){let e=dn(i),t=n.get(e);if(t===void 0)n.set(e,[i]);else if(t.some(e=>An(e,i)))continue;else t.push(i);r.push(i)}return r},Nr=/*#__PURE__*/ j(2,(e,t)=>{if(e.reasons.length===0)return t;if(t.reasons.length===0)return e;let n=new Er(Mr(e.reasons,t.reasons));return An(e,n)?e:n}),Pr=(e,t)=>{let n=e.reasons.slice();for(let e of t.reasons)Vr(e)&&!n.some(t=>Vr(t)&&t.fiberId===e.fiberId&&t.annotations===e.annotations)&&n.push(e);return n.length===e.reasons.length?e:new Er(n)},Fee=/*#__PURE__*/ new Er([]),Fr=e=>new Er([new Ar(e)]);var Ir=class extends Or{constructor(e,t=kr){super(`Die`,t,e),this.defect=e}toString(){return`Die(${qn(this.defect)})`}toJSON(){return{_tag:`Die`,defect:this.defect}}[kn](e){return Br(e)&&An(this.defect,e.defect)&&An(this.annotations,e.annotations)}[un](){return mn(vn(this._tag))(mn(dn(this.defect))(dn(this.annotations)))}};const Lr=e=>new Er([new Ir(e)]),Rr=/*#__PURE__*/ j(e=>wr(e[0]),(e,t,n)=>t.mapUnsafe.size===0?e:new Er(e.reasons.map(e=>e.annotate(t,n)))),zr=e=>e._tag===`Fail`,Br=e=>e._tag===`Die`,Vr=e=>e._tag===`Interrupt`;function Iee(e){return Xr(`Effect.evaluate: Not implemented`)}const Hr=e=>({...yr,[dr]:e.op,[pr]:e[`~effect/Effect/evaluate`]??Iee,[mr]:e[mr],[hr]:e[hr],[gr]:e[gr]}),Ur=e=>{let t=Hr(e),n=function(e){this[fr]=e};return n.prototype=t,function(e){return new n(e)}},Wr=e=>{let t={[lr]:lr,_tag:e.op,get[e.prop](){return this[fr]},...Hr(e),toString(){return`${e.op}(${qn(this[fr])})`},toJSON(){return{_id:`Exit`,_tag:e.op,[e.prop]:this[fr]}},[kn](e){return xr(e)&&e._tag===this._tag&&An(this[`~effect/Effect/args`],e[`~effect/Effect/args`])},[un](){return mn(vn(e.op),dn(this[fr]))}},n=function(e){this[fr]=e};return n.prototype=t,function(e){return new n(e)}},Gr=/*#__PURE__*/ Wr({op:`Success`,prop:`value`,[pr](e){let t=e.getCont(mr);return t?t[mr](this[fr],e,this):e.yieldWith(this)}}),Kr={key:`effect/Cause/StackTrace`},qr={key:`effect/Cause/InterruptorStackTrace`},Jr=/*#__PURE__*/ Wr({op:`Failure`,prop:`cause`,[pr](e){let t=this[fr],n=!1;e.cache.stackFrame&&(t=Rr(t,{mapUnsafe:/* @__PURE__ */ new Map([[Kr.key,e.cache.stackFrame]])}),n=!0);let r=e.getCont(hr),i=e._interruptedCause;if(i&&e.interruptible){let a=!1;for(;r&&e.interruptible;)a||=dr in r,r=e.getCont(hr);a&&(t=jr(t.reasons.filter(e=>e._tag!==`Fail`))),t=Pr(t,i),n=!0}return r?r[hr](t,e,n?void 0:this):e.yieldWith(n?Jr(t):this)}}),Yr=e=>Jr(Fr(e)),Xr=e=>Jr(Lr(e)),Zr=/*#__PURE__*/ Ur({op:`WithFiber`,[pr](e){return this[fr](e)}}),Lee=/*#__PURE__*/ function(){class e extends globalThis.Error{}let t=/*#__PURE__*/ Hr({op:`YieldableError`,[pr](){return Yr(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Qr=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Symbol.for(`effect/Data/Error/plainArgs`);return class extends Lee{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(sr(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}(),$r=e=>{class t extends Qr{_tag=e}return t.prototype.name=e,t},ei=`~effect/Cause/NoSuchElementError`,Ree=e=>N(e,ei);var zee=class extends (/*#__PURE__*/ $r(`NoSuchElementError`)){[ei]=ei;constructor(e){super({message:e})}};const ti=`~effect/Cause/Done`,Bee=e=>N(e,ti),ni={[ti]:ti,_tag:`Done`,value:void 0},ri=e=>e===void 0?ni:{[ti]:ti,_tag:`Done`,value:e},Vee=/*#__PURE__*/ Yr(ni),Hee=e=>e===void 0?Vee:Yr(ri(e)),ii=e=>Hr({op:e.label,[pr]:e.evaluate}),ai=e=>(t,n)=>t===n||e(t,n),Uee=(e,t)=>e===t,oi=()=>Uee;function Wee(e){return ai((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 Gee(e){return ai((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 si=`~effect/Option`,ci={[si]:{_A:e=>e},...vr,[Symbol.iterator](){return new ir(this)}},Kee=/*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(ci),{_tag:`Some`,_op:`Some`,[kn](e){return li(e)&&di(e)&&An(this.value,e.value)},[un](){return mn(dn(this._tag))(dn(this.value))},toString(){return`some(${qn(this.value)})`},toJSON(){return{_id:`Option`,_tag:this._tag,value:$n(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),qee=/*#__PURE__*/ dn(`None`),Jee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(ci),{_tag:`None`,_op:`None`,valueOrUndefined:void 0,[kn](e){return li(e)&&ui(e)},[un](){return qee},toString(){return`none()`},toJSON(){return{_id:`Option`,_tag:this._tag}}}),li=e=>N(e,si),ui=e=>e._tag===`None`,di=e=>e._tag===`Some`,Yee=/*#__PURE__*/ Object.create(Jee),fi=function(e){this.value=e};fi.prototype=Kee;const Xee=e=>new fi(e),pi=`~effect/Result`,mi={[pi]:{
|
|
4
|
+
/* v8 ignore next 2 */
|
|
5
|
+
_A:e=>e,_E:e=>e},...vr,[Symbol.iterator](){return new ir(this)}},Zee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(mi),{_tag:`Success`,_op:`Success`,[kn](e){return hi(e)&&_i(e)&&An(this.success,e.success)},[un](){return mn(dn(this._tag))(dn(this.success))},toString(){return`success(${qn(this.success)})`},toJSON(){return{_id:`Result`,_tag:this._tag,value:$n(this.success)}}}),Qee=/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(mi),{_tag:`Failure`,_op:`Failure`,[kn](e){return hi(e)&&gi(e)&&An(this.failure,e.failure)},[un](){return mn(dn(this._tag))(dn(this.failure))},toString(){return`failure(${qn(this.failure)})`},toJSON(){return{_id:`Result`,_tag:this._tag,failure:$n(this.failure)}}}),hi=e=>N(e,pi),gi=e=>e._tag===`Failure`,_i=e=>e._tag===`Success`,vi=function(e){this.failure=e};vi.prototype=Qee;const yi=e=>new vi(e),bi=function(e){this.success=e};bi.prototype=Zee;const xi=e=>new bi(e);function Si(e){return(t,n)=>t===n?0:e(t,n)}const Ci=/*#__PURE__*/ Si((e,t)=>e<t?-1:1),wi=/*#__PURE__*/ Si((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),Ti=/*#__PURE__*/ j(2,(e,t)=>Si((n,r)=>e(t(n),t(r)))),Ei=e=>j(2,(t,n)=>e(t,n)===-1),Di=e=>j(2,(t,n)=>e(t,n)===1),Oi=e=>j(2,(t,n)=>e(t,n)!==1),ki=e=>j(2,(t,n)=>e(t,n)!==-1),Ai=()=>Yee,ji=Xee,Mi=ui,Ni=di,Pi=/*#__PURE__*/ j(2,(e,{onNone:t,onSome:n})=>Mi(e)?t():n(e.value)),Fi=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?t():e.value),Ii=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?t():e),Li=e=>e==null?Ai():ji(e),Ri=e=>e===void 0?Ai():ji(e),zi=/*#__PURE__*/ Fi(Lt),Bi=e=>(...t)=>{try{return ji(e(...t))}catch{return Ai()}},Vi=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?Ai():ji(t(e.value))),Hi=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?Ai():t(e.value)),Ui=/*#__PURE__*/ j(2,(e,t)=>Mi(e)?Ai():t(e.value)?ji(e.value):Ai()),Wi=`~effect/Context/Service`,P=function(){function e(){}let t=e;Object.setPrototypeOf(t,Gi);let n=(e,n)=>(t.key=e,n?.defaultValue&&(t[qi]=qi,t.defaultValue=n.defaultValue),n?.make&&(t.make=n.make),n?.fiberCached&&Ki.add(e),t);return arguments.length>0?n(arguments[0],arguments[1]):n},Gi={[Wi]:Wi,.../*#__PURE__*/ ii({label:`Service`,evaluate(e){return Gr(da(e.context,this))}}),toJSON(){return{_id:`Service`,key:this.key}},of(e){return e},context(e){return aa(this,e)},use(e){return Zr(t=>e(da(t.context,this)))},useSync(e){return Zr(t=>Gr(e(da(t.context,this))))}},Ki=/*#__PURE__*/ new Set,qi=`~effect/Context/Reference`,Ji=`~effect/Context`,Yi=(e,t,n,r)=>{let i=Object.create($ee);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Xi=(e,t)=>{t&&(Xi(e,t.parent),e.set(t.key,t.value))},Zi=e=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Xi(t,e.overlay),e._flat=t},Qi=(e,t)=>{let n=new Map(e.mapUnsafe);return t(n),ta(n)},$i=/*#__PURE__*/ Symbol(),ea=(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)?$i:(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=8&&(n.base=Zi(n),n.overlay=void 0,n.depth=0),r)},ta=e=>Yi(void 0,e,void 0,0),$ee={get mapUnsafe(){return Zi(this)},...vr,[Ji]:{_Services:e=>e},toJSON(){return{_id:`Context`,services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[kn](e){if(!na(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)||!An(r,n.get(e)))return!1;return!0},[un](){return _n(this.mapUnsafe.size)}},ete=(e,t)=>e.cacheRoot===t.cacheRoot,na=e=>N(e,Ji),tte=e=>N(e,Wi),ra=e=>!!e[qi],ia=()=>nte,nte=/*#__PURE__*/ ta(/*#__PURE__*/ new Map),aa=(e,t)=>ta(/* @__PURE__ */ new Map([[e.key,t]])),oa=/*#__PURE__*/ j(3,(e,t,n)=>rte(e,t.key,n)),rte=(e,t,n)=>{let r=e,i=Ki.has(t)?void 0:r.cacheRoot;if(r.depth>=8){let e=new Map(r._flat??r.base);return r._flat||Xi(e,r.overlay),e.set(t,n),Yi(i,e,void 0,0)}return Yi(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},sa=/*#__PURE__*/ j(3,(e,t,n)=>{let r=ea(e,t.key);return r===$i?ra(t)?pa(t):n():r}),ca=/*#__PURE__*/ j(2,(e,t)=>la(e,t.key)),la=(e,t)=>{let n=ea(e,t);return n===$i?void 0:n},ua=/*#__PURE__*/ j(2,(e,t)=>{let n=ea(e,t.key);if(n===$i){if(ra(t))return pa(t);throw ite(t)}return n}),da=ua,fa=`~effect/Context/defaultValue`,pa=e=>fa in e?e[fa]:e[fa]=e.defaultValue(),ite=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},ma=/*#__PURE__*/ j(2,(e,t)=>{let n=ea(e,t.key);return n===$i?ra(t)?ji(pa(t)):Ai():ji(n)}),ha=/*#__PURE__*/ j(2,(e,t)=>e.mapUnsafe.size===0?t:t.mapUnsafe.size===0?e:Qi(e,e=>t.mapUnsafe.forEach((t,n)=>e.set(n,t)))),ate=(...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 ta(t)},ga=(...e)=>t=>Qi(t,t=>{for(let n=0;n<e.length;n++)t.delete(e[n].key)}),_a=P,va=e=>e.length>0,ya=e=>e>0?Math.floor(e):0,ba=xi,xa=yi,ote=e=>{if($t(e))try{return ba(e())}catch(e){return xa(e)}try{return ba(e.try())}catch(t){return xa(e.catch(t))}},Sa=hi,Ca=gi,wa=_i,ste=/*#__PURE__*/ j(2,(e,t)=>Ca(e)?xa(t(e.failure)):e),Ta=/*#__PURE__*/ j(2,(e,t)=>wa(e)?ba(t(e.success)):e),cte=/*#__PURE__*/ j(2,(e,{onFailure:t,onSuccess:n})=>Ca(e)?t(e.failure):n(e.success)),lte=/*#__PURE__*/ (/* @__PURE__ */ j(2,(e,t)=>Ca(e)?t(e.failure):e.success))(Lt),ute=Wee,dte=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},fte=()=>({}),pte=e=>Object.keys(e).length===0,mte=/*#__PURE__*/ j(2,(e,t)=>Object.hasOwn(e,t)),Ea=/*#__PURE__*/ j(2,(e,t)=>{let n={...e};for(let r of Da(e))or(n,r,t(e[r],r));return n}),hte=/*#__PURE__*/ j(2,(e,t)=>{let n=fte();for(let r of Da(e))t(e[r],r)&&or(n,r,e[r]);return n}),Da=e=>Object.keys(e),gte=/*#__PURE__*/ j(3,(e,t,n)=>({...e,[t]:n})),_te=e=>j(2,(t,n)=>{for(let r of Da(t))if(!mte(n,r)||!e(t[r],n[r]))return!1;return!0}),vte=e=>{let t=_te(e);return(e,n)=>t(e,n)&&t(n,e)},Oa=globalThis.Array,ka=e=>Oa.isArray(e)?e:Oa.from(e),Aa=e=>Oa.isArray(e)?e:[e],ja=/*#__PURE__*/ j(2,(e,t)=>[...e,t]);Oa.isArray;const Ma=va,Na=va;function yte(e){let t=Number(e);return String(t)===e&&Number.isInteger(t)&&t>=0&&t<2**32-1}const bte=(e,t)=>Math.min(ya(e),t),xte=/*#__PURE__*/ j(2,(e,t)=>{let n=ka(e);return n.slice(0,bte(t,n.length))}),Ste=e=>Oa.from(e).reverse(),Cte=(e,t)=>{let n=dn(t),r=e.get(n);if(r===void 0)return e.set(n,[t]),!0;for(let e of r)if(An(e,t))return!1;return r.push(t),!0},Pa=()=>[],Fa=e=>[e],Ia=/*#__PURE__*/ j(2,(e,t)=>e.map(t)),wte=Gee,Tte=e=>{let t=ka(e);if(t.length<2)return[...t];let n=/* @__PURE__ */ new Map,r=[];for(let e of t)Cte(n,e)&&r.push(e);return r},La=`~effect/Duration`,Ra=/*#__PURE__*/ BigInt(0),za=/*#__PURE__*/ BigInt(1),Ete=/*#__PURE__*/ BigInt(2),Dte=/*#__PURE__*/ BigInt(10),Ba=/*#__PURE__*/ BigInt(24),Va=/*#__PURE__*/ BigInt(60),Ha=/*#__PURE__*/ BigInt(1e3),Ua=/*#__PURE__*/ BigInt(1e6),Wa=e=>BigInt(Math.sign(e)*Math.round(Math.abs(e))),Ga=e=>Number.isInteger(e)?BigInt(e)*Ua:Wa(e*1e6),Ka=e=>eo(Number.isFinite(e)?Wa(e):e),qa=(e,t)=>{let n=e.indexOf(`.`);if(n===-1)return BigInt(e)*t;let r=e[0]===`-`,i=e.slice(n+1),a=Dte**BigInt(i.length),o=(BigInt(e.slice(+!!r,n))*a+BigInt(i))*t;return Ote(r?-o:o,a)},Ote=(e,t)=>{let n=e<Ra?-e:e,r=n/t+(n%t*Ete>=t?za:Ra);return e<Ra?-r:r},kte=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Ja=e=>{switch(typeof e){case`number`:return uo(e);case`bigint`:return lo(e);case`string`:{if(e===`Infinity`)return so;if(e===`-Infinity`)return co;let t=kte.exec(e);if(!t)break;let[n,r,i]=t;if(i===`nano`||i===`nanos`)return lo(qa(r,za));if(i===`micro`||i===`micros`)return lo(qa(r,Ha));let a=Number(r);switch(i){case`milli`:case`millis`:return uo(a);case`second`:case`seconds`:return fo(a);case`minute`:case`minutes`:return po(a);case`hour`:case`hours`:return mo(a);case`day`:case`days`:return ho(a);case`week`:case`weeks`:return go(a)}break}case`object`:{if(e===null)break;if(La in e)return e;if(Array.isArray(e))return e.length!==2||!e.every(Yt)?Ya(e):Number.isNaN(e[0])||Number.isNaN(e[1])?oo:e[0]===-1/0||e[1]===-1/0?co:e[0]===1/0||e[1]===1/0?so:Ka(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?eo(n):Ka(n*1e6+(t.microseconds??0)*1e3+(t.nanoseconds??0))}}return Ya(e)},Ya=e=>{throw Error(`Invalid Input: ${e}`)},Xa={_tag:`Millis`,millis:0},Za={_tag:`Infinity`},Qa={_tag:`NegativeInfinity`},$a={[La]:La,[un](){switch(this.value._tag){case`Millis`:return dn(Ga(this.value.millis));case`Nanos`:return dn(this.value.nanos);default:return bn(this.value)}},[kn](e){return to(e)&&Co(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`}}},[Qn](){return this.toJSON()},pipe(){return jt(this,arguments)}},eo=e=>{let t=Object.create($a);return t.value=typeof e==`number`?isNaN(e)||e===0||Object.is(e,-0)?Xa:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:Ga(e)}:e>0?Za:Qa:e===Ra?Xa:{_tag:`Nanos`,nanos:e},t},to=e=>N(e,La),no=e=>e.value._tag!==`Infinity`&&e.value._tag!==`NegativeInfinity`,ro=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===Ra;case`Infinity`:case`NegativeInfinity`:return!1}},io=e=>{switch(e.value._tag){case`Millis`:return e.value.millis<0;case`Nanos`:return e.value.nanos<Ra;case`NegativeInfinity`:return!0;case`Infinity`:return!1}},ao=e=>{switch(e.value._tag){case`Infinity`:case`NegativeInfinity`:return so;case`Millis`:return e.value.millis<0?eo(-e.value.millis):e;case`Nanos`:return e.value.nanos<Ra?eo(-e.value.nanos):e}},oo=/*#__PURE__*/ eo(0),so=/*#__PURE__*/ eo(1/0),co=/*#__PURE__*/ eo(-1/0),lo=e=>eo(e),uo=e=>eo(e),fo=e=>eo(e*1e3),po=e=>eo(e*6e4),mo=e=>eo(e*36e5),ho=e=>eo(e*864e5),go=e=>eo(e*6048e5),_o=e=>bo(Ja(e),{onMillis:M,onNanos:e=>Number(e)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),vo=e=>bo(Ja(e),{onMillis:e=>e/1e3,onNanos:e=>Number(e)/1e9,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),yo=e=>{let t=Ja(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 Ga(t.value.millis)}},bo=/*#__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)()}}),xo=/*#__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(yo(e),t.value.nanos):n.onNanos(e.value.nanos,yo(t))),So=(e,t)=>xo(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t,onInfinity:(e,t)=>e.value._tag===t.value._tag}),Co=/*#__PURE__*/ j(2,(e,t)=>So(e,t)),wo=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=yo(e),n=t<Ra,r=n?-t:t,i=r/Ua,a=i/Ha,o=a/Va,s=o/Va,c=s/Ba,l=n?-1:1;return{days:l*Number(c),hours:l*Number(s%Ba),minutes:l*Number(o%Va),seconds:l*Number(a%Va),millis:l*Number(i%Ha),nanos:l*Number(r%Ua)}},To=e=>{if(e.value._tag===`Infinity`)return`Infinity`;if(e.value._tag===`NegativeInfinity`)return`-Infinity`;if(ro(e))return`0`;if(io(e))return`-`+To(ao(e));let t=wo(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(` `)},Eo=/*#__PURE__*/ _a(`effect/Scheduler`,{fiberCached:!0,defaultValue:()=>new jo}),Do=e=>{let t=!1;return Promise.resolve().then(()=>{t||e()}),()=>{t=!0}},Oo=`setImmediate`in globalThis?e=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:e=>{let t=setTimeout(e,0);return()=>clearTimeout(t)},ko=e=>{try{return Oo(e)}catch{return Do(e)}};var Ao=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}},jo=class{executionMode;setImmediate;constructor(e=`async`,t){this.executionMode=e,this.setImmediate=t??(e===`sync`?Do:ko)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new Mo(this.setImmediate)}},Mo=class{tasks=/*#__PURE__*/ new Ao;running=void 0;setImmediate;constructor(e=ko){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 No=/*#__PURE__*/ _a(`effect/Scheduler/MaxOpsBeforeYield`,{fiberCached:!0,defaultValue:()=>2048}),Po=/*#__PURE__*/ _a(`effect/Scheduler/PreventSchedulerYield`,{fiberCached:!0,defaultValue:()=>!1}),Fo=class extends Nt{constructor(e){super(),e&&sr(this,e)}},Io=e=>class extends Fo{_tag=e},Lo=()=>new Proxy({},{get(e,t,n){return t===`$is`?ln:t===`$match`?Ro:e=>({...e,_tag:t})}});function Ro(){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 zo=Qr,Bo=$r,Vo=`~effect/encoding/EncodingError`;var Ho=class extends (/*#__PURE__*/ Bo(`EncodingError`)){[Vo]=Vo};const Uo=e=>{switch(e){case 16:return qo();case 32:return Jo();default:{let t=``;for(let n=e>>>3;n>0;n--)t+=Ko();return t}}},Wo=/*#__PURE__*/ Uint8Array.from(`0123456789abcdef`,e=>e.charCodeAt(0)),Go=()=>Math.random()*4294967296>>>0,Ko=()=>{let e=Go();return String.fromCharCode(Wo[e>>>28],Wo[e>>>24&15],Wo[e>>>20&15],Wo[e>>>16&15],Wo[e>>>12&15],Wo[e>>>8&15],Wo[e>>>4&15],Wo[e&15])},qo=()=>{let e=Go(),t=Go();return String.fromCharCode(Wo[e>>>28],Wo[e>>>24&15],Wo[e>>>20&15],Wo[e>>>16&15],Wo[e>>>12&15],Wo[e>>>8&15],Wo[e>>>4&15],Wo[e&15],Wo[t>>>28],Wo[t>>>24&15],Wo[t>>>20&15],Wo[t>>>16&15],Wo[t>>>12&15],Wo[t>>>8&15],Wo[t>>>4&15],Wo[t&15])},Jo=()=>{let e=Go(),t=Go(),n=Go(),r=Go();return String.fromCharCode(Wo[e>>>28],Wo[e>>>24&15],Wo[e>>>20&15],Wo[e>>>16&15],Wo[e>>>12&15],Wo[e>>>8&15],Wo[e>>>4&15],Wo[e&15],Wo[t>>>28],Wo[t>>>24&15],Wo[t>>>20&15],Wo[t>>>16&15],Wo[t>>>12&15],Wo[t>>>8&15],Wo[t>>>4&15],Wo[t&15],Wo[n>>>28],Wo[n>>>24&15],Wo[n>>>20&15],Wo[n>>>16&15],Wo[n>>>12&15],Wo[n>>>8&15],Wo[n>>>4&15],Wo[n&15],Wo[r>>>28],Wo[r>>>24&15],Wo[r>>>20&15],Wo[r>>>16&15],Wo[r>>>12&15],Wo[r>>>8&15],Wo[r>>>4&15],Wo[r&15])},Yo=`effect/Tracer/ParentSpan`;var Xo=class extends (/*#__PURE__*/ P()(Yo,{fiberCached:!0})){};const Zo=e=>e,Qo=e=>({_tag:`ExternalSpan`,spanId:e.spanId,traceId:e.traceId,sampled:e.sampled??!0,annotations:e.annotations??ia()}),$o=/*#__PURE__*/ _a(`effect/Tracer/DisablePropagation`,{defaultValue:It}),es=/*#__PURE__*/ _a(`effect/Tracer/CurrentTraceLevel`,{defaultValue:()=>`Info`}),ts=/*#__PURE__*/ _a(`effect/Tracer/MinimumTraceLevel`,{defaultValue:()=>`All`}),ns=`effect/Tracer`,rs=/*#__PURE__*/ _a(ns,{fiberCached:!0,defaultValue:()=>is}),is=/*#__PURE__*/ Zo({span:e=>new as(e)});var as=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??=zi(this.parent)?.traceId??Uo(32)}get spanId(){return this._spanId??=Uo(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 os=/*#__PURE__*/ _a(`effect/ErrorReporter/CurrentErrorReporters`,{defaultValue:()=>/* @__PURE__ */ new Set}),ss=/*#__PURE__*/ _a(`effect/References/CurrentStackFrame`,{fiberCached:!0,defaultValue:Lt}),cs=/*#__PURE__*/ _a(`effect/References/TracerEnabled`,{fiberCached:!0,defaultValue:Ft}),ls=/*#__PURE__*/ _a(`effect/References/TracerTimingEnabled`,{defaultValue:Ft}),us=/*#__PURE__*/ _a(`effect/References/TracerSpanAnnotations`,{defaultValue:()=>({})}),ds=/*#__PURE__*/ _a(`effect/References/TracerSpanLinks`,{defaultValue:()=>[]}),fs=/*#__PURE__*/ _a(`effect/References/CurrentLogAnnotations`,{defaultValue:()=>({})}),ps=/*#__PURE__*/ _a(`effect/References/CurrentLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),Ate=/*#__PURE__*/ _a(`effect/References/MinimumLogLevel`,{fiberCached:!0,defaultValue:()=>`Info`}),jte=/*#__PURE__*/ _a(`effect/References/CurrentLogSpans`,{defaultValue:()=>[]}),ms=e=>{if(e?.captureStackTrace===!1||e?.captureStackTrace!==void 0&&typeof e.captureStackTrace!=`boolean`)return e;let t=nr();if(t===0&&e?.captureStackTrace!==!0)return{...e,captureStackTrace:!1};rr(3);let n=/* @__PURE__ */ Error();return rr(t),{...e,captureStackTrace:Mte(()=>n.stack)}},hs=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}},Mte=/*#__PURE__*/ hs(3);var gs=class extends Or{constructor(e,t=kr){super(`Interrupt`,t,`Interrupted`),this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:`Interrupt`,fiberId:this.fiberId}}[kn](e){return Vr(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[un](){return vn(`${this._tag}:${this.fiberId}`)}};const Nte=e=>new gs(e),_s=e=>new Er([new gs(e)]),Pte=e=>{let t=e.reasons.find(zr);return t?ba(t):xa(e)},vs=e=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag===`Fail`)return ba(n.error)}return xa(e)},ys=e=>e.reasons.some(Br),Fte=e=>{let t=e.reasons.find(Br);return t?ba(t.defect):xa(e)},bs=e=>e.reasons.some(Vr),xs=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?ba(t):xa(e)},Ite=e=>{let t=xs(e);return Ca(t)?Lte:t.success},Lte=/*#__PURE__*/ new Set,Rte=e=>e.reasons.length>0&&e.reasons.every(Vr),zte=e=>ta(e.annotations),Bte=/*#__PURE__*/ j(2,(e,t)=>{let n=!1,r=e.reasons.map(e=>zr(e)?(n=!0,new Ar(t(e.error),e.annotations)):e);return n?jr(r):e}),Ss=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},Vte=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=nr();i!==0&&rr(1);try{for(let i of e.reasons)i._tag===`Interrupt`?r.push(i):n.push(Cs(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=Gte(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(Cs(i,r[0].annotations,t))}}finally{i!==0&&rr(i)}return n},Cs=(e,t,n)=>{let r=typeof e,i;if(e&&r===`object`){if(i=new globalThis.Error(Hte(e),{cause:e.cause?Cs(e.cause):void 0}),typeof e.name==`string`&&(i.name=e.name),typeof e.stack==`string`)i.stack=Wte(e.stack,i,t);else{let e=`${i.name}: ${i.message}`;i.stack=t?ws(e,t):e}n?.includeCauseInStack&&(i.stack=Ds(i));for(let t of Object.keys(e))t in i||(i[t]=e[t])}else{i=new globalThis.Error(e?r===`string`?e:Zn(e):`Unknown error: ${e}`);let n=`${i.name}: ${i.message}`;i.stack=t?ws(n,t):n}return i},Hte=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 Zn(e)},Ute=/\((.*)\)/g,Wte=(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?ws(a.join(`
|
|
10
|
+
`),n):a.join(`
|
|
11
|
+
`)},ws=(e,t)=>{let n=t?.get(Kr.key);return n&&(e=`${e}\n${Ts(n)}`),e},Gte=(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(Ts(r))}return n.join(`
|
|
12
|
+
`)},Ts=e=>{let t=[],n=e,r=0;for(;n&&r<10;){let e=n.stack();if(e){let r=e.matchAll(Ute),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
|
+
`)},Es=e=>Vte(e).map(Ds).join(`
|
|
14
|
+
`),Ds=e=>e.cause?`${e.stack} {\n${Os(e.cause,` `)}\n}`:e.stack,Os=(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${Os(e.cause,`${t} `)}\n${t}}`),r},ks=`~effect/Fiber`,Kte={_A:M,_E:M},qte={id:0},As=/*#__PURE__*/ (()=>{try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncResource}catch{return}})(),js=()=>As===void 0?void 0:new As(`effect/Fiber`),Ms=()=>globalThis[Gn];var Ns=class{constructor(e,t=!0){this.setContext(e),this.id=++qte.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[ks](){return Kte}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return da(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Rt):(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=_s(e);this.cache.stackFrame&&(n=Rr(n,aa(Kr,this.cache.stackFrame))),t&&(n=Rr(n,t)),this._interruptedCause=this._interruptedCause?Pr(this._interruptedCause,n):n,this.interruptible&&(this._running?this._deferredInterrupt=!0:this.evaluate(Vs(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===_r){this._asyncContext=js();return}let n=Ps.interruptChildren&&Ps.interruptChildren(this);if(n!==void 0)return this.evaluate(_c(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=ia()}runLoop(e){let t=globalThis[Gn];globalThis[Gn]=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=Vs(this._interruptedCause)),this.currentOpCount++;let e=this.cache;if(!r&&!e.preventYield&&e.scheduler.shouldYield(this)){r=!0;let e=i;i=_c(Gs,()=>e)}if(i=e.tracerContext?e.tracerContext(i,this):i[pr](this),i===_r){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 _r}}catch(e){if(!N(i,`~effect/Effect/evaluate`))return Xr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);i=Xr(e)}}finally{this._running=n,globalThis[Gn]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,Yte;for(;;){let t=this._stack.pop();if(!t)return;let n=t[gr];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&Xte-1))return Gr(e);let t=this.getCont(mr);return t?t[mr](e,this):this.yieldWith(Gr(e))}yieldWith(e){return this._yielded=e,_r}children(){return this._children??=/* @__PURE__ */ new Set}pipe(){return jt(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&ete(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=Jte(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 Jte=e=>{let t=la(e,ns);return{scheduler:da(e,Eo),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:da(e,cs),span:la(e,Yo),logLevel:da(e,ps),minimumLogLevel:da(e,Ate),stackFrame:da(e,ss),runtimeMetrics:la(e,`effect/Metric/FiberRuntimeMetrics`),maxOpsBeforeYield:da(e,No),preventYield:da(e,Po)}},Yte={[mr](e,t){return Vs(t._interruptedCause)},[hr](e,t){return Vs(t._interruptedCause)}},Xte=32,Ps={interruptChildren:void 0},Fs=e=>{if(!e.cache.stackFrame)return;let t=/* @__PURE__ */ new Map;return t.set(qr.key,e.cache.stackFrame),ta(t)},Zte=e=>{if(e._children!==void 0&&e._children.size!==0)return zs(e._children)},Qte=e=>{let t=e;return t._exit?Bs(t._exit):Zs(n=>t._exit?n(Bs(t._exit)):Us(e.addObserver(e=>n(Bs(e)))))},Is=e=>Zs(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(Bs(r))}return a(),Us(()=>i?.())}),Ls=e=>{let t=e;return t._exit?t._exit:Zs(n=>t._exit?n(t._exit):Us(e.addObserver(n)))},Rs=e=>Zr(t=>$te(e,t.id)),$te=/*#__PURE__*/ j(e=>N(e[0],ks),(e,t,n)=>Zr(r=>{let i=Fs(r);return i=i&&n?ha(i,n):i??n,e.interruptUnsafe(t,i),hc(Qte(e))})),zs=e=>Zr(t=>{let n=Fs(t),r=Pa();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return hc(Is(r))}),Bs=Gr,Vs=Jr,Hs=Yr,Us=/*#__PURE__*/ Ur({op:`Sync`,[pr](e){let t=this[fr](),n=e.getCont(mr);return n?n[mr](t,e):e.yieldWith(Gr(t))}}),Ws=/*#__PURE__*/ Ur({op:`Suspend`,[pr](e){return this[fr]()}}),ene=/*#__PURE__*/ cte({onFailure:Hs,onSuccess:Bs}),Gs=/*#__PURE__*/ (/* @__PURE__ */ Ur({op:`Yield`,[pr](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{t||e.evaluate(Cc)},this[`~effect/Effect/args`]??0),e.yieldWith(()=>{t=!0})}}))(0),Ks=/*#__PURE__*/ Bs(/*#__PURE__*/ Ai()),tne=e=>Ws(()=>Vs(e())),qs=e=>Xr(e),Js=e=>Ws(()=>Hs(e())),Ys=/*#__PURE__*/ Bs(void 0),nne=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new qu(e,`An error occurred in Effect.try`):e.catch;return Ws(()=>{try{return Bs(t())}catch(e){return Hs(n(e))}})},rne=e=>Xs(function(t,n){e(n).then(e=>t(Bs(e)),e=>t(qs(e)))},e.length!==0),ine=e=>{let t=typeof e==`function`?e:e.try,n=typeof e==`function`?e=>new qu(e,`An error occurred in Effect.tryPromise`):e.catch;return Xs(function(e,r){let i=e=>Ws(()=>{try{return Hs(ar(()=>n(e)))}catch(e){return qs(e)}});try{t(r).then(t=>e(Bs(t)),t=>e(i(t)))}catch(t){e(i(t))}},t.length!==0)},ane=e=>Zr(t=>e(t.id)),Xs=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Hr({op:`Async`,[pr](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(one(()=>(t=!0,r?.abort(),i??Cc))),_r):n}}),t=function(e,t){this.register=e,this.withSignal=t};return t.prototype=e,function(e,n){return new t(e,n)}}(),one=/*#__PURE__*/ Ur({op:`AsyncFinalizer`,[gr](e){e.interruptible&&(e.interruptible=!1,e._stack.push(Fl))},[hr](e,t){return bs(e)?_c(tl(Jr(e),this[fr]()),()=>Vs(e)):Vs(e)}}),Zs=e=>Xs(e,e.length>=2),Qs=/*#__PURE__*/ Zs(Rt),sne=(...e)=>{if(e.length===1){let t=e[0];return Ws(()=>ic(t()))}let[t,n]=e;return Ws(()=>ic(n.call(t.self)))},$s=(e,...t)=>{let n=t.length===0?function(){return Ws(()=>ic(e.apply(this,arguments)))}:function(){let n=Ws(()=>ic(e.apply(this,arguments)));for(let e=0;e<t.length;e++)n=t[e](n,...arguments);return n};return ec(e.length,n)},ec=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),tc=/*#__PURE__*/ hs(2),cne=function(){let e=typeof arguments[0]==`string`,t=e?arguments[0]:`Effect.fn`,n=e?arguments[1]:void 0,r=nr(),i;return r!==0&&(rr(2),i=new globalThis.Error,rr(r)),e?(r,...a)=>nc(t,r,i,a,e,n):nc(t,arguments[0],i,Array.prototype.slice.call(arguments,1),e,n)},nc=(e,t,n,r,i,a)=>{let o=typeof t==`function`?t:r.shift().bind(t.self),s=`${e} (definition)`,c=n?tc(()=>n.stack):Lt;return ec(o.length,function(...t){let n=Ws(()=>{let e=o.apply(this,arguments);return br(e)?e:ic(e)});for(let e=0;e<r.length;e++)n=r[e](n,...t);if(!br(n))return n;let l=nr(),u;return l!==0&&(rr(2),u=new globalThis.Error,rr(l)),Ec(i?wu(e,a,e=>Tu(n,e)):n,ss,t=>({name:e,stack:u?tc(()=>u.stack):Lt,parent:{name:s,stack:c,parent:t}}))})},lne=(e,...t)=>ec(e.length,t.length===0?function(){return rc(()=>e.apply(this,arguments))}:function(){let n=rc(()=>e.apply(this,arguments));for(let e of t)n=e(n,...arguments);return n}),rc=e=>{try{let t=e(),n;for(;;){let r=t.next(n);if(r.done)return Bs(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 Ws(()=>n?(n=!1,_c(r.value,e=>ic(t,e))):Ws(()=>ic(e())))}}}}catch(e){return qs(e)}},ic=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Hr({op:`Iterator`,[mr](e,t){let n=this.iterator;for(;;){let r=n.next(e);if(r.done)return Bs(r.value);if(!vc(r.value))return t._stack.push(this),r.value;if(r.value._tag===`Failure`)return r.value;e=r.value.value}},[pr](e){return this[mr](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)}}(),ac=/*#__PURE__*/ j(2,(e,t)=>new sc(e,cc,Bs(t))),oc=function(e){return e._stack.push(this),this[fr]},une=/*#__PURE__*/ Hr({op:`OnSuccess`,[pr]:oc}),sc=function(e,t,n){this[fr]=e,this[mr]=t,this.payload=n};sc.prototype=une;const cc=function(){return this.payload},lc=function(e,t){return t.succeedWith(this.payload)},uc=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ nr();if(e===0)return!1;let t=`~effect/Effect/stackProbe`,n={[t]:function(){return/* @__PURE__ */ Error()}};rr(1);let r=/*#__PURE__*/ n[t]();return rr(e),r.stack?.includes(`[as `+t+`]`)===!0})(),dne=function(e,t){let n=this.payload;return t.succeedWith(uc?n(e):ar(()=>n(e)))},dc=function(e){let t=this.payload;return t(e)},fne=function(e){let t=this.payload;return new sc(t(e),lc,e)},pne=function(e){return new sc(this.payload,lc,e)},fc=e=>yc(e,ji),pc=/*#__PURE__*/ j(2,(e,t)=>new sc(e,br(t)?cc:dc,t)),mc=/*#__PURE__*/ j(2,(e,t)=>new sc(e,br(t)?pne:fne,t)),hc=e=>new sc(e,cc,Cc),mne=(e,t)=>Zr(n=>{let r=/* @__PURE__ */ new Set;return Sl(n,()=>r.size===0?void 0:zs(r)),Zs(i=>{let a=ka(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(Vs(jr(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=$l(n,a[e],!0,!0,!1);if(r.add(t),t.addObserver(n=>{r.delete(t),u(n,t,e)}),c)break}})}),hne=(e,t)=>Zr(n=>{let r=/* @__PURE__ */ new Set;return Sl(n,()=>r.size===0?void 0:zs(r)),Zs(i=>{let a=!1,o=0;for(let s of e){if(a)break;let e=o++,c=$l(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})})}})}),gne=/*#__PURE__*/ j(e=>br(e[1]),(e,t,n)=>mne([e,t],n)),gc=/*#__PURE__*/ j(e=>br(e[1]),(e,t,n)=>hne([e,t],n)),_c=/*#__PURE__*/ j(2,(e,t)=>new sc(e,dc,t)),_ne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?e._tag===`Success`?t.onSuccess(e.value):t.onFailure(e.cause):Rc(e,t)),vc=e=>e[lr]!==void 0,vne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?e._tag===`Success`?t(e.value):e:_c(e,t)),yne=e=>_c(e,M),yc=/*#__PURE__*/ j(2,(e,t)=>new sc(e,dne,t)),bne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?Ene(e,t):yc(e,t)),xne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?Dne(e,t):Ic(e,t)),Sne=/*#__PURE__*/ j(2,(e,t)=>vc(e)?One(e,t):qne(e,t)),Cne=/*#__PURE__*/ j(2,(e,t)=>{if(vc(e)){if(e._tag===`Success`)return e;let n=vs(e.cause);return Ca(n)?e:t(n.success)}return Pc(e,t)}),bc=e=>Jr(_s(e)),xc=e=>e._tag===`Success`,wne=e=>e._tag===`Failure`,Tne=e=>e._tag===`Failure`?ba(e.cause):xa(e),Sc=e=>e._tag===`Failure`&&bs(e.cause),Cc=/*#__PURE__*/ Gr(void 0),Ene=/*#__PURE__*/ j(2,(e,t)=>e._tag===`Success`?Gr(t(e.value)):e),Dne=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return e;let n=vs(e.cause);return Ca(n)?e:Yr(t(n.success))}),One=/*#__PURE__*/ j(2,(e,t)=>{if(e._tag===`Success`)return Gr(t.onSuccess(e.value));let n=vs(e.cause);return Ca(n)?e:Yr(t.onFailure(n.success))}),kne=/*#__PURE__*/ j(2,(e,t)=>xc(e)?t:e),wc=e=>{let t=[];for(let n of e)n._tag===`Failure`&&t.push(...n.cause.reasons);return t.length===0?Cc:Jr(jr(t))},Ane=e=>e,jne=e=>Zr(t=>Bs(ma(t.context,e))),Tc=/*#__PURE__*/ j(2,(e,t)=>Zr(n=>{let r=n.context,i=t(r);return r===i||(n.setContext(i),Sl(n,()=>{n.setContext(r)})),e})),Ec=/*#__PURE__*/ j(3,(e,t,n)=>Tc(e,e=>{let r=ua(e,t),i=n(r);return r===i?e:oa(e,t,i)})),Mne=()=>Nne,Nne=/*#__PURE__*/ Zr(e=>Bs(e.context)),Dc=e=>Zr(t=>e(t.context)),Pne=/*#__PURE__*/ j(2,(e,t)=>Tc(e,Pt(t))),Oc=/*#__PURE__*/ j(2,(e,t)=>vc(e)?e:Tc(e,ha(t))),kc=function(){return arguments.length===1?j(2,(e,t)=>Ac(e,arguments[0],t)):j(3,(e,t,n)=>Ac(e,t,n)).apply(this,arguments)},Ac=(e,t,n)=>Tc(e,oa(t,n)),Fne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>Zl(e,t,n?e=>Hs(n(e)):()=>Hs(new zee))),Ine=/*#__PURE__*/ j(2,(e,t)=>_c(t,t=>t?fc(e):Ks)),Lne=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>Ul({while:Ft,body:Pt(t?.disableYield?e:_c(e,e=>Gs)),step:Rt})),jc=/*#__PURE__*/ j(2,(e,t)=>new Mc(e,t.length===1?t:e=>t(e))),Rne=/*#__PURE__*/ Hr({op:`OnFailure`,[pr]:oc}),Mc=function(e,t){this[fr]=e,this[hr]=t};Mc.prototype=Rne;const zne=/*#__PURE__*/ j(3,(e,t,n)=>jc(e,e=>t(e)?n(e):Vs(e))),Nc=/*#__PURE__*/ j(3,(e,t,n)=>jc(e,e=>{let r=t(e);return Ca(r)?Vs(r.failure):n(r.success,e)})),Pc=/*#__PURE__*/ j(2,(e,t)=>Nc(e,vs,e=>t(e))),Bne=/*#__PURE__*/ j(2,(e,t)=>Nc(e,Fte,t)),Vne=/*#__PURE__*/ j(2,(e,t)=>jc(e,e=>pc(t(e),Vs(e)))),Hne=/*#__PURE__*/ j(3,(e,t,n)=>jc(e,e=>{let r=t(e);return Ca(r)?Vs(e):pc(n(r.success,e),Vs(e))})),Une=/*#__PURE__*/ j(2,(e,t)=>Hne(e,vs,e=>t(e))),Fc=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n,r)=>jc(e,e=>{let i=vs(e);return Ca(i)?Vs(i.failure):t(i.success)?n(i.success):r?r(i.success):Vs(e)})),Wne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n,r)=>jc(e,e=>{let i=vs(e);if(Ca(i))return Vs(i.failure);let a=t(i.success);return Ca(a)?r?r(a.failure):Vs(e):n(a.success)})),Gne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n,r)=>{let i=Array.isArray(t)?e=>N(e,`_tag`)&&t.includes(e._tag):ln(t);return Fc(e,i,n,r)}),Kne=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>{let r;return Wne(e,e=>(r??=Object.keys(t),N(e,`_tag`)&&Jt(e._tag)&&r.includes(e._tag)?ba(e):xa(e)),e=>t[e._tag](e),n)}),Ic=/*#__PURE__*/ j(2,(e,t)=>Pc(e,e=>Js(()=>t(e)))),qne=/*#__PURE__*/ j(2,(e,t)=>Bc(e,{onFailure:e=>Js(()=>t.onFailure(e)),onSuccess:e=>Us(()=>t.onSuccess(e))})),Jne=e=>Pc(e,qs),Yne=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>{if(!t?.log)return Bc(e,{onFailure:e=>Ys,onSuccess:e=>Ys});let n=rd(t.log===!0?void 0:t.log);return Rc(e,{onFailure(e){let r=Pte(e);return Ca(r)?Vs(r.failure):t.message===void 0?n(e):n(t.message,e)},onSuccess:e=>Ys})}),Xne=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>{if(!t?.log)return Rc(e,{onFailure:e=>Ys,onSuccess:e=>Ys});let n=rd(t.log===!0?void 0:t.log);return Rc(e,{onFailure:e=>t.message===void 0?n(e):n(t.message,e),onSuccess:e=>Ys})}),Zne=e=>Vc(e,{onFailure:Ai,onSuccess:ji}),Lc=e=>tre(e,{onFailure:xa,onSuccess:ba}),Rc=/*#__PURE__*/ j(2,(e,t)=>new zc(e,t.onSuccess.length===1?t.onSuccess:e=>t.onSuccess(e),t.onFailure.length===1?t.onFailure:e=>t.onFailure(e))),Qne=/*#__PURE__*/ Hr({op:`OnSuccessAndFailure`,[pr]:oc}),zc=function(e,t,n){this[fr]=e,this[mr]=t,this[hr]=n};zc.prototype=Qne;const $ne=function(e,t){let n=this.payload;return t.succeedWith(uc?n.onSuccess(e):ar(()=>n.onSuccess(e)))},ere=/*#__PURE__*/ ((e,t)=>{let n=Hr({op:e,[pr]:oc,[mr]:$ne,[hr]:t}),r=function(e,t){this[fr]=e,this.payload=t};return r.prototype=n,r})(`Match`,function(e,t){let n=e.reasons.find(zr);if(n===void 0)return Vs(e);let r=this.payload;return t.succeedWith(uc?r.onFailure(n.error):ar(()=>r.onFailure(n.error)))}),Bc=/*#__PURE__*/ j(2,(e,t)=>Rc(e,{onFailure:e=>{let n=e.reasons.find(zr);return n?t.onFailure(n.error):Vs(e)},onSuccess:t.onSuccess})),Vc=/*#__PURE__*/ j(2,(e,t)=>new ere(e,t)),tre=/*#__PURE__*/ j(2,(e,t)=>{if(vc(e)){if(e._tag===`Success`)return Gr(t.onSuccess(e.value));let n=vs(e.cause);return Ca(n)?e:Gr(t.onFailure(n.success))}return Vc(e,t)}),Hc=e=>vc(e)?Gr(e):Uc(e),Uc=/*#__PURE__*/ Ur({op:`Exit`,[pr](e){return e._stack.push(this),this[fr]},[mr](e,t,n){return t.succeedWith(n??Gr(e))},[hr](e,t,n){return t.succeedWith(n??Jr(e))}}),Wc=/*#__PURE__*/ j(2,(e,t)=>pc(Iu(t),e)),Gc=/*#__PURE__*/ j(2,(e,t)=>_c(Jc(e,t.duration),e=>Mi(e)?t.orElse():Bs(e.value))),Kc=e=>new zu(`Operation timed out after '${To(e)}'`),qc=/*#__PURE__*/ j(2,(e,t)=>{let n=Ja(t);return Gc(e,{duration:n,orElse:()=>Hs(Kc(n))})}),Jc=/*#__PURE__*/ j(2,(e,t)=>gc(fc(e),ac(Iu(t),Ai()))),Yc=`~effect/Scope`,Xc=`~effect/Scope/Closeable`,Zc=/*#__PURE__*/ P(`effect/Scope`),Qc=(e,t)=>Zr(n=>(Rl(n),$c(e,t)??Ys)),$c=(e,t)=>{let n=e.state;if(n._tag===`Closed`||(e.state={_tag:`Closed`,exit:t},e.parent!==void 0&&cl(e.parent,e),n._tag===`Empty`))return;if(n.finalizer!==void 0)return el(n.finalizer,t);let r=n.finalizers;return r.size===1?el(r.values().next().value,t):nl(e,r,t)},el=(e,t)=>{try{return e(t)}catch(e){return Xr(e)}},tl=(e,t)=>xc(e)?t:jc(t,t=>Vs(Nr(e.cause,t))),nl=/*#__PURE__*/ $s(function*(e,t,n){let r=[],i=[],a=Array.from(t.values()),o=Ms();for(let t=a.length-1;t>=0;t--){let s=a[t];e.strategy===`sequential`?r.push(yield*Hc(el(s,n))):i.push($l(o,el(s,n),!0,!0,`inherit`))}return i.length>0&&(r=yield*Is(i)),yield*wc(r)}),rl=(e,t)=>Us(()=>il(e,t)),il=(e,t)=>{let n=ul(t,e);return e.state._tag===`Closed`?(n.state=e.state,n):(sl(e,n,e=>Qc(n,e)),n)},al=(e,t)=>Ws(()=>e.state._tag===`Closed`?t(e.state.exit):(sl(e,{},t),Ys)),ol=(e,t)=>al(e,Pt(t)),sl=(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)}},cl=(e,t)=>{if(e.state._tag!==`Open`)return;let n=e.state;n.finalizerKey===t?e.state=dl:n.finalizers!==void 0&&(n.finalizers.delete(t),n.finalizers.size===0&&(e.state=dl))},ll=e=>ul(e,void 0),ul=(e=`sequential`,t)=>({[Xc]:Xc,[Yc]:Yc,strategy:e,parent:t,state:dl}),dl={_tag:`Empty`},fl=e=>Us(()=>ll(e)),pl=Zc,ml=/*#__PURE__*/ kc(Zc),hl=e=>Zr(t=>{let n=t.context,r=ll();return t.setContext(oa(t.context,Zc,r)),Sl(t,e=>(t.setContext(n),$c(r,e))),e}),gl=/*#__PURE__*/ j(2,(e,t)=>Cl(ml(e,t),e=>Ws(()=>$c(t,e)??Ys))),_l=e=>Ws(()=>{let t=ll();return Cl(e(t),e=>Ws(()=>$c(t,e)??Ys))}),vl=(e,t,n)=>Dc(r=>Vl(i=>_c(pl,a=>mc(n?.interruptible?i(e):e,e=>al(a,n=>Oc(t(e,n),r)))))),yl=e=>_c(pl,t=>Dc(n=>al(t,t=>Oc(e(t),n)))),bl=/*#__PURE__*/ function(){let e=/*#__PURE__*/ Hr({op:`OnExit`,[pr](e){return e._stack.push(this),this.effect},[gr](e){e.interruptible&&this.interruptible!==!0&&(e._stack.push(Fl),e.interruptible=!1)},[mr](e,t,n){n??=Gr(e);let r;try{r=this.onExit(n)}catch(e){r=Xr(e)}return r?_c(r,e=>n):n},[hr](e,t,n){n??=Jr(e);let r;try{r=this.onExit(n)}catch(e){r=Xr(e)}return r?_c(tl(n,r),e=>n):n}}),t=function(e,t,n){this.effect=e,this.onExit=t,this.interruptible=n};return t.prototype=e,t}(),xl=(e,t,n)=>new bl(e,t,n),Sl=(e,t)=>{e._stack.push(new bl(void 0,t,void 0))},Cl=/*#__PURE__*/ j(2,xl),wl=/*#__PURE__*/ j(2,(e,t)=>Cl(e,e=>t)),Tl=/*#__PURE__*/ j(3,(e,t,n)=>Cl(e,e=>{let r=t(e);return Ca(r)?Ys:n(r.success,e)})),El=/*#__PURE__*/ j(2,(e,t)=>Tl(e,Tne,t)),Dl=/*#__PURE__*/ j(3,(e,t,n)=>Cl(e,e=>{if(e._tag!==`Failure`)return Ys;let r=t(e.cause);return Ca(r)?Ys:n(r.success,e.cause)})),Ol=/*#__PURE__*/ j(2,(e,t)=>Dl(xs,t)(e)),kl=/*#__PURE__*/ Pt(1/0),Al=(e,t)=>{let n=0,r,i,a=(e,t)=>(t.awaiters++,Sl(e,()=>{if(!(--t.awaiters>0||i!==t))return i=void 0,Rs(t.fiber)}),Ls(t.fiber));return[Zr(o=>{if(i!==void 0)return o===i.fiber?Ls(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 Ns(o.context),awaiters:0};i=c;let l=a(o,c);return c.fiber.evaluate(xl(e,e=>{if(i!==c||(i=void 0,Sc(e)))return;let a=t(e);n=a===1/0?1/0:s.currentTimeMillisUnsafe()+a,r=e})),c.fiber._exit??l}),Us(()=>{r=void 0})]},jl=e=>Us(()=>Al(e,kl)[0]),Ml=/*#__PURE__*/ Zr(e=>Vs(_s(e.id))),Nl=e=>Zr(t=>(t.interruptible&&(t.interruptible=!1,t._stack.push(Fl)),e)),Pl=/*#__PURE__*/ Ur({op:`SetInterruptible`,[gr](e){if(e.interruptible=this[fr],e._interruptedCause&&e.interruptible)return()=>Vs(e._interruptedCause)}}),Fl=/*#__PURE__*/ Pl(!0),Il=/*#__PURE__*/ Pl(!1),Ll=e=>{if(e.interruptible=!0,e._stack.push(Il),e._interruptedCause)return Vs(e._interruptedCause)},Rl=e=>{let t=e;t.interruptible&&(t.interruptible=!1,t._stack.push(Fl))},zl=e=>{let t=e;if(!t.interruptible)return Ll(t)},Bl=e=>Zr(t=>t.interruptible?e:Ll(t)??e),Vl=e=>Zr(t=>t.interruptible?(t.interruptible=!1,t._stack.push(Fl),e(Bl)):e(M)),Hl=(e,t)=>xee(e)?t?.mode===`result`?Wl(e,Lc,t):Wl(e,M,t):t?.discard?t.mode===`result`?Wl(Object.values(e),Lc,t):Wl(Object.values(e),M,t):Ws(()=>{let n={};return ac(Wl(Object.entries(e),([e,r])=>yc(t?.mode===`result`?Lc(r):r,t=>{or(n,e,t)}),{discard:!0,concurrency:t?.concurrency}),n)}),Ul=/*#__PURE__*/ Ur({op:`While`,[mr](e,t){return this[fr].step(e),this[`~effect/Effect/args`].while()?(t._stack.push(this),this[fr].body()):Cc},[pr](e){return this[`~effect/Effect/args`].while()?(e._stack.push(this),this[fr].body()):Cc}}),Wl=/*#__PURE__*/ j(e=>typeof e[1]==`function`,(e,t,n)=>Ws(()=>{let r=Kl(n?.concurrency);if(r===1)return Gl(e,t,n);let i=ka(e),a=i.length;if(a===0)return n?.discard?Ys:Bs([]);let o=n?.discard?void 0:Array(a),s=Xl({f:t,out:o},i,{concurrency:r});return s?ac(s,o):Bs(o)})),Gl=(e,t,n)=>Ws(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),a=i.next(),o=0;return ac(Ul({while:()=>!a.done,body:()=>t(a.value,o++),step:e=>{r&&r.push(e),a=i.next()}}),r)}),Kl=e=>e===`unbounded`?1/0:Math.max(1,e??1),ql=()=>e=>{let t=e.onItem,n=e.step,r=(e,t,r,a,o)=>_c(Hc(o),o=>n(e,t[r],o,r)??i(e,t,r+1,a)??Ys),i=(e,i,a=0,o=i.length)=>{for(;a<o;a++){let s=i[a],c=t(e,s,a);if(!vc(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},Jl=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=Xr(e);return f=t,c=!0,u&&u.size>0?_c(Nl(zs(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(vc(g)){if(f=n(e,o,g,a),f)break}else if(l){p=void 0;let t=$l(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=jr(e);f=Jr(f._tag===`Failure`?Nr(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??Ys)}catch(e){d(m(e))}}),u.size<s)continue;i=!0,a++;return}else return Zs(e=>{l=Ms(),u=/* @__PURE__ */ new Set,p=g,d=e;let t;try{t=h()}catch(t){return e(m(t))}return t?e(t):Ws(()=>(f??=Cc,_c(u?zs(u):Ys,()=>f?._tag===`Failure`?f:Ys)))})}if(c=!0,f){if(u&&u.size>0){let e=Fs(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(Ys);else return Cc}};return h()}},Yl=()=>e=>Jl(e),Xl=/*#__PURE__*/ Jl({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)}}),Zl=/*#__PURE__*/ j(3,(e,t,n)=>_c(e,e=>t(e)?Bs(e):n(e))),Ql=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>Zr(n=>(cd(),Bs($l(n,e,t?.startImmediately,!1,t?.uninterruptible??!1))))),$l=(e,t,n=!1,r=!1,i=!1)=>{let a=e,o=i===`inherit`?a.interruptible:!i,s=new Ns(a.context,o);return r||(a.children().add(s),s._parent=a),n?s.evaluate(t):(s._asyncContext=js(),a.currentDispatcher.scheduleTask(()=>s.evaluate(t),0)),s},eu=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>Zr(r=>{let i=$l(r,e,n?.startImmediately,!0,n?.uninterruptible);if(!i._exit){if(t.state._tag!==`Closed`){let e={};sl(t,e,()=>ane(e=>e===i.id?Ys:Rs(i))),i.addObserver(()=>cl(t,e))}else i.interruptUnsafe(r.id,Fs(r))}return Bs(i)})),tu=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>_c(pl,n=>eu(e,n,t))),nu=e=>(t,n)=>{let r=new Ns(n?.scheduler?oa(e,Eo,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},ru=/*#__PURE__*/ j(2,(e,t)=>e._exit?e:t.state._tag===`Closed`?(e.interruptUnsafe(e.id),e):(cl(t,e),sl(t,e,()=>Rs(e)),e.addObserver(()=>cl(t,e)),e)),iu=/*#__PURE__*/ nu(/*#__PURE__*/ ia()),au=e=>{let t=nu(e);return(e,n)=>{let r=t(e,n);return new Promise(e=>{r.addObserver(t=>e(t))})}},ou=e=>{let t=au(e);return(e,n)=>t(e,n).then(e=>{if(e._tag===`Failure`)throw Ss(e.cause);return e.value})},su=/*#__PURE__*/ ou(/*#__PURE__*/ ia()),cu=e=>{let t=nu(e);return e=>{if(vc(e))return e;let n=new jo(`sync`),r=t(e,{scheduler:n});return r._dispatcher?.flush(),r._exit??Xr(new Gu(r))}},lu=/*#__PURE__*/ cu(/*#__PURE__*/ ia()),uu=/*#__PURE__*/ (e=>{let t=cu(e);return e=>{let n=t(e);if(n._tag===`Failure`)throw Ss(n.cause);return n.value}})(/*#__PURE__*/ ia()),du=/*#__PURE__*/ Bs(!0),fu=/*#__PURE__*/ Bs(!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](Cc)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](Cc)}open=/*#__PURE__*/ Zr(e=>this._isOpen?fu:(this._isOpen=!0,this.scheduleUnsafe(e)));release=/*#__PURE__*/ Zr(e=>this._isOpen?fu:this.scheduleUnsafe(e));openUnsafe(){return!this._isOpen&&(this._isOpen=!0,this.flushWaiters(),!0)}await=/*#__PURE__*/ Zs(e=>this._isOpen?e(Ys):(this.waiters.push(e),Us(()=>{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__*/ Us(()=>this.closeUnsafe());whenOpen=e=>_c(this.await,()=>e);isOpen(){return this._isOpen}};const mu=e=>new pu(e??!1),hu=e=>Us(()=>mu(e)),gu=/*#__PURE__*/ BigInt(0),_u={_tag:`Span`,spanId:`noop`,traceId:`noop`,sampled:!1,status:{_tag:`Ended`,startTime:gu,endTime:gu,exit:Cc},attributes:/*#__PURE__*/ new Map,links:[],kind:`internal`,attribute(){},event(){},end(){},addLinks(){}},vu=e=>Object.assign(Object.create(_u),e),yu=e=>e?da(e.annotations,$o)?e._tag===`Span`?yu(zi(e.parent)):Ai():ji(e):Ai(),bu=(e,t,n)=>{let r=!e.cache.tracerEnabled||n?.annotations&&da(n.annotations,$o),i=n?.parent===void 0?n?.root?Ai():yu(e.cache.span):ji(n.parent),a;if(r)a=vu({name:t,parent:i,annotations:oa(n?.annotations??ia(),$o,!0)});else{let r=e.cache.tracer??is,o=e.getRef(ku),s=e.getRef(ls),c=e.getRef(us),l=e.getRef(ds),u=n?.level??e.getRef(es),d=n?.links===void 0?l.length===0?[]:l.slice():[...l,...n.links];a=r.span({name:t,parent:i,annotations:n?.annotations??ia(),links:d,startTime:s?o.currentTimeNanosUnsafe():gu,kind:n?.kind??`internal`,root:n?.root??!1,sampled:n?.sampled??(Ni(i)&&i.value.sampled===!1?!1:!Xu(e.getRef(ts),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)=>Nl(Zr(n=>{let r=ua(n.context,Zc),i=bu(n,e,t??{}),a=n.getRef(ku),o=n.getRef(ls);return ac(al(r,e=>Cu(i,e,a,o)),i)})),Su=(e,t)=>(t=typeof t==`function`?t:Lt,Ec(ss,n=>({name:e,stack:t,parent:n}))),Cu=(e,t,n,r)=>Us(()=>{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 Zr(t=>{let i=bu(t,e,n),a=t.getRef(ku),o=t.getRef(ls);return Sl(t,e=>Cu(i,e,a,o)),r(i)})},Tu=/*#__PURE__*/ kc(Xo),Eu=function(){let e=br(arguments[0]),t=e?arguments[1]:arguments[0],n=e?arguments[2]:arguments[1],r=M;return t._tag===`Span`&&(n=ms(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=ms(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)=>Zr(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 Ys}),ku=/*#__PURE__*/ _a(`effect/Clock`,{defaultValue:()=>new ju}),Au=2**31-1;var ju=class{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=/*#__PURE__*/ Us(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return Pu()}currentTimeNanos=/*#__PURE__*/ Us(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return Nu()}monotonicTimeNanos=/*#__PURE__*/ Us(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(_o(e))}sleepMillis(e){return e<=0?Gs:Number.isFinite(e)?Zs(t=>{let n=e>Au?this.sleepMillis(e-Au):Ys,r=setTimeout(()=>t(n),Math.min(e,Au));return Us(()=>clearTimeout(r))}):Qs}};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=>Zr(t=>e(t.getRef(ku))),Iu=e=>Fu(t=>t.sleep(Ja(e))),Lu=/*#__PURE__*/ Fu(e=>e.currentTimeMillis),Ru=`~effect/Cause/TimeoutError`;var zu=class extends (/*#__PURE__*/ $r(`TimeoutError`)){[Ru]=Ru;constructor(e){super({message:e})}};const Bu=`~effect/Cause/IllegalArgumentError`;var Vu=class extends (/*#__PURE__*/ $r(`IllegalArgumentError`)){[Bu]=Bu;constructor(e){super({message:e})}};const Hu=`~effect/Cause/ExceededCapacityError`;var Uu=class extends (/*#__PURE__*/ $r(`ExceededCapacityError`)){[Hu]=Hu;constructor(e){super({message:e})}};const Wu=`~effect/Cause/AsyncFiberError`;var Gu=class extends (/*#__PURE__*/ $r(`AsyncFiberError`)){[Wu]=Wu;constructor(e){super({message:`An asynchronous Effect was executed with Effect.runSync`,fiber:e})}};const Ku=`~effect/Cause/UnknownError`;var qu=class extends (/*#__PURE__*/ $r(`UnknownError`)){[Ku]=Ku;constructor(e,t){super({message:t,cause:e})}};const Ju=/*#__PURE__*/ _a(`effect/Console`,{defaultValue:()=>globalThis.console}),Yu=/*#__PURE__*/ Ti(wi,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}}),Xu=/*#__PURE__*/ Di(Yu),Zu=/*#__PURE__*/ _a(`effect/Logger/CurrentLoggers`,{defaultValue:()=>/* @__PURE__ */ new Set([od,sd])}),Qu=/*#__PURE__*/ _a(`effect/Logger/LogToStderr`,{defaultValue:It}),$u={"~effect/Logger":{_Message:M,_Output:M},pipe(){return jt(this,arguments)}},ed=e=>{let t=Object.create($u);return t.log=e,t},td=e=>e.replace(/[\s="]/g,`_`),nd=(e,t)=>`${td(e[0])}=${t-e[1]}ms`,rd=e=>(...t)=>{let n;for(let e=0,r=t.length;e<r;e++){let r=t[e];wr(r)&&(n?t.splice(e,1):t=t.slice(0,e).concat(t.slice(e+1)),n=n?jr(n.reasons.concat(r.reasons)):r,e--)}return n===void 0&&(n=Fee),Zr(r=>{let i=e??r.cache.logLevel;if(Xu(r.cache.minimumLogLevel,i))return Ys;let a=r.getRef(ku),o=r.getRef(Zu);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 Ys})},id={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`};id.gray,id.blue,id.green,id.yellow,id.red,id.bgBrightRed,id.black;const ad=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`)}`,od=/*#__PURE__*/ ed(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let a=Array.isArray(i)?i.slice():[i];e.reasons.length>0&&a.push(Es(e));let o=t.getTime(),s=n.getRef(jte),c=``;for(let e of s)c+=` ${nd(e,o)}`;let l=n.getRef(fs);Object.keys(l).length>0&&a.push(l);let u=n.getRef(Ju);(n.getRef(Qu)?u.error:u.log)(`[${ad(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...a)}),sd=/*#__PURE__*/ ed(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(ku),a=t.getRef(fs),o=t.cache.span;if(o===void 0||o._tag===`ExternalSpan`)return;let s={};for(let[e,t]of Object.entries(a))or(s,e,t);s[`effect.fiberId`]=t.id,s[`effect.logLevel`]=n.toUpperCase(),e.reasons.length>0&&(s[`effect.cause`]=Es(e)),o.event(Nee(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)});function cd(){Ps.interruptChildren??=Zte}const ld=/*#__PURE__*/ j(e=>br(e[0]),(e,t)=>El(e,e=>Zr(n=>(ud(n,e,t?.defectsOnly),Ys)))),ud=(e,t,n)=>{let r=e.getRef(os);if(r.size===0||n&&!ys(t))return;let i={cause:t,fiber:e,timestamp:e.getRef(ku).currentTimeNanosUnsafe()};r.forEach(e=>e.report(i))},nre=wr,rre=Tr,dd=zr,ire=Br,fd=jr,are=Fr,pd=Lr,md=e=>new Ar(e),hd=e=>new Ir(e),ore=Nte,sre=Rte,gd=Bte,cre=Nr,_d=Ss,lre=vs,vd=ys,yd=bs,ure=Ite,dre=Es,fre=Ree,bd=Bee,xd=ri,Sd=Hee,Cd=Vu,pre=Uu,mre=qu,wd=zte;var Td=class extends (/*#__PURE__*/ P()(`effect/Cause/StackTrace`)){};const Ed=xr,Dd=Gr,Od=Jr,kd=Yr,Ad=Xr,jd=bc,Md=Cc,Nd=xc,Pd=wne,hre=Sc,gre=wc,Fd=`~effect/Deferred`,_re=e=>N(e,Fd),vre={[Fd]:{_A:M,_E:M},pipe(){return jt(this,arguments)}},Id=function(){this.resumes=void 0,this.effect=void 0};Id.prototype=vre;const Ld=()=>new Id,Rd=()=>Us(()=>Ld()),zd=e=>Zs(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),Us(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),Bd=/* @__PURE__ */ j(2,(e,t)=>Us(()=>Wd(e,t))),yre=/*#__PURE__*/ j(2,(e,t)=>Bd(e,Jr(t))),bre=/*#__PURE__*/ j(2,(e,t)=>yre(e,_s(t))),Vd=e=>Us(()=>Hd(e)),Hd=e=>e.effect!==void 0,Ud=/*#__PURE__*/ j(2,(e,t)=>Bd(e,Gr(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},xre=fs,Gd=ps,Sre=ls,Kd=Zc,Cre=fl,qd=ll,Jd=ml,Yd=al,Xd=ol,Zd=rl,Qd=il,$d=Qc,ef=$c,wre=gl,tf=`~effect/Layer/MemoMap`,Tre=(e,t)=>{let n={observers:0,deferred:Ld(),scope:qd(),finalizer:r=>Ws(()=>--n.observers>0?Ys:(e.map.delete(t),$d(n.scope,r)))};return n},nf=(e,t)=>t.state._tag!==`Closed`&&(e.observers++,sl(t,{},e.finalizer),!0),Ere={"~effect/Layer":{_ROut:M,_E:M,_RIn:M},pipe(){return jt(this,arguments)}},rf=e=>{let t=Object.create(Ere);return t.build=e,t},af=e=>rf((t,n)=>{let r=Qd(n);return Cl(e(t,r),e=>e._tag===`Failure`?$d(r,e):Ys)}),Dre=e=>{let t=af((n,r)=>n.getOrElseMemoize(t,r,e));return t};var of=class{get[tf](){return tf}parent;constructor(e){this.parent=e}map=/*#__PURE__*/ new Map;get(e,t){let n=this.map.get(e);return n?(nf(n,t),n.deferred.effect??zd(n.deferred)):this.parent?.get(e,t)}getOrElseMemoize(e,t,n){return Ws(()=>{let r;return xl(Ws(()=>{let i=this.get(e,t);if(i)return i;let a=Tre(this,e);return nf(a,t)?(r=a.deferred,this.map.set(e,a),n(this,a.scope)):n(this,t)}),e=>{r&&Wd(r,e)})})}};const sf=()=>new of,Ore=e=>new of(e);var cf=class e extends (/*#__PURE__*/ P()(`effect/Layer/CurrentMemoMap`)){static forkOrCreate(t){let n=ca(t,e);return n?Ore(n):sf()}};const lf=/*#__PURE__*/ j(3,(e,t,n)=>kc(yc(Ws(()=>e.build(t,n)),oa(cf,t)),cf,t)),kre=e=>Zr(t=>lf(e,cf.forkOrCreate(t.context),ua(t.context,Kd))),Are=/*#__PURE__*/ j(2,(e,t)=>Zr(n=>lf(e,cf.forkOrCreate(n.context),t))),uf=function(){return arguments.length===1?e=>df(aa(arguments[0],e)):df(aa(arguments[0],arguments[1]))},df=e=>rf(Pt(Bs(e))),ff=/*#__PURE__*/ df(/*#__PURE__*/ ia()),pf=function(){return arguments.length===1?e=>mf(arguments[0],e):mf(arguments[0],arguments[1])},mf=(e,t)=>hf(yc(t,t=>aa(e,t))),hf=e=>Dre((t,n)=>Jd(e,n)),gf=e=>hf(ac(e,ia())),_f=/*#__PURE__*/ P(`effect/Layer/unwrap`),vf=e=>jre(pf(_f)(e),da(_f)),yf=(e,t,n)=>{let r=Qd(n,`parallel`);return Wl(e,e=>e.build(t,Qd(r,`sequential`)),{concurrency:e.length}).pipe(yc(e=>ate(...e)))},bf=(...e)=>af((t,n)=>yf(e,t,n)),xf=/*#__PURE__*/ j(2,(e,t)=>bf(e,...Array.isArray(t)?t:[t])),Sf=(e,t,n)=>af((r,i)=>_c(Array.isArray(t)?yf(t,r,i):t.build(r,i),t=>e.build(r,i).pipe(Oc(t),yc(e=>n(e,t))))),Cf=/*#__PURE__*/ j(2,(e,t)=>Sf(e,t,M)),wf=/*#__PURE__*/ j(2,(e,t)=>Sf(e,t,(e,t)=>ha(t,e))),jre=/*#__PURE__*/ j(2,(e,t)=>af((n,r)=>_c(e.build(n,r),e=>t(e).build(n,r)))),Mre=e=>rf((t,n)=>e.build(sf(),n)),Tf=ku,Ef=Lu,Df=`~effect/DateTime`,Of=`~effect/DateTime/TimeZone`,kf={[Df]:Df,pipe(){return jt(this,arguments)},[Qn](){return this.toString()},toJSON(){return Ff(this).toJSON()}},Nre={...kf,_tag:`Utc`,[un](){return _n(this.epochMilliseconds)},[kn](e){return jf(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ff(this).toJSON()})`}};({...kf});const Af={[Of]:Of,[Qn](){return this.toString()}};({...Af}),{...Af};const jf=e=>N(e,Df),Pre=e=>e._tag===`Utc`,Mf=e=>{let t=Object.create(Nre);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Nf=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Cd(`Invalid date`);return Mf(t)},Pf=e=>{if(jf(e))return e;if(e instanceof Date)return Nf(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Nf(new Date(e.epochMilliseconds));let t=/* @__PURE__ */ new Date(0);return zre(t,e),Nf(t)}return typeof e==`string`&&!Fre(e)?Nf(/* @__PURE__ */ new Date(e+`Z`)):Nf(new Date(e))},Fre=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Ire=/*#__PURE__*/ Bi(Pf),Lre=e=>Mf(e.epochMilliseconds),Ff=e=>new Date(e.epochMilliseconds),Rre=e=>e.epochMilliseconds,zre=(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)},Bre=e=>Ff(e).toISOString();globalThis.String;const Vre=e=>e.trim(),Hre=(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)},If=/*#__PURE__*/ j(2,(e,t)=>Nc(e,Ure,e=>t(e))),Lf=e=>e.reasons.some(Rf),Rf=e=>e._tag===`Fail`&&bd(e.error),zf=e=>{let t,n=!1;for(let r of e.reasons)Rf(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?xa(e):n?xa(fd(e.reasons.filter(e=>!Rf(e)))):ba(t)},Ure=e=>{let t=zf(e);return Ca(t)?t:ba(t.success.value)},Bf=e=>{let t=zf(e);return Ca(t)?Od(t.failure):Dd(t.success.value)},Wre=/*#__PURE__*/ j(2,(e,t)=>Rc(e,{onSuccess:t.onSuccess,onFailure:e=>{let n=zf(e);return Ca(n)?t.onFailure(n.failure):t.onDone(n.success.value)}})),Gre=(e,t,n)=>_l(r=>_c(n?.local?lf(t,sf(),r):Are(t,r),t=>Oc(e,t))),Kre=/*#__PURE__*/ j(e=>br(e[0]),(e,t,n)=>na(t)?Oc(e,t):Gre(e,Array.isArray(t)?bf(...t):t,n)),Vf=`~effect/MutableHashMap`,qre={[Vf]:Vf,[Symbol.iterator](){return this.backing[Symbol.iterator]()},toString(){return`MutableHashMap(${qn(Array.from(this))})`},toJSON(){return{_id:`MutableHashMap`,values:$n(Array.from(this))}},[Qn](){return this.toJSON()},pipe(){return jt(this,arguments)}},Jre=()=>{let e=Object.create(qre);return e.backing=/* @__PURE__ */ new Map,e.buckets=/* @__PURE__ */ new Map,e},Hf=/*#__PURE__*/ j(2,(e,t)=>{if(e.backing.has(t))return ji(e.backing.get(t));if(Uf(t))return Ai();let n=dn(t),r=e.buckets.get(n);return r===void 0?Ai():Yre(e,r,t)}),Uf=e=>typeof e!=`object`&&typeof e!=`function`,Yre=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(An(n,t[r])){let n=t[r];return ji(e.backing.get(n))}return Ai()},Xre=/*#__PURE__*/ j(3,(e,t,n)=>{if(e.backing.has(t)||Uf(t))return e.backing.set(t,n),e;let r=dn(t),i=e.buckets.get(r);if(i===void 0)return e.buckets.set(r,[t]),e.backing.set(t,n),e;let a=Zre(i,t);return a===void 0&&(i.push(t),a=t),e.backing.set(a,n),e}),Zre=(e,t)=>{for(let n=0,r=e.length;n<r;n++)if(An(t,e[n]))return e[n]},Wf=/*#__PURE__*/ j(2,(e,t)=>{if(Uf(t))return e.backing.delete(t),e;let n=dn(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||An(t,i)){e.backing.delete(i),r.splice(n,1);break}}return r.length===0&&e.buckets.delete(n),e}),Qre=e=>(e.backing.clear(),e.buckets.clear(),e),$re=e=>e.backing.size,Gf=br,Kf=Hl,qf=Wl,Jf=Ul,Yf=rne,Xf=ine,F=Bs,Zf=Ks,Qf=Ws,I=Us,L=Ys,$f=Zs,ep=Qs,R=sne,z=Hs,tp=Vs,np=tne,rp=qs,ip=nne,eie=Gs,ap=Zr,op=ene,B=_c,tie=yne,sp=pc,cp=mc,lp=Lc,nie=Zne,up=Hc,V=yc,dp=ac,fp=hc,pp=Pc,mp=Gne,rie=Kne,hp=jc,gp=Bne,_p=Fc,iie=zne,vp=Ic,yp=Jne,bp=Une,xp=Vne,Sp=Yne,Cp=Xne,aie=ld,oie=qc,wp=Gc,sie=Wc,Tp=Iu,cie=gne,Ep=gc,lie=Fne,uie=Ine,Dp=Vc,die=_ne,Op=Rc,kp=Bc,Ap=Mne,jp=Dc,Mp=Kre,Np=Oc,fie=Pne,Pp=Ane,Fp=jne,Ip=Tc,Lp=kc,Rp=pl,zp=hl,pie=_l,Bp=vl,Vp=yl,Hp=wl,Up=El,Wp=xl,Gp=Cl,Kp=jl,qp=Ml,Jp=Bl,Yp=Ol,Xp=Nl,Zp=Vl,Qp=Lne,mie=Ou,hie=xu,$p=wu,em=Du,tm=Eu,nm=Ql,rm=eu,im=tu,am=iu,om=nu,sm=su,cm=ou,lm=uu,um=lu,H=$s,dm=cne,fm=Fu,pm=/*#__PURE__*/ rd(`Fatal`),mm=/*#__PURE__*/ rd(`Warn`),hm=/*#__PURE__*/ rd(`Error`),gm=/*#__PURE__*/ rd(`Info`),_m=/*#__PURE__*/ rd(`Debug`),vm=/*#__PURE__*/ j(e=>Gf(e[0]),(e,...t)=>Ec(e,xre,e=>{let n=t.length===1?{...e,...t[0]}:{...e};return t.length===1||or(n,t[0],t[1]),n})),ym=(e,t,n)=>(...r)=>$f(i=>{try{e(...r,(e,n)=>{i(e?t?Qf(()=>z(t(e,r))):z(e):F(n))})}catch(e){i(n?z(n(e,r)):rp(e))}}),bm=bne,xm=xne,Sm=Sne,Cm=vne,wm=Cne,Tm=lne,Em=`~effect/BigDecimal`,Dm={[Em]:Em,[un](){let e=Fm(this);return mn(vn(String(e.value)),_n(e.scale))},[kn](e){return Om(e)&&zm(this,e)===0},toString(){return`BigDecimal(${Vm(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Qn](){return this.toJSON()},pipe(){return jt(this,arguments)}},Om=e=>N(e,Em),km=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(Dm);return n.value=e,n.scale=t,n},Am=(e,t)=>{let n=km(e,t);return n.normalized=n,n},jm=/*#__PURE__*/ BigInt(0),Mm=/*#__PURE__*/ BigInt(1),Nm=/*#__PURE__*/ BigInt(10),Pm=/*#__PURE__*/ Am(jm,0),Fm=e=>{if(e.normalized===void 0){if(e.value===jm)e.normalized=Pm;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=Am(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Im=[Mm],Lm=(e,t)=>e===t?0:e<t?-1:1,Rm=(e,t)=>{let n=`${e.value<jm?-e.value:e.value}`,r=`${t.value<jm?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==jm)return i<jm?-1:1;let a=Math.max(n.length,r.length);return Ci(n.padEnd(a,`0`),r.padEnd(a,`0`))},zm=(e,t)=>{if(e.scale===t.scale)return Lm(e.value,t.value);let n=Bm(e),r=Bm(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?Rm(t,e):Rm(e,t);let o=Im[a]??=Nm**BigInt(a);return i>0?Lm(e.value,t.value*o):Lm(e.value*o,t.value)},Bm=e=>e.value===jm?0:e.value<jm?-1:1,Vm=e=>{let t=Fm(e);if(Math.abs(t.scale)>=16)return Hm(t);let n=t.value<jm,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},Hm=e=>{if(Um(e))return`0e+0`;let t=Fm(e),n=`${t.value}`,r=t.value<jm?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Um=e=>e.value===jm,Wm=globalThis.BigInt,Gm=e=>e>Wm(2**53-1)||e<Wm(-(2**53-1))?Ai():ji(Number(e)),Km=/*#__PURE__*/ BigInt(0),qm=/*#__PURE__*/ BigInt(1),Jm=/*#__PURE__*/ BigInt(1e3),Ym=/*#__PURE__*/ BigInt(1024),Xm=[{symbol:`B`,factor:qm,names:[`B`,`byte`,`bytes`]},{symbol:`kB`,factor:Jm,names:[`kB`,`kilobyte`,`kilobytes`]},{symbol:`MB`,factor:Jm**/*#__PURE__*/ BigInt(2),names:[`MB`,`megabyte`,`megabytes`]},{symbol:`GB`,factor:Jm**/*#__PURE__*/ BigInt(3),names:[`GB`,`gigabyte`,`gigabytes`]},{symbol:`TB`,factor:Jm**/*#__PURE__*/ BigInt(4),names:[`TB`,`terabyte`,`terabytes`]},{symbol:`PB`,factor:Jm**/*#__PURE__*/ BigInt(5),names:[`PB`,`petabyte`,`petabytes`]},{symbol:`EB`,factor:Jm**/*#__PURE__*/ BigInt(6),names:[`EB`,`exabyte`,`exabytes`]},{symbol:`ZB`,factor:Jm**/*#__PURE__*/ BigInt(7),names:[`ZB`,`zettabyte`,`zettabytes`]},{symbol:`YB`,factor:Jm**/*#__PURE__*/ BigInt(8),names:[`YB`,`yottabyte`,`yottabytes`]},{symbol:`RB`,factor:Jm**/*#__PURE__*/ BigInt(9),names:[`RB`,`ronnabyte`,`ronnabytes`]},{symbol:`QB`,factor:Jm**/*#__PURE__*/ BigInt(10),names:[`QB`,`quettabyte`,`quettabytes`]}],Zm=[Xm[0],{symbol:`KiB`,factor:Ym,names:[`KiB`,`kibibyte`,`kibibytes`]},{symbol:`MiB`,factor:Ym**/*#__PURE__*/ BigInt(2),names:[`MiB`,`mebibyte`,`mebibytes`]},{symbol:`GiB`,factor:Ym**/*#__PURE__*/ BigInt(3),names:[`GiB`,`gibibyte`,`gibibytes`]},{symbol:`TiB`,factor:Ym**/*#__PURE__*/ BigInt(4),names:[`TiB`,`tebibyte`,`tebibytes`]},{symbol:`PiB`,factor:Ym**/*#__PURE__*/ BigInt(5),names:[`PiB`,`pebibyte`,`pebibytes`]},{symbol:`EiB`,factor:Ym**/*#__PURE__*/ BigInt(6),names:[`EiB`,`exbibyte`,`exbibytes`]},{symbol:`ZiB`,factor:Ym**/*#__PURE__*/ BigInt(7),names:[`ZiB`,`zebibyte`,`zebibytes`]},{symbol:`YiB`,factor:Ym**/*#__PURE__*/ BigInt(8),names:[`YiB`,`yobibyte`,`yobibytes`]}],Qm=[...Xm,.../*#__PURE__*/ Zm.slice(1)],$m=/*#__PURE__*/ new Map(/*#__PURE__*/ Qm.flatMap(e=>e.names.map(t=>[t,e]))),eh=/*#__PURE__*/ new Map(/*#__PURE__*/ Qm.map(e=>[e.symbol,e])),th=e=>e,nh=/*#__PURE__*/ th(Km),rh=e=>{throw Error(`Invalid ByteSize: ${e}`)},ih=e=>!Number.isSafeInteger(e)||e<0?rh(`expected a non-negative safe integer, received ${e}`):th(BigInt(e)),ah=(e,t)=>{if(typeof e==`bigint`)return e<Km?rh(`expected a non-negative quantity, received ${e}`):th(e*t.factor);let n=e*Number(t.factor);return!Number.isSafeInteger(n)||n<0?rh(`expected an exact non-negative safe-integer byte result, received ${e} ${t.symbol}`):th(BigInt(n))},oh=e=>{let t=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(e);if(t===null)return rh(`unsupported syntax ${JSON.stringify(e)}`);let n=$m.get(t[3]);if(n===void 0)return rh(`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===Km?th(a/i):rh(`${JSON.stringify(e)} does not represent an integral number of bytes`)},sh=e=>{switch(typeof e){case`bigint`:return e<Km?rh(`expected a non-negative bigint, received ${e}`):th(e);case`number`:return ih(e);case`string`:return oh(e)}return rh(`unsupported input ${e}`)},ch=/*#__PURE__*/ Bi(sh),lh=e=>typeof e==`bigint`?sh(e):ih(e),uh=/*#__PURE__*/ (e=>t=>ah(t,eh.get(e)))(`MiB`),dh=jf,fh=Pre,ph=Nf,mh=Pf,hh=Ire,gh=Lre,_h=Rre,vh=Bre,yh=e=>Sh(typeof e==`string`?Ch.encode(e):e),bh=e=>{let t=Th(e),n=t.length;if(n%4!=0)return xa(new Ho({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 xa(new Ho({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=Oh(t.charCodeAt(e))<<18|Oh(t.charCodeAt(e+1))<<12|Oh(t.charCodeAt(e+2))<<6|Oh(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return ba(r)}catch(e){return xa(new Ho({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},xh=e=>Ta(bh(e),e=>wh.decode(e)),Sh=e=>{let t=e.length,n=``,r=2;for(;r<t;r+=3)n+=Eh[e[r-2]>>2],n+=Eh[(e[r-2]&3)<<4|e[r-1]>>4],n+=Eh[(e[r-1]&15)<<2|e[r]>>6],n+=Eh[e[r]&63];return r===t+1&&(n+=Eh[e[r-2]>>2],n+=Eh[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Eh[e[r-2]>>2],n+=Eh[(e[r-2]&3)<<4|e[r-1]>>4],n+=Eh[(e[r-1]&15)<<2],n+=`=`),n},Ch=/*#__PURE__*/ new TextEncoder,wh=/*#__PURE__*/ new TextDecoder,Th=e=>e.replace(/[\n\r]/g,``),Eh=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Dh=/*#__PURE__*/ (/* @__PURE__ */ new Uint8Array(123)).fill(255);for(let e=0;e<64;e++)Dh[/*#__PURE__*/ Eh.charCodeAt(e)]=e;Dh[61]=0;const Oh=e=>{if(e>=Dh.length||Dh[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Dh[e]},kh=`~effect/http/Cookies`,Ah=e=>N(e,kh),jh=`~effect/http/Cookies/Cookie`,Mh=`~effect/http/Cookies/CookieError`;var Nh=class extends zo{},Ph=class e extends (/*#__PURE__*/ Bo(`CookiesError`)){static fromReason(t,n){return new e({reason:new Nh({_tag:t,cause:n})})}[Mh]=Mh;get message(){return this.reason._tag}};const Fh={[kh]:kh,...er,toJSON(){return{_id:`effect/Cookies`,cookies:Ea(this.cookies,e=>e.toJSON())}},pipe(){return jt(this,arguments)}},Ih=e=>{let t=Object.create(Fh);return t.cookies=e,t},Lh=e=>{let t={};for(let n of e)or(t,n.name,n);return Ih(t)},Rh=e=>{let t=typeof e==`string`?[e]:e,n=[];for(let e of t){let t=zh(e.trim());t&&n.push(t)}return Lh(n)};function zh(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(!Uh.test(r))return;let i=t[0].slice(n+1),a=ng(i);if(t.length===1)return Object.assign(Object.create(Kh),{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=fo(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(Kh),{name:r,value:a,valueEncoded:i,options:Object.keys(o).length>0?o:void 0})}const Bh=/*#__PURE__*/ Lh([]),Vh=e=>pte(e.cookies),Hh=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Uh=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Wh=/^[\u0009\u0020-\u003a\u003c-\u007e\u0080-\u00ff]+$/,Gh=/^[\u0020-\u003a\u003c-\u007e]+$/,Kh={[jh]:jh,...er,toJSON(){return{_id:`effect/Cookies/Cookie`,name:this.name,value:this.value,options:this.options}}};function qh(e,t,n){let r=encodeURIComponent(t),i=Jh(e,r,n);return i===void 0?ba(Object.assign(Object.create(Kh),{name:e,value:t,valueEncoded:r,options:n})):xa(i)}function Jh(e,t,n){if(!Uh.test(e))return Ph.fromReason(`InvalidCookieName`);if(t&&!Hh.test(t))return Ph.fromReason(`InvalidCookieValue`);if(n?.domain!==void 0&&!Wh.test(n.domain))return Ph.fromReason(`InvalidCookieDomain`);if(n?.path!==void 0&&!Gh.test(n.path))return Ph.fromReason(`InvalidCookiePath`);if(n?.maxAge!==void 0&&!no(Ja(n.maxAge)))return Ph.fromReason(`CookieInfinityMaxAge`)}const Yh=/*#__PURE__*/ j(2,(e,t)=>Ih({...e.cookies,...t.cookies})),Xh=/*#__PURE__*/ j(e=>Ah(e[0]),(e,t,n,r)=>Ta(qh(t,n,r),n=>Ih(gte(e.cookies,t,n))));function Zh(e){let t=Jh(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=vo(Ja(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 Qh=e=>Object.values(e.cookies).map(e=>`${e.name}=${e.valueEncoded}`).join(`; `),$h=e=>{let t={},n=Object.values(e.cookies);for(let e=0;e<n.length;e++){let r=n[e];or(t,r.name,r.value)}return t},eg=e=>Object.values(e.cookies).map(Zh);function tg(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();or(t,o,n.indexOf(`%`)===-1?n:ng(n))}r=i+1}return t}const ng=e=>{try{return decodeURIComponent(e)}catch{return e}},rg=/*#__PURE__*/ new WeakMap,ig=e=>{if(rg.has(e))return rg.get(e);throw Error(`Unable to get redacted value`+(e.label?` with label: "${e.label}"`:``))},ag=`~effect/Redacted`,og=e=>N(e,ag),sg=(e,t)=>{let n=Object.create(cg);return t?.label&&(n.label=t.label),rg.set(n,e),n},cg={[ag]:{_A:e=>e},label:void 0,...vr,toJSON(){return this.toString()},toString(){return`<redacted${Jt(this.label)?`:`+this.label:``}>`},[un](){return dn(rg.get(this))},[kn](e){return og(e)&&An(rg.get(this),rg.get(e))}},lg=ig,ug=e=>ai((t,n)=>e(lg(t),lg(n))),dg=/*#__PURE__*/ Symbol.for(`~effect/http/Headers`),fg=/*#__PURE__*/ Object.defineProperties(/*#__PURE__*/ Object.create(null),{[dg]:{value:dg},[Hn]:{value(e){return Cg(this,da(e,Tg))}},toJSON:{value(){return Un(this)}},[kn]:{value(e){return mg(this,e)}},[un]:{value(){return bn(this)}},toString:{value:er.toString},[Qn]:{value:er[Qn]}}),pg=e=>Object.assign(Object.create(fg),e),mg=/*#__PURE__*/ vte(/*#__PURE__*/ oi()),hg=/*#__PURE__*/ Object.create(fg),gg=e=>{if(e===void 0)return hg;if(Symbol.iterator in e){let t=Object.create(fg);for(let[n,r]of e)t[n.toLowerCase()]=r;return t}let t=Object.create(fg);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},_g=e=>Object.setPrototypeOf(e,fg),vg=/*#__PURE__*/ j(3,(e,t,n)=>{let r=pg(e);return r[t.toLowerCase()]=n,r}),yg=/*#__PURE__*/ j(2,(e,t)=>pg({...e,...gg(t)})),bg=/*#__PURE__*/ j(2,(e,t)=>{let n=pg(e);return Object.assign(n,t),n}),xg=/*#__PURE__*/ j(2,(e,t)=>{let n=pg(e);return delete n[t.toLowerCase()],n}),Sg=/*#__PURE__*/ j(2,(e,t)=>{let n=pg(e);for(let e of t)delete n[e.toLowerCase()];return n}),Cg=/*#__PURE__*/ j(2,(e,t)=>{let n={...e},r=t=>{if(typeof t==`string`){let r=t.toLowerCase();r in e&&(n[r]=sg(e[r]))}else for(let r in e)r.search(t)!==-1&&(n[r]=sg(e[r]))};if(Array.isArray(t))for(let e=0;e<t.length;e++)r(t[e]);else r(t);return n}),wg=(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},Tg=/*#__PURE__*/ _a(`effect/Headers/CurrentRedactedNames`,{defaultValue:()=>[`authorization`,`cookie`,`set-cookie`,`x-api-key`]}),Eg=e=>typeof e==`string`?e:lg(e),Dg=`~effect/http/UrlParams`,Og=e=>N(e,Dg),kg={...vr,[Dg]:Dg,[Symbol.iterator](){return this.params[Symbol.iterator]()},[Hn](e){return{_id:`UrlParams`,params:Object.fromEntries(Bg(this,da(e,Xg)))}},toJSON(){return Un(this)},[kn](e){return Pg(this,e)},[un](){return Sn(this.params.flat())}},Ag=e=>{let t=Object.create(kg);return t.params=e,t},jg=e=>{if(Og(e))return e;let t=Mg(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 Ag(n)},Mg=e=>{let t=typeof e[Symbol.iterator]==`function`?ka(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,Ng(r[t])]);else if(typeof r==`object`&&r&&!og(r)){let t=Mg(r);for(let[r,i]of t)n.push([[e,...typeof r==`string`?[r]:r],i])}else r!==void 0&&n.push([e,Ng(r)]);return n},Ng=e=>og(e)?e:String(e),Pg=/*#__PURE__*/ ai((e,t)=>Fg(e.params,t.params)),Fg=/*#__PURE__*/ wte(/*#__PURE__*/ ute([/*#__PURE__*/ oi(),/*#__PURE__*/ Tee()])),Ig=/*#__PURE__*/ Ag([]),Lg=/*#__PURE__*/ j(2,(e,t)=>{let n=jg(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 Ag(n)}),Rg=e=>new URLSearchParams(jg(e).params.map(([e,t])=>[e,Eg(t)])).toString(),zg=e=>{let t={};for(let[n,r]of e.params){let e=Eg(r);if(!Object.hasOwn(t,n))or(t,n,e);else{let r=t[n];typeof r==`string`?or(t,n,[r,e]):r.push(e)}}return t},Bg=/*#__PURE__*/ j(2,(e,t)=>{let n=Array.isArray(t)?t:[t];return e.params.map(([e,t])=>[e,typeof t==`string`&&Vg(e,n)?sg(t):t])}),Vg=wg,Hg=(e,t=Yg())=>{e.includes(`@`)&&(e=Kg(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)+qg(e.slice(n+1,i),t)+e.slice(i)},Ug=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i,Wg=/[/\\?#]/,Gg=/[/?#]/,Kg=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=Ug.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?Wg:Gg),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])},qg=(e,t)=>e.split(`&`).map(e=>{let n=e.indexOf(`=`);return n!==-1&&Vg(Jg(e.slice(0,n)),t)?e.slice(0,n+1)+`REDACTED`:e}).join(`&`),Jg=e=>{if(!e.includes(`%`)&&!e.includes(`+`))return e;try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return e}},Yg=()=>da(globalThis[`~effect/Fiber/currentFiber`]?.context??ia(),Xg),Xg=/*#__PURE__*/ _a(`effect/http/UrlParams/CurrentRedactedNames`,{defaultValue:()=>[`AWSAccessKeyId`,`Signature`,`sig`,`X-Goog-Signature`]});function Zg(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Qg(e){return t=>Zg(t)?.[e]}const $g=`~structural`,e_=`~identifier`,t_=`~sentinels`,n_=`~constructor`,r_=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],i_=/*#__PURE__*/ Qg(`identifier`),a_=/*#__PURE__*/ Qg(e_),o_=/*#__PURE__*/ Qg(`description`),s_=/*#__PURE__*/ Vt(e=>{let t=Zg(e)?.identifier;return typeof t==`string`?t:e.getExpected(s_)}),c_=/*#__PURE__*/ new Set([t_,$g,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),l_=/*#__PURE__*/ Symbol(),u_=Dd,d_=/*#__PURE__*/ u_(l_),f_=/*#__PURE__*/ u_(l_),p_=e=>e===l_?Ai():ji(e),m_=e=>e._tag===`None`?d_:u_(e.value),h_=`~effect/SchemaIssue/Issue`;function g_(e){return N(e,h_)&&e[h_]===h_}function __(e){return Object.hasOwn(e,`input`)}var v_=class{[h_]=h_;constructor(e,t){t?.reportInput===!0&&e!==l_&&(this.input=e)}};const y_=class extends v_{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},b_=class extends v_{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},x_=class extends v_{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},S_=class extends v_{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},C_=class extends v_{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},w_=class extends v_{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},T_=class extends v_{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},E_=class extends v_{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}};function D_(e,t,n,r,i){return new w_(e,[new x_([t],n)],r,i)}const O_=class extends v_{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},k_=class extends v_{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},A_=class extends v_{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function j_(e,t,n){if(g_(e))return e;if(typeof e==`string`)return new E_({message:e},t,n);let r=typeof e.issue==`string`?new E_({message:e.issue},t,n):e.issue;return new x_(e.path,r)}function M_(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new E_(void 0,t,n):j_(e,t,n)}function N_(e,t,n,r){return Array.isArray(t)?Na(t)?t.length===1?j_(t[0],n,r):new w_(e,Ia(t,e=>j_(e,n,r)),n,r):void 0:M_(t,n,r)}const P_=e=>{let t=G_(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return z_(s_(e.ast),e);case`InvalidValue`:{let t=R_(e);if(t!==void 0)return z_(t,e);let n=L_(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=L_(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=L_(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},F_=e=>G_(e.issue)??G_(e);function I_(e){return t=>({issues:B_(t,[],e?.leafHook??P_,e?.checkHook??F_)})}function L_(e){return __(e)?qn(e.input):void 0}function R_(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function z_(e,t){let n=L_(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function B_(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 B_(e.issue,t,n,r);let a=R_(e.issue);return[{path:t,message:a===void 0?z_(V_(e.filter),e):z_(a,e.issue)}]}case`Encoding`:return B_(e.issue,t,n,r);case`Pointer`:return B_(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>B_(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:G_(e)??z_(s_(e.ast),e)}]:e.issues.flatMap(e=>B_(e,t,n,r));default:return[{path:t,message:n(e)}]}}function V_(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=>V_(e)).join(` & `)}}function H_(){return e=>W_(e,``)}const U_=/*#__PURE__*/ H_();function W_(e,t){let n;switch(e._tag){case`Filter`:{let r=F_(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return W_(e.issue,t);let r=R_(e.issue);n=r===void 0?z_(V_(e.filter),e):z_(r,e.issue)}break}case`Encoding`:return W_(e.issue,t);case`Pointer`:return W_(e.issue,t+Yn(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>W_(e,t)).join(`
|
|
16
|
+
`);n=G_(e)??z_(s_(e.ast),e);break;default:n=P_(e)}return t?`${n}\n at ${t}`:n}function G_(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return G_(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 K_(e){let t;for(let n of e.reasons){if(!dd(n)||!g_(n.error))return;t??=n.error}return t}function q_(e,t){let n=K_(e);if(n===void 0)throw Error(t,{cause:e});return n}const J_=(e,t,n)=>{switch(e._tag){case`Passthrough`:return F(t);case`Transform`:return F(Vi(t,e.transform));case`TransformOptional`:return F(e.transform(t));case`TransformEffect`:return Mi(t)?Zf:bm(e.transform(t.value,n),ji);case`TransformOptionalEffect`:return e.transform(t,n)}},Y_=e=>Object.assign(Object.create(Mt),e),X_=(e,t)=>ov((n,r)=>Cm(J_(e,n,r),e=>J_(t,e,r))),Z_=/*#__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 rv(n=>t.transform(e.transform(n)));case`TransformOptional`:return av(n=>t.transform(Vi(n,e.transform)));case`TransformEffect`:return iv((n,r)=>t.transform(e.transform(n),r));case`TransformOptionalEffect`:return X_(e,t)}case`TransformOptional`:switch(t._tag){case`Transform`:return av(n=>Vi(e.transform(n),t.transform));case`TransformOptional`:return av(n=>t.transform(e.transform(n)));case`TransformEffect`:case`TransformOptionalEffect`:return X_(e,t)}case`TransformEffect`:switch(t._tag){case`Transform`:return iv((n,r)=>bm(e.transform(n,r),t.transform));case`TransformOptional`:case`TransformOptionalEffect`:return X_(e,t);case`TransformEffect`:return iv((n,r)=>Cm(e.transform(n,r),e=>t.transform(e,r)))}case`TransformOptionalEffect`:return X_(e,t)}});function Q_(e){return ov((t,n)=>z(e(t,n)))}function $_(e){return Q_((t,n)=>{let r={message:e(t)};return Ni(t)?new O_(r,t.value,n):new O_(r)})}const ev=/*#__PURE__*/ $_(()=>`Encoding is not supported`),tv=/*#__PURE__*/ Y_({_tag:`Passthrough`});function nv(){return tv}function rv(e){return Y_({_tag:`Transform`,transform:e})}function iv(e){return Y_({_tag:`TransformEffect`,transform:e})}function av(e){return Y_({_tag:`TransformOptional`,transform:e})}function ov(e){return Y_({_tag:`TransformOptionalEffect`,transform:e})}function gie(e){return ov(t=>{let n=Ui(t,tn);return Ni(n)?F(n):bm(e,ji)})}function sv(){return rv(globalThis.String)}function cv(){return rv(globalThis.Number)}function _ie(){return rv(Vre)}function vie(e){return iv((t,n)=>ip({try:()=>JSON.parse(t,e?.reviver),catch:()=>new E_({expected:`a valid JSON string`},t,n)}))}function yie(e){return iv((t,n)=>ip({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 E_({expected:`a JSON-serializable value`},t,n)}))}function bie(e){let t=e?.separator??`,`;return rv(e=>e===``?[]:e.split(t))}function xie(){return rv(yh)}function Sie(){return iv((e,t)=>xm(op(bh(e)),()=>new E_({expected:`a valid Base64 string`},e,t)))}const Cie=class extends Nt{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Cie(this.encode,this.decode)}},lv=`~effect/SchemaTransformation/Transformation`,uv=class extends Nt{[lv]=lv;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new uv(this.encode,this.decode)}};function wie(e){return N(e,lv)&&e[lv]===lv}const dv=e=>wie(e)?e:new uv(e.decode,e.encode);function fv(e){return new uv(iv(e.decode),iv(e.encode))}function pv(e){return new uv(rv(e.decode),rv(e.encode))}function Tie(){return new uv(_ie(),nv())}const Eie=/*#__PURE__*/ new uv(/*#__PURE__*/ nv(),/*#__PURE__*/ nv());function mv(){return Eie}const hv=/*#__PURE__*/ new uv(/*#__PURE__*/ cv(),/*#__PURE__*/ sv()),Die=e=>on(e)&&typeof e.message==`string`,Oie=e=>{let t=Object.hasOwn(e,`cause`)?Error(e.message,{cause:gv(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},kie=e=>{try{let t=Zn(e);return t===void 0?qn(e):JSON.parse(t)}catch{return qn(e)}},Aie=(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},jie=e=>{let t=/* @__PURE__ */ new WeakSet,n=r=>{if(bee(r)){if(t.has(r))return`[Circular]`;t.add(r);let i=Aie(r,e,n);return t.delete(r),i}return kie(r)};return n},gv=e=>Die(e)?Oie(e):e,Mie=e=>pv({decode:gv,encode:jie(e)}),_v=/*#__PURE__*/ new uv(/*#__PURE__*/ Sie(),/*#__PURE__*/ xie());function Nie(e){return new uv(vie(e??{}),yie(e))}function vv(e){return t=>t._tag===e}const yv=/*#__PURE__*/ vv(`Declaration`),Pie=/*#__PURE__*/ vv(`Null`),Fie=/*#__PURE__*/ vv(`Undefined`),bv=/*#__PURE__*/ vv(`Void`),Iie=/*#__PURE__*/ vv(`Never`),xv=/*#__PURE__*/ vv(`Literal`),Sv=/*#__PURE__*/ vv(`UniqueSymbol`),Lie=/*#__PURE__*/ vv(`Enum`),Cv=/*#__PURE__*/ vv(`Arrays`),wv=/*#__PURE__*/ vv(`Objects`),Tv=/*#__PURE__*/ vv(`Union`),Ev=/*#__PURE__*/ vv(`Suspend`),Dv=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Ov={},kv=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}},Av=`~effect/Schema`;var jv=class{[Av]=Av;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 Mv=class extends jv{_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===l_?d_:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=Vy(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Mv(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>`}},Nv=/*#__PURE__*/ new class extends jv{_tag=`Null`;getParser(){return Zy(this,null)}getExpected(){return`null`}},Rie=class extends jv{_tag=`Undefined`;getParser(){return Zy(this,void 0)}toCodecJson(){return Ay(this,[Pv])}getExpected(){return`undefined`}},Pv=/*#__PURE__*/ new Dv(Nv,/*#__PURE__*/ new uv(/*#__PURE__*/ rv(()=>void 0),/*#__PURE__*/ rv(()=>null))),Fv=/*#__PURE__*/ new Rie,zie=/*#__PURE__*/ new class extends jv{_tag=`Void`;getParser(){let e=u_(void 0);return t=>t===l_?d_:e}toCodecJson(){return Ay(this,[Pv])}getExpected(){return`void`}},Bie=/*#__PURE__*/ new class extends jv{_tag=`Never`;getParser(){return Qy(this,yee)}getExpected(){return`never`}},Vie=/*#__PURE__*/ new class extends jv{_tag=`Any`;getParser(){return Qy(this,an)}getExpected(){return`any`}},Iv=/*#__PURE__*/ new class extends jv{_tag=`Unknown`;getParser(){return Qy(this,an)}getExpected(){return`unknown`}};function Lv(e){return typeof e==`number`?`parts[${e}]`:e}function Rv(e,t,n){if(n.has(e))return!0;if(e.encoding)throw Error(`TemplateLiteral parts cannot have an encoding at ${Lv(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=Lv(t);r=!e.checks&&e.parts.every((e,t)=>Rv(e,`${i}.parts[${t}]`,n));break}case`Union`:{let i=Lv(t);r=!e.checks&&e.types.every((e,t)=>Rv(e,`${i}.types[${t}]`,n));break}default:return!1}return r&&n.add(e),r}const Hie=class extends jv{_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(!Rv(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 Wv(!1,this.parts.map(nb),[]),n=e(Wy(Vv,t,Uie(this)));return(e,t)=>{if(e===l_)return d_;let r=n(e,t);return r._tag===`Success`?f_:Sm(r,{onSuccess:()=>e,onFailure:n=>new w_(this,[n],e,t)})}}getExpected(){return`string`}matchPart(e,t){return $y(this,e,t)===void 0?void 0:e}};function Uie(e){return new uv(iv((t,n)=>{let r=$y(e,t,n);return r?F(r):z(new E_({expected:`a string matching template literal parts`},t,n))}),rv(e=>e.join(``)))}const zv=class extends jv{_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 Zy(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Bv(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Bv(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Bv(e){let t=globalThis.String(e.literal);return Ay(e,[new Dv(new zv(t),new uv(rv(()=>e.literal),rv(()=>t)))])}const Vv=/*#__PURE__*/ new class extends jv{_tag=`String`;getParser(){return Qy(this,Jt)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&ab(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Wie=class extends jv{_tag=`Number`;getParser(){return Qy(this,Yt)}matchKey(e,t){return this._match(mae,e,t)}matchPart(e,t){return this._match(rb,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:ab(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Hv(this.checks,`effect/schema/isFinite`)||Hv(this.checks,`effect/schema/isInt`))?this:Ay(this,[nae])}toCodecStringTree(){return this.toCodecJson()===this?Ay(this,[gae]):Ay(this,[_ae])}getExpected(){return`number`}};function Hv(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Hv(e.checks,t))}const Uv=/*#__PURE__*/ new Wie,Gie=/*#__PURE__*/ new class extends jv{_tag=`Boolean`;getParser(){return Qy(this,Xt)}getExpected(){return`boolean`}},Wv=class extends jv{_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(Gy(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(Gy(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 C_(n,t[o],i),a=new x_([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return z(new w_(n,[a],t,i))}return e.issues?z(new w_(n,e.issues,t,i)):u_(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:Kl(t.concurrency),f=d===1?qie(i,e,0,u):Jie(i,e,{concurrency:d,end:u});if(!f)return c(i);if(vc(f))return Cm(f,()=>c(i));let p=!0;return Qf(()=>p?(p=!1,B(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===l_)return d_;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 T_(n,e,a))}catch(e){return rp(e)}}}_rebuild(e,t,n){let r=Vy(this.elements,e),i=Vy(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Wv(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 Kie(e,t,n,r){if(n._tag===`Failure`)return Kv(e,e.ast,r,n);let i=n===f_?t:n[fr];if(i!==l_)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Gy(t.ast))return;let n=new x_([r],new S_(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return kd(new w_(e.ast,[n],e.input,e.options))}}const Gv={onItem(e,t,n){let r=n<e.len?t:l_;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Kie},qie=/*#__PURE__*/ ql()(Gv),Jie=/*#__PURE__*/ Yl()(Gv),Kv=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=K_(r.cause);if(i===void 0)return Od(gd(r.cause,r=>new w_(t,[new x_([n],r)],e.input,e.options)));let a=new x_([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return kd(new w_(t,[a],e.input,e.options))},qv=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function Jv(e,t,n=Ov){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(eb(Jy(t)))}const Yv=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Xv(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(Xv);default:return!1}}function Zv(e){let t=My(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(Zv);default:return!1}}function Yie(e){return Xv(e)&&Zv(e)}const Qv=class{parameter;type;constructor(e,t){if(!Yie(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Gy(t)&&!Xy(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},$v=class extends jv{_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 Qy(n,vee);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(eb(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 Kv(t,n,i,s)??Md;let c=s===f_?o:s[fr];if(a!==l_&&c!==l_){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Md;or(t.out,a,c)}return Md},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!vc(t))return B(up(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Kv(e,n,r,a)??Md;let o=a===f_?r:a[fr],s=e.input[r],l=i.parserValue(s,e.options);return vc(l)?t(e,r,o,s,l):B(up(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return vc(a)?t(e,n,n,i,a):B(up(a),r=>t(e,n,n,i,r))},u=i?Yl()({onItem:(e,[t,n])=>n.is.parameter===Vv?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return Tm(function*(t,d){if(t===l_)return l_;if(typeof t!=`object`||!t||Array.isArray(t))return yield*z(new T_(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:Kl(d.concurrency),v=i&&g?n.indexSignatures.map(e=>Jv(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 C_(n,f[a],d),r=new x_([a],e);if(h){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*z(new w_(n,[r],t,d))}}}if(r){let e=_===1?ny(m,a):Xie(m,a,{concurrency:_});e&&(yield*e)}if(i&&_===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Vv?l:c,r=v?.[e]??(t.is.parameter===Vv?Object.keys(f):Jv(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!vc(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=Pa();for(let t=0;t<i;t++){let n=o[t],r=v?.[t]??(n.is.parameter===Vv?Object.keys(f):Jv(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 w_(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return B(up(n),n=>{let i=ey(e,r,n);if(i)return i;let o=()=>u_(e.out),s=ny(e,a.slice(t+1));return s?Cm(s,o):o()})};return(e,t)=>{if(e===l_)return d_;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Kl(t.concurrency)!==1)return(l??=c())(e,t);if(typeof e!=`object`||!e||Array.isArray(e))return z(new T_(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=my(i,s),l=c?i[s]:l_,d=n.parser(l,t);if(!vc(d))return u(o,e,d);if(d===f_){c&&or(a,s,l);continue}let f=ey(o,n,d);if(f)return f}}catch(e){return rp(e)}return u_(a)}}_rebuild(e,t,n,r){let i=Vy(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new Yv(t.name,n)}),a=Vy(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new Qv(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new $v(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 ey(e,t,n){if(n._tag===`Failure`)return Kv(e,e.ast,t.name,n);if(n===f_)return;let r=n[fr];if(r!==l_)or(e.out,t.name,r);else if(delete e.out[t.name],!Gy(t.type)){let n=new x_([t.name],new S_(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return kd(new w_(e.ast,[n],e.input,e.options))}}const ty={onItem(e,t){if(!my(e.input,t.name))return t.parser(l_,e.options);let n=e.input[t.name];return or(e.out,t.name,n),t.parser(n,e.options)},step:ey},ny=/*#__PURE__*/ ql()(ty),Xie=/*#__PURE__*/ Yl()(ty);function ry(e,t){return e?t?[...e,...t]:e:t}function iy(e,t,n){return new $v(Reflect.ownKeys(e).map(t=>new Yv(t,e[t].ast)),[],n,t)}function ay(e){return e.ast}function oy(e,t=void 0){return new Wv(!1,e.map(e=>e.ast),[],void 0,t)}function sy(e,t,n){return new hy(e.map(ay),t,void 0,n)}function Zie(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=ry(i,e.checks)}return new $v(n,r,void 0,i)}const cy=/*#__PURE__*/ Ht(e=>{for(;;){if(Ev(e))return Iv;let t=e.encoding;if(!t)return e.recur?.(cy,M)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==M))return Iv;e=t[t.length-1].to}});function ly(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(ly)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function uy(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[t_];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Gy(t)){if(xv(t))return[{key:e.name,literal:t.literal}];if(Sv(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Gy(e)){if(xv(e))return[{key:t,literal:e.literal}];if(Sv(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>uy(cy(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return uy(e.thunk())}}const dy=/*#__PURE__*/ new WeakMap,fy=/*#__PURE__*/ Object.freeze([]),py=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,my=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Qie(e){let t=dy.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=cy(c);if(Iie(l))continue;if(xv(l)||Sv(l)){a??=/* @__PURE__ */ new Map;let e=xv(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=uy(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=ly(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??fy);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??fy;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(cn(e)){let n=my(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??fy;if(t)return o}return fy}}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=py(t);if(!cn(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=my(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=my(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=my(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(py(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return dy.set(e,t),t}const hy=class extends jv{_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===l_)return d_;let i=(o??=Qie(n.types))(e,r);if(i.length===0)return z(new k_(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:vc(r)?gy(n,r.cause,e,t):$ie(n,r,e,t)}return _y(n,a,i,e,t)}}_rebuild(e,t,n){let r=Vy(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new hy(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=Jy(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(xv);if(t.length>0)return`${by(n.isMutable)}[ ${t.map(t=>e(t)+xy(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>xv(e.type));if(t.length>0)return`{ ${t.map(t=>`${by(t.type.context?.isMutable)}${Jn(t.name)}${xy(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function gy(e,t,n,r){let i=K_(t);return i?kd(new k_(e,[i],n,r)):Od(t)}function $ie(e,t,n,r){return hp(t,t=>gy(e,t,n,r))}function _y(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=eae(a,n);if(!o)return a.out?a.out:z(new k_(e,a.issues??[],r,i));if(vc(o))return vy(o,a);let s=!0;return Qf(()=>s?(s=!1,vy(o,a)):_y(e,t,n,r,i))}function vy(e,t){return Cm(e,e=>t.out===f_?F(t.input):t.out?t.out:z(new k_(t.ast,t.issues??[],t.input,t.options)))}const eae=/*#__PURE__*/ ql()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=K_(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]),kd(new A_(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Md}}}),yy=/*#__PURE__*/ new hy([/*#__PURE__*/ new zv(`Infinity`),/*#__PURE__*/ new zv(`-Infinity`),/*#__PURE__*/ new zv(`NaN`)]);function by(e){return e?``:`readonly `}function xy(e){return e?`?`:``}const Sy=class extends Nt{_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 Sy(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Sy(this.run,this.annotations,!0)}and(e,t){return new Cy([this,e],t)}},Cy=class extends Nt{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Cy(this.checks,{...this.annotations,...e})}and(e,t){return new Cy([this,e],t)}};function wy(e,t,n=!1){return new Sy((t,n,r)=>N_(n,e(t,n,r),t,r),t,n)}function tae(e){return wy(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 Ty=/*#__PURE__*/ Fy(Uv,[/*#__PURE__*/ tae()]),nae=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([Ty,yy]),/*#__PURE__*/ new uv(/*#__PURE__*/ cv(),/*#__PURE__*/ rv(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Ey(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return wy(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 Dy=/*#__PURE__*/ new WeakMap;function Oy(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Dy.set(n,ky(e)),n}function ky(e){let t=Dy.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 Dy.set(e,n),n}function Ay(e,t){return e.encoding===t?e:Oy(e,{encoding:t})}function jy(e,t){if(e.context===t)return e;let n=ky(e);return n.context===t&&n.encoding===e.encoding?n:Oy(e,{context:t})}function My(e){return e.encoding?My(e.encoding[e.encoding.length-1].to):e}function Ny(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Py(e,ja(e.checks.slice(0,-1),n.annotate(t)))}return Oy(e,{annotations:{...e.annotations,...t}})}function Py(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Oy(e,{checks:t})}function Fy(e,t){return Py(e,ry(e.checks,t))}function Iy(e,t){let n=t(e.to);return n===e.to?e:new Dv(n,e.transformation)}function Ly(e,t){let n=e,r=n[n.length-1],i=Iy(r,t);return i===r?e:ja(e.slice(0,e.length-1),i)}function Ry(e){return t=>t.encoding?Ay(t,Ly(t.encoding,e)):t}function zy(e,t){return Ry(e=>jy(e,t))(e)}function rae(e){function t(n){return n.encoding?Ay(n,Ly(n.encoding,t)):e(n)}return Vt(t)}function By(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:Ay(r,Ly(r.encoding,n))}return e(r)}return Ht(n)}function iae(e,t,n){let r=new Dv(e,t);return Ay(n,n.encoding?[...n.encoding,r]:[r])}function Vy(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 Hy(e,t){return jy(e,e.context?new kv(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new kv(!1,!1,void 0,t))}const Uy=/*#__PURE__*/ Ht(e=>{let t=e.context?e.context.isOptional===!1?new kv(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new kv(!0,!1);return aae(jy(e,t))}),aae=/*#__PURE__*/ Ry(Uy),oae=/*#__PURE__*/ Vt(e=>Uy(new hy([e,Fv])));function sae(e,t){return jy(e,e.context?new kv(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new kv(!1,!1,t))}function Wy(e,t,n){return iae(e,n,t)}function cae(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 lae(e,t){let{literals:n,parameters:r}=cae(e);return new $v(n.map(e=>new Yv(e,t)),r.map(e=>new Qv(e,t)))}function Gy(e){return e.context?.isOptional??!1}function uae(e){return e.context?.isMutable??!1}function Ky(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(Ky)}function dae(e){function t(e){return Ky(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Ma(n)?n:void 0}function fae(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Ev(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}const qy=/*#__PURE__*/ Ht(e=>{let t=ky(e);if(t!==e){let n=qy(t);return n===t&&e.encoding===void 0?e:jy(n,e.context)}let n=`recur`in e?e.recur(qy):e;if(`encodingChecks`in n&&n.encodingChecks){let t=fae(e)?n.encodingChecks:Cv(n)||wv(n)||yv(n)&&n.typeParameters.length>0?dae(n.encodingChecks):void 0;return Oy(n,{encodingChecks:void 0,checks:ry(n.checks,t)})}return n}),Jy=/*#__PURE__*/ Ht(e=>qy(Yy(e)));function pae(e,t){let n=t,r=n.length,i=n[r-1],a=[new Dv(Yy(Ay(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Dv(Yy(n[e-1].to),n[e].transformation.flip()));let o=Yy(i.to);return o.encoding?Ay(o,[...o.encoding,...a]):Ay(o,a)}const Yy=/*#__PURE__*/ Vt(e=>{if(e.encoding)return pae(e,e.encoding);let t=ky(e);if(t!==e){let n=Yy(t);return n===t?e:jy(n,e.context)}return`flip`in e?e.flip(Yy):`recur`in e?e.recur(Yy):e});function Xy(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(Xy);default:return!1}}function Zy(e,t){let n=t===0?f_:u_(t);return(r,i)=>r===l_?d_:r===t?n:z(new T_(e,r,i))}function Qy(e,t){return(n,r)=>n===l_?d_:t(n)?f_:z(new T_(e,n,r))}function $y(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 eb=/*#__PURE__*/ By(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(eb)}}),tb=/*#__PURE__*/ By(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(tb)}}),nb=/*#__PURE__*/ By(e=>{switch(e._tag){default:return e;case`Number`:case`Literal`:case`BigInt`:return e.toCodecStringTree();case`Union`:return e.recur(nb)}}),rb=/*#__PURE__*/ new globalThis.RegExp(`^${qv}$`),mae=/*#__PURE__*/ new globalThis.RegExp(`^(?:${qv}|Infinity|-Infinity|NaN)$`);function hae(e){return Ey(rb,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:rb.source}),...e})}const ib=/*#__PURE__*/ Fy(Vv,[/*#__PURE__*/ hae()]),gae=/*#__PURE__*/ new Dv(ib,hv),_ae=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([ib,yy]),hv);function ab(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=ab(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 y_(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function vae(e){if(!yv(e))return;let t=e.annotations?.[n_];return $t(t)?t(e.typeParameters):void 0}const ob=Qg,sb=i_,yae=o_;function bae(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function xae(e){return e===void 0||typeof e==`string`}function cb(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 lb(e){return cb(e,bae)}const ub=/*#__PURE__*/ new Mv([],()=>(e,t,n)=>lb(e)?f_:z(new T_(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>fb}),db=/*#__PURE__*/ new Dv(ub,/*#__PURE__*/ mv()),Sae=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([/*#__PURE__*/ new Wv(!1,[],[ub]),/*#__PURE__*/ new $v([],[/*#__PURE__*/ new Qv(Vv,ub)])]),/*#__PURE__*/ mv());function Cae(e){return cb(e,xae)}const fb=/*#__PURE__*/ new Dv(/* @__PURE__ */ new Mv([],()=>(e,t,n)=>Cae(e)?f_:z(new T_(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),/*#__PURE__*/ mv()),pb=(e,t,n)=>e===f_?n(t):Cm(e,n);function mb(e){if(e._tag===`Middleware`)return(t,n,r)=>{let i=t===f_?e.decode(u_(p_(n)),r):e.decode(bm(t,p_),r);return hb(i)};let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===f_?u_(t):e;case`Transform`:{let e=e=>e===l_?d_:u_(t.transform(e));return(t,n)=>pb(t,n,e)}case`TransformOptional`:{let e=e=>m_(t.transform(p_(e)));return(t,n)=>pb(t,n,e)}case`TransformEffect`:return(e,n,r)=>pb(e,n,e=>e===l_?d_:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>pb(e,n,e=>hb(t.transform(p_(e),r)))}}const hb=e=>Cm(e,m_),gb=(e,t,n,r)=>hp(r,r=>np(()=>gd(r,r=>new b_(e,r,t,n))));function wae(e,t){let n=mb(e.link.transformation),r;return(i,a)=>{if(i===l_)return d_;if(e.isConstructed(i))return f_;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function Tae(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==l_&&r!==void 0)return t(r,i);let a=n;if(vc(a)&&a._tag===`Success`){let e=t(a[fr],i);return e===f_?a:e}return Cm(gb(e,r,i,a),e=>{let n=t(e,i);return n===f_?u_(e):n})}}function Eae(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:Tae(e,n)}function _b(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?vae(e):void 0,o=a?wae(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>mb(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(vc(r)){if(r._tag===`Success`){let i=r===f_?t:r[fr];if(t!==l_&&i!==l_){let i=ab(u,t,void 0,e,n);i&&(r=z(new w_(e,i,t,n)))}}}else r=B(r,r=>{if(t!==l_&&r!==l_){let r=ab(u,t,void 0,e,n);if(r)return z(new w_(e,r,t,n))}return F(r)})}if(s&&!n.disableChecks){if(vc(r)){if(r._tag===`Success`){let i=r===f_?t:r[fr];if(i===l_)return r;let a=ab(s,i,void 0,e,n);a&&(r=z(new w_(e,a,i,n)))}}else r=B(r,t=>{if(t!==l_){let r=ab(s,t,void 0,e,n);if(r)return z(new w_(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[fr],o=t(a,r)):o=Cm(o,e=>{let n=t(e,r);return n===f_?u_(e):n})}if(o._tag===`Success`){let e=o[fr],t=p(e,r);return t===f_?o:t}return o=gb(e,n,r,o),Cm(o,e=>{let t=p(e,r);return t===f_?u_(e):t})}:p}const Dae=/*#__PURE__*/ Symbol(),vb=/*#__PURE__*/ new WeakMap,Oae=e=>bb(e).parser,yb=e=>bb(e).makeEffect,kae=e=>Eae(e,yb);var Aae=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=_b(this.ast,Oae)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=_b(this.ast,yb,kae)}};function bb(e){let t=vb.get(e);if(t!==void 0)return t;let n=new Aae(e);return vb.set(e,n),n}function xb(e){let t=e.ast,n;return(e,r)=>(n??=Ab(Vae,qy(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Sb(e){let t=xb(e);return(e,n)=>{let r=um(t(e,n));return Nd(r)?ji(r.value):(q_(r.cause,`Option adapter can only return none for schema issues`),Ai())}}function Cb(e){return zae(qy(e.ast))}function jae(e){return wb(e.ast)}function Mae(e){{let t=jb(kb(e));return e=>{let n=t(e,Ov);return Nd(n)?!0:(q_(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function wb(e){let t=qy(e),n=e=>(n=Mae(t),n(e));return e=>n(e)}function Tb(e,t){let n=kb(e.ast);return t===void 0?n:(e,r)=>n(e,Db(t,r))}function Nae(e,t){return Iae(Tb(e,t))}function Pae(e,t){return Lae(Tb(e,t))}function Eb(e,t){let n=kb(Yy(e.ast));return t===void 0?n:(e,r)=>n(e,Db(t,r))}const Db=(e,t)=>t?{...e,...t}:e,Ob=e=>e===l_?z(new E_):F(e);function kb(e){return Ab(Bae,e)}function Fae(e,t){return e===f_?F(t):vc(e)?e[`~effect/Effect/args`]===l_?Ob(l_):e:Cm(e,Ob)}function Ab(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Ov);return a===f_?F(r):vc(a)?a[`~effect/Effect/args`]===l_?Ob(l_):a:Cm(a,Ob)}}function jb(e){return(t,n)=>um(e(t,n))}function Iae(e){let t=jb(e);return(e,n)=>{let r=t(e,n);return Nd(r)?ji(r.value):(q_(r.cause,`Option adapter can only return none for schema issues`),Ai())}}function Lae(e){let t=jb(e);return(e,n)=>{let r=t(e,n);return Nd(r)?ba(r.value):xa(q_(r.cause,`Result adapter can only return schema issues`))}}function Rae(e,t){let n=um(e);if(Nd(n))return n.value;let r=q_(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function zae(e){let t,n;return(r,i)=>{t??=bb(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Ov,o=t.make;if(o!==void 0&&r!==l_){let e;try{e=o(r,a)}catch(e){throw q_(pd(e),`Constructor adapter can only throw schema issues`),e}if(e!==Dae&&e!==l_)return e}return Rae(Fae((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}const Bae=e=>bb(e).parser,Vae=e=>bb(e).makeEffect,Mb=`~effect/Schema/Schema`,Nb=/*#__PURE__*/ Symbol(),Hae={[Mb]:Mb,get make(){let e=Cb(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=xb(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Sb(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return jt(this,arguments)},annotate(e){return this.rebuild(Ny(this.ast,e))},annotateKey(e){return this.rebuild(Hy(this.ast,e))},check(...e){return this.rebuild(Fy(this.ast,e))},rebuild(e){return Pb(e,this[Nb])}};function Pb(e,t){function n(){}let r=Object.setPrototypeOf(n,Hae);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[Nb]=t,r.ast=e,r}function Uae(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Fb(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Ib(e){return encodeURI(Uae(e)).replace(/#/g,`%23`)}function Lb(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 Rb(e){let t=Lb(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(Fb)}function Wae(e){return e.reduce((e,t)=>`${e}/${Ib(t)}`,`#`)}const Gae=[`example`,`discriminator`,`xml`,`externalDocs`];function Kae(e){let t=Object.keys(e.definitions),n=/* @__PURE__ */ new Map,r=new Set(t.filter(e=>zb.test(e))),i=t.filter(e=>!zb.test(e)).sort().map(e=>[e,qae(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=Hb(t.$id),a=on(t.$defs)?t.$defs:void 0;return Bb(t,(t,o)=>{Xae(t,Gae,`OpenAPI 3.1`,`Draft 2020-12`),Vb(t,(t,s)=>{let c=t.startsWith(`#`)?Rb(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))&&Wb(s,`OpenAPI 3.1`,`a schema resource cannot reference the shared definitions pool`),t):o?t:Wae([`components`,`schemas`,n.get(l)??l,...c.slice(2)])})})}let o=e.schemas.map(e=>a(e,!0)),s={};for(let r of t)or(s,n.get(r)??r,a(e.definitions[r]));return{dialect:`openapi-3.1`,schemas:o,definitions:s}}const zb=/^[a-zA-Z0-9.\-_]+$/;function qae(e){return e.length===0?`_`:e.replace(/[^a-zA-Z0-9._-]/gu,`_`)}function Bb(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!on(e))return e;let a=r||!i&&Hb(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=Yae(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)}or(o,t,i)}return t(o,a),o}}function Jae(e,t){return Bb(e,e=>{Vb(e,t)})}function Vb(e,t){typeof e.$ref==`string`&&or(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&or(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function Yae(e,t){if(!on(e))return;let n={};for(let r of Object.keys(e))or(n,r,t(e[r],r));return n}function Hb(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}const Ub=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Ub],[...Ub];function Wb(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Xae(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Wb(i,n,`it is not active in ${r} but would become active in the target`)}function Zae(e){return Pb(Gb(e.ast),{schema:e})}const Gb=/*#__PURE__*/ By(e=>{let t=$ae(e,Gb),n=e.context;return t===e||n===void 0?t:zy(t,Kb(n))});function Kb(e){return e.constructorDefault===void 0?e:new kv(e.isOptional,e.isMutable,void 0,e.annotations)}function qb(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Jb(e){return t=>{let n=[...t].sort((t,n)=>e(Jy(t))-e(Jy(n)));return n.some((e,n)=>e!==t[n])?n:t}}const Qae=/*#__PURE__*/ Jb(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function $ae(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!$t(n))return Ay(e,[db]);let r=n(e.typeParameters.map(e=>Pb(Jy(e))));return r===void 0?e:Ay(e,[Iy(r,t)])}case`Unknown`:return Ay(e,[db]);case`ObjectKeyword`:return Ay(e,[Sae]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return qb(e),e.recur(t,tb);case`Union`:{let n=Qae(e.types);return n===e.types?e.recur(t):new hy(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 eoe(e){return Pb(Zb(e.ast),{schema:e})}function toe(e){return Pb($b(e.ast))}const noe=/*#__PURE__*/ Jb(e=>{switch(e._tag){case`Null`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function roe(e,t,n){switch(e._tag){case`Declaration`:{let r=e.typeParameters.map(e=>Pb(t(Jy(e)))),i=e.annotations?.toCodecStringTree;if($t(i)){let n=i(r);return n===void 0?e:Ay(e,[Iy(n,t)])}let a=e.annotations?.toCodecJson,o=$t(a)?a(r):void 0,s=o===void 0?e.annotations?.toCodec:void 0,c=o??($t(s)?s(r):void 0);return c===void 0?n(e):Ay(e,[Iy(c,t)])}case`Null`:return Ay(e,[ioe]);case`Boolean`:return Ay(e,[aoe]);case`Unknown`:case`ObjectKeyword`:return Ay(e,[fb]);case`Enum`:case`Number`:case`Literal`:case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return qb(e),e.recur(t,tb);case`Union`:{let n=noe(e.types);return n===e.types?e.recur(t):new hy(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 ioe=/*#__PURE__*/ new Dv(/*#__PURE__*/ new zv(`null`),/*#__PURE__*/ new uv(/*#__PURE__*/ rv(()=>null),/*#__PURE__*/ rv(()=>`null`))),aoe=/*#__PURE__*/ new Dv(/*#__PURE__*/ new hy([/*#__PURE__*/ new zv(`true`),/*#__PURE__*/ new zv(`false`)]),/*#__PURE__*/ new uv(/*#__PURE__*/ rv(e=>e===`true`),/*#__PURE__*/ sv())),Yb=/*#__PURE__*/ new uv(/*#__PURE__*/ rv(e=>typeof e==`string`?[e]:e),/*#__PURE__*/ nv()),Xb=e=>e.transformation===Yb,Zb=/*#__PURE__*/ By(e=>{let t=roe(e,Zb,e=>{throw new globalThis.Error(`Missing structural codec for StringTree`,{cause:e})});return t!==e&&e.context!==void 0?zy(t,Kb(e.context)):t},{stopAt:Xb}),Qb=e=>Gy(e)?Uy(Iv):Iv,$b=/*#__PURE__*/ By(e=>{let t=ooe(e);if(Cv(t)){let n=Wy(new hy([new Wv(t.isMutable,t.elements.map(Qb),t.rest.map(Qb)),Vv],{mode:`anyOf`}),t,Yb);return Gy(e)?Uy(n):n}return t},{stopAt:Xb});function ooe(e){return e._tag===`Declaration`||e._tag===`Arrays`||e._tag===`Objects`||e._tag===`Union`||e._tag===`Suspend`?e.recur($b):e}globalThis.RegExp;const soe=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function ex(e,t){return t.length>0&&(e+=`\n at ${Yn(t)}`),Error(e)}function tx(e){return`#/$defs/${Ib(e)}`}const coe=/*#__PURE__*/ new Set([...c_,e_,...r_]);function nx(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;lb(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&lb(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(lb(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))!coe.has(r)&&t.includeAnnotationKey(r)&&lb(i)&&or(n,r,i);return Object.keys(n).length===0?void 0:n}function rx(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=rx(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 loe(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 ix(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function uoe(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}function doe(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 ax=`|title|description|default|examples|readOnly|writeOnly|`;function ox(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=loe(e);if(i!==void 0||a){let r=rx(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:ix(r.schema,ax)&&uoe(o,s)?{...o,...r.schema}:ox(o,r.schema,n)}}if(n){let n=doe(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 sx(e,t=/* @__PURE__ */ new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>sx(e,t)))}function foe(e){return Array.isArray(e)}function cx(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=Ia(e,(e,n)=>v(e,t[n],[]));for(let[e,t]of s.values())if(!sx(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=>An(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Ia(u,h),f={};for(let e of l)a.has(e)||or(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 ex(`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 Jae(e,e=>{let t=Lb(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(Fb(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,tx(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[e_]: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=foe(s);c&&i.push(!1);let l=c?s[0]:s,u=nx(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`&&ix(d,f)&&(u===void 0||ix(u,ax))?!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=nx(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:tx(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=nx(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&poe(s.type)?s.type:void 0,i=_(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=ox(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 ex(`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(lx).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw ex(`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=nx(e.annotations,r);return s===void 0?o:p(ox(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 ex(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=v(s.type,[...t,`propertySignatures`,i,`type`],n),u=nx(s.annotations,r);or(a,c,u===void 0?l:p(ox(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);An(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];or(s,e,t===void 0?a:t===!1||a===!1?!1:p(ox(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=moe(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 ex(`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 sx(n)&&r.type===`string`&&typeof r.pattern==`string`&&ix(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(lx).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 ex(`Invalid schema representation document`,t)}}}function poe(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function moe(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 lx(e){switch(e._tag){case`Literal`:return soe(globalThis.String(e.literal));case`String`:return`[\\s\\S]*?`;case`Number`:return qv;case`TemplateLiteral`:return e.parts.map(lx).join(``);case`Union`:return`(?:${e.types.map(lx).join(`|`)})`;default:throw ex(`Invalid schema representation document`,[])}}function hoe(e,t){let n=cx([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}function goe(e,t){return cx(e.representations,e.representations.map((e,t)=>[`representations`,t]),e.references,t)}const _oe=({identifier:e})=>e;function ux(e){return e===void 0?void 0:{annotations:e}}function voe(e,t){let{references:n,representations:r}=dx([e],t);return{representation:r[0],references:n}}function dx(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??_oe;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:Ia(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:Ny(e,{identifier:n}):a_(e)===r?e:Ny(e,{[e_]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),or(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=My(e),n=ky(t),r=i_(t),i=r===void 0?(t===e?void 0:i_(e))??a_(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(qy(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,...ux(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...ux(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...ux(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...ux(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...ux(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=My(e),n=t.context?.annotations;return{isOptional:Gy(t),type:m(e),...ux(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...ux(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=My(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Gy(t),isMutable:uae(t),...ux(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...ux(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...ux(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...ux(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:Ia(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(qy(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function fx(e){return Nd(e)?e.value:{issues:[{message:dre(e.cause)}]}}function yoe(e,t){let n=Tb(e),r={errors:`all`,...t?.parseOptions},i=I_(t),a=e=>{let t=new jo(`sync`),a=am(Dp(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?fx(o):new Promise(e=>{a.addObserver(t=>{e(fx(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 boe=/*#__PURE__*/ j(2,(e,t)=>Coe(e,(e,n)=>Soe(t,e)?void 0:[e,n])),xoe=/*#__PURE__*/ j(2,(e,t)=>({...e,...t})),px=e=>e;function Soe(e,t){return e.some(e=>e===t||typeof e==`number`&&String(e)===t)}function Coe(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;or(n,e,t)}}return n}const mx=`~effect/Schema/SchemaError`;function hx(e){return N(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}({...er}),{...er},{...er},{...er},{...er},{...er},{...er},{...er};const gx=Mb;function _x(){return(e,t,n)=>Ax(new Mv(e.map(ay),e=>t(e.map(e=>Ax(e))),n))}function vx(e,t){return _x()([],()=>(t,n,r)=>e(t)?F(t):z(new T_(n,t,r)),t)}var yx=class extends (/*#__PURE__*/ Bo(`SchemaError`)){[mx]=mx;constructor(e){let t=nr();rr(0);try{super({issue:e})}finally{rr(t)}}get message(){return U_(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[Qn](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}};function woe(e){return hx(e)}function bx(e){return vc(e)?Toe(e):hp(e,e=>np(()=>gd(e,e=>new yx(e))))}function Toe(e){return Nd(e)?e:Od(gd(e.cause,e=>new yx(e)))}function Eoe(e,t){let n;for(let r of e.reasons){if(!dd(r)||!woe(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 xx(e){let t=um(e);if(Nd(t))return t.value;throw Eoe(t.cause,`Sync adapter can only throw schema errors`)}function Doe(e,t){return yoe(e,t)}const Sx=jae;function Cx(e,t){let n=Tb(e,t);return(e,t)=>bx(n(e,t))}const wx=Cx,Ooe=Nae;function koe(e,t){let n=Pae(e,t);return(e,t)=>ste(n(e,t),e=>new yx(e))}function Tx(e,t){let n=Cx(e,t);return(e,t)=>xx(n(e,t))}const Aoe=Tx;function Ex(e,t){let n=Eb(e,t);return(e,t)=>bx(n(e,t))}const Dx=Ex;function Ox(e,t){let n=Ex(e,t);return(e,t)=>xx(n(e,t))}const kx=Ox,Ax=Pb;function jx(e){return N(e,gx)&&e[gx]===gx}const Mx=/*#__PURE__*/ px(e=>Ax(Uy(e.ast),{schema:e})),Nx=/*#__PURE__*/ px(e=>{let t=Qx(e);return Ax(oae(e.ast),{schema:t})}),Px=/*#__PURE__*/ px(e=>Ax(qy(e.ast),{schema:e})),joe=/*#__PURE__*/ px(e=>Ax(Jy(e.ast),{schema:e}));function Fx(e){let t=Ax(new zv(e),{literal:e,transform(n){return t.pipe($x(Fx(n),{decode:rv(()=>n),encode:rv(()=>e)}))}});return t}function Moe(e){return e.map(e=>jx(e)?e.ast:new zv(e))}function Ix(e){return Ax(new Hie(Moe(e)),{parts:e})}const Lx=/*#__PURE__*/ Ax(Bie),Rx=/*#__PURE__*/ Ax(Vie),zx=/*#__PURE__*/ Ax(Iv),Noe=/*#__PURE__*/ Ax(Nv),Poe=/*#__PURE__*/ Ax(Fv),U=/*#__PURE__*/ Ax(Vv),Bx=/*#__PURE__*/ Ax(Uv),Vx=/*#__PURE__*/ Ax(Gie),Hx=/*#__PURE__*/ Ax(zie);function Ux(e,t){return Ax(e,{fields:t,mapFields(e,t){let n=e(this.fields);return Ux(iy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function W(e){return Ux(iy(e,void 0),e)}function Wx(e){return px(t=>t.mapFields(xoe(e)))}function Gx(e,t){return Ax(lae(e.ast,t.ast),{key:e,value:t})}function Kx(e,t){return Ax(Zie(e.ast,t.map(ay)),{schema:e,records:t})}function qx(e,t){return Ax(e,{elements:t,mapElements(e,t){let n=e(this.elements);return qx(oy(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function Foe(e){return qx(oy(e),e)}const G=/*#__PURE__*/ px(e=>Ax(new Wv(!1,[],[e.ast]),{value:e})),Jx=/*#__PURE__*/ px(e=>Ax(new Wv(!1,[e.ast],[e.ast]),{value:e}));function Yx(e,t){return Ax(e,{members:t,mapMembers(e,t){let n=e(this.members);return Yx(sy(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function K(e,t){return Yx(sy(e,t,void 0),e)}function Xx(e){let t=e.map(Fx);return Ax(sy(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return K(e(this.members))},pick(e){return Xx(e)},transform(e){return K(t.map((t,n)=>t.transform(e[n])))}})}const Zx=/*#__PURE__*/ px(e=>K([e,Noe])),Qx=/*#__PURE__*/ px(e=>K([e,Poe]));function $x(e,t){return n=>Ax(Wy(n.ast,e.ast,t?dv(t):mv()),{from:n,to:e})}function Ioe(){return(e,t)=>iS()(e,{decode:t,encode:ev})}const Loe=/*#__PURE__*/ Xx([`true`,`yes`,`on`,`1`,`y`]),Roe=/*#__PURE__*/ Xx([`false`,`no`,`off`,`0`,`n`]),zoe=/*#__PURE__*/ Xx([...Loe.literals,...Roe.literals]).pipe(/*#__PURE__*/ $x(Vx,/*#__PURE__*/ pv({decode:e=>e===`true`||e===`yes`||e===`on`||e===`1`||e===`y`,encode:e=>e?`true`:`false`})));function Boe(e){return t=>$x(Px(t),e)(t)}function eS(e){return t=>Ax(sae(t.ast,e),{schema:t})}function tS(e){return Fx(e).pipe(eS(F(e)))}function nS(e,t){return W({_tag:tS(e),...t})}function rS(){return e=>e}function Voe(e,t){return vx(t=>t instanceof e,t)}function iS(){return(e,t)=>new Dv(e.ast,dv(t))}const aS=wy,oS=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Hoe(e){let t=new globalThis.RegExp(oS);return aS(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:oS,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 Ey(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}const cS=/*#__PURE__*/ Ax(Ty);function Uoe(e){let t=ki(e.order),n=e.formatter??qn;return(r,i)=>aS(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 Woe(e){let t=ki(e.order),n=Di(e.order),r=Oi(e.order),i=Ei(e.order),a=e.formatter??qn;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return aS(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 lS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${qn(e)}`);return e}const Goe=/*#__PURE__*/ Uoe({order:wi,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:lS(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${qn(e)})`})})}),uS=/*#__PURE__*/ Woe({order:wi,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:lS(e.minimum),maximum:lS(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 Koe(e){return aS(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 dS=/*#__PURE__*/ Bx.check(/*#__PURE__*/ Koe());function fS(e,t){return e=hS(e),pS(e,Math.ceil(e/2),t)}function pS(e,t,n){return aS(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})`}),[$g]:!0,arbitraryConstraint:{minLength:e},...n})}function qoe(e){return pS(1,1,e)}function mS(e,t){return e=hS(e),aS(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})`}),[$g]:!0,arbitraryConstraint:{maxLength:e},...t})}function hS(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Joe(e,t){return e=hS(e),aS(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})`}),[$g]:!0,arbitraryConstraint:{minProperties:e},...t})}function gS(e){return aS(e=>Tte(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 _S=/*#__PURE__*/ U.check(/*#__PURE__*/ qoe()),Yoe=e=>+(e?.includeStack===!0)|(e?.excludeCause===!0?2:0),vS=e=>{switch(e){case 0:return;case 1:return{includeStack:!0};case 2:return{excludeCause:!0};case 3:return{includeStack:!0,excludeCause:!0}}},yS=[];function bS(e){let t=Yoe(e),n=yS[t];if(n!==void 0)return n;let r=QS.pipe($x(zx,Mie(vS(t))));return yS[t]=r,r}globalThis.RegExp,globalThis.URL;const xS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function SS(e,t){return xS.pipe($x(e,Nie(t)))}const CS=/*#__PURE__*/ SS(zx);globalThis.File,globalThis.FormData,globalThis.URLSearchParams;const wS=/*#__PURE__*/ U.check(/*#__PURE__*/ Hoe()),TS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(/*#__PURE__*/ $x(wS,/*#__PURE__*/ Tie())),ES=/*#__PURE__*/ U.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),DS=/*#__PURE__*/ Voe(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>iS()(ES,_v)}),OS=/*#__PURE__*/ ES.pipe(/*#__PURE__*/ $x(DS,_v));function kS(e,t){let n=_x()([e,t],([e,t])=>(n,r,i)=>{if(!rre(n))return z(new T_(r,n,i));switch(n._tag){case`Fail`:return Sm(Tb(e)(n.error,i),{onSuccess:md,onFailure:e=>D_(r,`error`,e,n,i)});case`Die`:return Sm(Tb(t)(n.defect,i),{onSuccess:hd,onFailure:e=>D_(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])=>iS()(K([W({_tag:Fx(`Fail`),error:e}),W({_tag:Fx(`Die`),defect:t}),W({_tag:Fx(`Interrupt`),fiberId:Qx(cS)})]),pv({decode:e=>{switch(e._tag){case`Fail`:return md(e.error);case`Die`:return hd(e.defect);case`Interrupt`:return ore(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 Ax(n.ast,{error:e,defect:t})}function AS(e,t){let n=_x()([e,t],([e,t])=>{let n=G(kS(e,t));return(e,t,r)=>nre(e)?Sm(Tb(n)(e.reasons,r),{onSuccess:fd,onFailure:n=>D_(t,`failures`,n,e,r)}):z(new T_(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])=>iS()(G(kS(e,t)),pv({decode:fd,encode:({reasons:e})=>e}))});return Ax(n.ast,{error:e,defect:t})}const jS=/*#__PURE__*/ fv({decode:(e,t)=>Pi(hh(e),{onNone:()=>z(new E_({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>F(gh(e))}),encode:e=>F(vh(e))});function MS(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 NS(e,t){return dS.check(uS({minimum:e,maximum:t}))}const PS=/*#__PURE__*/ vx(e=>dh(e)&&fh(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]=MS(e,-864e13,864e13);return Ioe()(NS(t,n),rv(mh))},toCodecJson:()=>iS()(U,jS),toFormatter:()=>e=>e.toString()}),FS=/*#__PURE__*/ U.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(/*#__PURE__*/ $x(PS,jS));function IS(e,t,n){let r=_x()([e,t,n],([e,t,n])=>{let r=AS(t,n);return(t,n,i)=>{if(!Ed(t))return z(new T_(n,t,i));switch(t._tag){case`Success`:return Sm(Tb(e)(t.value,i),{onSuccess:Dd,onFailure:e=>D_(n,`value`,e,t,i)});case`Failure`:return Sm(Tb(r)(t.cause,i),{onSuccess:Od,onFailure:e=>D_(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])=>iS()(K([W({_tag:Fx(`Success`),value:e}),W({_tag:Fx(`Failure`),cause:AS(t,n)})]),pv({decode:e=>e._tag===`Success`?Dd(e.value):Od(e.cause),encode:e=>Nd(e)?{_tag:`Success`,value:e.value}:{_tag:`Failure`,cause:e.cause}}))});return Ax(r.ast,{value:e,error:t,defect:n})}function LS(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:Tb(Fx(n)),o=_x()([e],([e])=>(t,n,r)=>{if(og(t)){let i=a===void 0?L:xm(a(t.label,r),e=>new x_([`label`],e));return Cm(i,()=>Sm(Tb(e)(lg(t),r),{onSuccess:e=>sg(e,{label:t.label}),onFailure:()=>new w_(n,[new x_([`value`],new E_(void 0,t,r))],t,r)}))}return z(new T_(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])=>iS()(e,{decode:rv(e=>sg(e,{label:n})),encode:r?$_(e=>`Cannot serialize Redacted`+(Ni(e)&&typeof e.value.label==`string`?` with label: "${e.value.label}"`:``)):rv(lg)}),toEquivalence:([e])=>ug(e)});return Ax(o.ast,{value:e})}const RS=/*#__PURE__*/ globalThis.Symbol.for(`immer-draftable`),zS={};function BS(e,t,n,r,i){let a=US(n,t,r),o=HS(t),s=class extends e{constructor(...[e,t]){let r=t?.[`~payload`],i=r?.token===zS?r.value:n.make(e??{},t);super(i,{...t,disableChecks:!0,"~payload":{token:zS,value:i}})}static[gx]=gx;get[o](){return o}static[RS]=!0;static identifier=t;static fields=n.fields;static get ast(){return a(this).ast}static pipe(){return jt(this,arguments)}static rebuild(e){return a(this).rebuild(e)}static make(e,t){return Cb(a(this))(e??{},t)}static makeOption(e,t){return Sb(a(this))(e??{},t)}static makeEffect(e,t){return a(this).makeEffect(e??{},t)}static annotate(e){return this.rebuild(Ny(this.ast,e))}static annotateKey(e){return this.rebuild(Hy(this.ast,e))}static check(...e){return this.rebuild(Fy(this.ast,e))}static extend(e){return(t,r)=>{let a=WS(t)?t:W(t),o={...n.fields,...a.fields},s=iy(o,n.ast.checks,{identifier:e});return BS(this,e,Ux(Fy(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 VS(e){return new uv(rv(t=>new e(t,{"~payload":{token:zS,value:t}})),nv())}function HS(e){return`~effect/Schema/Class/${e}`}function US(e,t,n){let r;return i=>{if(r!==void 0)return r;let a=HS(t),o=e=>e instanceof i||N(e,a),s=VS(i);return r=$x(Ax(new Mv([e.ast],()=>(e,t,n)=>o(e)?F(e):z(new T_(t,e,n)),{identifier:t,[n_]:([e])=>({isConstructed:o,link:new Dv(e,s)}),toCodec:([e])=>new Dv(e.ast,s),toEquivalence:([e])=>e,toFormatter:([e])=>t=>`${i.identifier}(${e(t)})`,[t_]:uy(e.ast),...n})),s)(e)}}function WS(e){return jx(e)}const GS=e=>(t,n)=>{let r=WS(t)?t:W(t);return BS(Fo,e,r,n,e=>({toString(){return`${e}(${qn({...this})})`}}))},KS=e=>(t,n)=>{let r=WS(t)?t:W(t);return BS(Qr,e,r,n,e=>({name:e}))},qS=e=>(t,n,r)=>{let i=WS(n)?n.mapFields(e=>({_tag:tS(t),...e}),{unsafePreserveChecks:!0}):nS(t,n);return KS(e??t)(i,r)};function JS(e,t){return hoe(voe(Gb(e.ast),t),t)}const YS=Zae,XS=eoe,ZS=toe,QS=/*#__PURE__*/ Ax(/*#__PURE__*/ Ny(ub,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),q=/*#__PURE__*/ Gx(U,QS);function $S(){return Object.assign(e=>e,{option:e=>ji(e),result:e=>ba(e),is:e=>!0})}const eC=Ls,tC=Rs,nC=Ms,rC=ru,iC=mu,aC=hu,oC=`~effect/MutableRef`,sC={[oC]:oC,...vr,toJSON(){return{_id:`MutableRef`,current:$n(this.current)}}},cC=e=>{let t=Object.create(sC);return t.current=e,t},lC=/*#__PURE__*/ j(2,(e,t)=>(e.current=t,e)),uC=/*#__PURE__*/ Symbol.for(`effect/MutableList/Empty`),dC=()=>({head:void 0,tail:void 0,length:0}),fC=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})},pC=()=>({array:[],mutable:!0,offset:0,next:void 0}),mC=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=pC(),e.tail=e.tail.next):e.head=e.tail=pC(),e.tail.array.push(t),e.length++},hC=(e,t)=>{e.head={array:[t],mutable:!0,offset:0,next:e.head},e.tail||=e.head,e.length++},gC=(e,t)=>_C(e,ka(t),!Array.isArray(t)),_C=(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},vC=e=>{e.head=e.tail=void 0,e.length=0},yC=(e,t)=>{if(t=ya(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 vC(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?vC(e):fC(e),n;i=i.next}return vC(e),n},bC=e=>yC(e,e.length),xC=e=>{if(!e.head)return uC;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:vC(e):fC(e),t},SC=(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?vC(e):(e.head=e.tail={array:n,mutable:!0,offset:0,next:void 0},e.length=n.length)},CC=(e,t)=>SC(e,e=>e!==t),wC=e=>I(()=>BC(e.atomicPubSub(),/* @__PURE__ */ new Map,qd(),iC(!1),cC(!1),e.strategy(),cC(Ai()))),TC=e=>wC({atomicPubSub:()=>EC(e),strategy:()=>new VC}),EC=e=>{let t=e?.replay;return new IC(t&&t>0?new WC(Math.ceil(t)):void 0)},DC=/*#__PURE__*/ j(2,(e,t)=>Qf(()=>e.shutdownFlag.current||Ni(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))),OC=e=>Xp(jp(t=>{let n=da(t,Kd),r=Qd(e.scope),i=FC(e.pubsub,e.subscribers,e.strategy,e.ended);return Xd(r,kC(i)).pipe(sp(Yd(n,e=>$d(r,e))),dp(i))})),kC=e=>Xp(ap(t=>(lC(e.shutdownFlag,!0),qf(bC(e.pollers),e=>bre(e,t.id),{discard:!0,concurrency:`unbounded`}).pipe(cp(()=>I(()=>{e.subscribers.delete(e.subscription),e.subscription.unsubscribe(),e.replayWindow.close(),e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers)})),uie(e.shutdownHook.open),fp)))),AC=e=>Qf(()=>{if(e.shutdownFlag.current)return qp;if(e.replayWindow.remaining>0){let t=e.replayWindow.take();return F(t)}let t=e.pollers.length===0?e.subscription.poll():uC;return t===uC?jC(e):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),F(t))}),jC=e=>$f(t=>{if(e.shutdownFlag.current)return t(qp);if(Ni(e.ended.current)){let n=e.pollers.length===0?e.subscription.poll():uC;return n===uC?t(F(e.ended.current.value)):(e.strategy.onPubSubEmptySpaceUnsafe(e.pubsub,e.subscribers),t(F(n)))}let n=Ld(),r=e.subscribers.get(e.subscription);return r||(r=/* @__PURE__ */ new Set,e.subscribers.set(e.subscription,r)),r.add(e.pollers),mC(e.pollers,n),e.strategy.completePollersUnsafe(e.pubsub,e.subscribers,e.subscription,e.pollers),n.effect?t(n.effect):(n.resumes=[t],I(()=>CC(e.pollers,n)))}),MC=/*#__PURE__*/ Symbol.for(`effect/PubSub/AbsentValue`),NC=(e,t,n)=>{e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(n)},PC=(e,t,n)=>{if(!e.has(t))return;let r=e.get(t);r.delete(n),r.size===0&&e.delete(t)},FC=(e,t,n,r)=>new RC(e,t,e.subscribe(),dC(),iC(!1),cC(!1),n,e.replayWindow(),r);var IC=class{publisherHead={value:MC,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 GC(this.replayBuffer):KC}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=MC,this.subscribersIndex+=1,this.replayBuffer?.slide(t,e.replayIndex)}}subscribe(){return this.publisherTail.subscribers+=1,new LC(this,this.publisherTail,this.publisherIndex,!1)}},LC=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===MC?(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 uC;let e=!0,t=uC;for(;e;)if(this.subscriberHead===this.self.publisherTail)e=!1;else{let n=this.subscriberHead.next.value;n!==MC&&(t=n,--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=MC,this.self.subscribersIndex+=1),e=!1),this.subscriberHead=this.subscriberHead.next,this.subscriberIndex+=1}return t}pollUpTo(e){e=ya(e);let t=[],n=0;for(;n!==e;){let r=this.poll();r===uC?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!==MC&&(--this.subscriberHead.subscribers,this.subscriberHead.subscribers===0&&(this.self.publisherHead=this.self.publisherHead.next,this.self.publisherHead.value=MC,this.self.subscribersIndex+=1)),this.subscriberHead=this.subscriberHead.next}},RC=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 jt(this,arguments)}},zC=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 jt(this,arguments)}};const BC=(e,t,n,r,i,a,o)=>new zC(e,t,n,r,i,a,o);var VC=class{get shutdown(){return L}handleSurplus(e,t,n,r){return F(!1)}onPubSubEmptySpaceUnsafe(e,t){}completePollersUnsafe(e,t,n,r){return HC(this,e,t,n,r)}completeSubscribersUnsafe(e,t){return UC(this,e,t)}};const HC=(e,t,n,r,i)=>{let a=!0;for(;a&&!r.isEmpty();){let o=xC(i);if(o===uC)PC(n,r,i),i.length===0?a=!1:NC(n,r,i);else{let a=r.poll();a===uC?hC(i,o):(Wd(o,Dd(a)),e.onPubSubEmptySpaceUnsafe(t,n))}}},UC=(e,t,n)=>{for(let[r,i]of n)for(let a of i)e.completePollersUnsafe(t,n,r,a)};var WC=class{capacity;head={value:MC,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:MC,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)}},GC=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]=MC,this.index=(this.index+1)%this.values.length,this.remaining--,this.remaining===0&&this.close(),e}takeN(e){e=ya(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 KC={remaining:0,take:()=>void 0,takeN:()=>[],takeAll:()=>[],close:()=>void 0},qC={_A:M,_E:M},JC={"~effect/Queue":qC,"~effect/Queue/Enqueue":qC,"~effect/Queue/Dequeue":qC,...vr,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:mw(this)}}},YC=e=>Zr(t=>{let n=Object.create(JC);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=dC(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:/* @__PURE__ */ new Set,offers:/* @__PURE__ */ new Set,awaiters:/* @__PURE__ */ new Set},Bs(n)}),XC=e=>YC({capacity:e}),ZC=e=>YC({capacity:e,strategy:`dropping`}),QC=/*#__PURE__*/ j(2,(e,t)=>Ws(()=>$C(e,t)?gw:e.state._tag===`Open`&&e.strategy===`suspend`?Tw(e,t):hw)),$C=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(xC(e.messages),mC(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(mC(e.messages,t),yw(e),!0):(mC(e.messages,t),bw(e),!0):!1,ew=/*#__PURE__*/ j(2,(e,t)=>Zs(n=>{let r=tw(e,t);return r.length===0||e.strategy===`dropping`?n(Gr(r)):Ew(e,{_tag:`Array`,remaining:r,offset:0,resume:n})})),tw=(e,t)=>{if(e.state._tag!==`Open`)return ka(t);if(e.capacity===1/0||e.strategy===`sliding`)return gC(e.messages,t),e.strategy===`sliding`&&yC(e.messages,e.messages.length-e.capacity),bw(e),[];let n=e.capacity<=0?e.state.takers.size:e.capacity-e.messages.length;if(n===0)return ka(t);let r=[],i=0;for(let a of t)i<n?mC(e.messages,a):r.push(a),i++;return bw(e),r},nw=/*#__PURE__*/ j(2,(e,t)=>Us(()=>rw(e,t))),rw=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Jr(t),r=kne(n,_w);return e.state.offers.size===0&&e.messages.length===0?(Aw(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},bw(e),!0)},iw=e=>nw(e,Fr(ri())),aw=e=>rw(e,Fr(ri())),ow=e=>Us(()=>sw(e)),sw=e=>{if(e.state._tag===`Done`)return!1;vC(e.messages);let t=e.state.offers;Aw(e,e.state._tag===`Open`?vw:e.state.exit);for(let e of t)Dw(e);return!0},cw=e=>uw(e,1,1/0),lw=e=>Ws(()=>{let t=Pa();return ac(If(Ul({while:Ft,body:Pt(cw(e)),step(e){for(let n=0;n<e.length;n++)t.push(e[n])}}),()=>Ys),t)}),uw=/*#__PURE__*/ j(3,(e,t,n)=>(t=ya(t),n=ya(n),Sw(()=>xw(e,t,n)??pc(ww(e,()=>Cw(e,t)),uw(e,t,n))))),dw=e=>Sw(()=>pw(e)??pc(ww(e,()=>Cw(e,1)),dw(e))),fw=e=>Sw(()=>{let t=pw(e);return t===void 0?Bs(Ai()):t._tag===`Success`?Bs(ji(t.value)):Bs(Ai())}),pw=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=xC(e.messages);return kw(e),Gr(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=Ow(e.state.offers);return kw(e),Gr(t)}},mw=e=>e.state._tag===`Done`?0:e.messages.length,hw=/*#__PURE__*/ Gr(!1),gw=/*#__PURE__*/ Gr(!0),_w=/*#__PURE__*/ Yr(/*#__PURE__*/ ri()),vw=/*#__PURE__*/ bc(),yw=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(Cc),e.messages.length===0))break}},bw=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,yw(e)},0))},xw=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Gr([]);if(!Cw(e,t))return;let r=e.messages.length>0?yC(e.messages,n):[Ow(e.state.offers)];return kw(e),Gr(r)},Sw=/*#__PURE__*/ Ur({op:`QueueTake`,[pr](e){let t=this[fr]();return xr(t)?t[pr](e):t}}),Cw=(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,ww=(e,t)=>Zs(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(Cc);let r={ready:t,resume:n};return e.state.takers.add(r),Us(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),Tw=(e,t)=>Zs(n=>$C(e,t)?n(gw):Ew(e,{_tag:`Single`,message:t,resume:n})),Ew=(e,t)=>{if(e.state._tag!==`Open`)return Dw(t);let n=e.state.offers;return n.add(t),Us(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&Aw(e,e.state.exit))})},Dw=e=>e._tag===`Single`?e.resume(hw):e.resume(Gr(e.remaining.slice(e.offset))),Ow=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(gw),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Gr([]))),n},kw=e=>{if(e.state._tag===`Done`)return Lf(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(Aw(e,e.state.exit),Lf(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`)mC(e.messages,t.message),e.state.offers.delete(t),t.resume(gw);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;mC(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Gr([]))}let r=e.state;if(r._tag===`Done`)return Lf(r.exit.cause)}return!1},Aw=(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()},jw=e=>new Nw(e),Mw=(e,t,n)=>Zs(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),Us(()=>{e.waiters.delete(i)})});var Nw=class{waiters=/*#__PURE__*/ new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Ws(()=>this.free<e?Mw(this,e,t):(this.taken+=e,Bs(e)));return t}takeIfAvailable(e){return Ws(()=>this.free<e?Bs(!1):(this.taken+=e,Bs(!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 Zr(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Ys))}release(e){return Zr(t=>Bs(this.releaseUnsafe(t,e)))}get releaseAll(){return Zr(e=>Bs(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>Vl(n=>{let r=Ws(()=>{if(this.free<e){let t=Mw(this,e,Ys);return _c(n(t),()=>r)}return this.taken+=e,xl(n(t),()=>{this.releaseUnsafe(Ms(),e)},!0)});return r})}withPermit=/*#__PURE__*/ this.withPermits(1);withPermitsIfAvailable(e){return t=>Vl(n=>this.free<e?Ks:(this.taken+=e,xl(n(fc(t)),()=>{this.releaseUnsafe(Ms(),e)},!0)))}};const Pw=e=>Us(()=>new Nw(e)),Fw=`~effect/Channel`,Iw=e=>N(e,Fw),Lw={[Fw]:{_Env:M,_InErr:M,_InElem:M,_OutErr:M,_OutElem:M},pipe(){return jt(this,arguments)}},Rw=e=>{let t=Object.create(Lw);return t.transform=(t,n)=>hp(e(t,n),e=>F(tp(e))),t},zw=(e,t)=>Rw((n,r)=>B(Hw(e)(n,r),e=>t(e,r))),Bw=e=>Rw((t,n)=>e),Vw=e=>Rw(H(function*(t,n){let r=Qd(n),i=e=>$d(r,Bf(e)),a=yield*Up(e(t,n,r),i);return Up(a,i)})),Hw=e=>e.transform,Uw=(e,t,n)=>YC({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(cp(t=>Xd(e,ow(t))),cp(n=>Jd(t(n),e).pipe(hp(e=>nw(n,e)),rm(e)))),Ww=(e,t)=>Rw((n,r)=>V(Uw(r,e,t),cw)),Gw=e=>Rw((t,n)=>Qf(()=>Hw(e())(t,n))),Kw=e=>Bw(I(()=>{let t=e();return Qf(()=>{let e=t.next();return e.done?Sd(e.value):F(e.value)})})),qw=e=>Qw(F(e)),Jw=/*#__PURE__*/ Bw(/*#__PURE__*/ F(/*#__PURE__*/ Sd())),Yw=e=>Bw(F(z(e))),Xw=e=>Bw(tp(e)),Zw=e=>Xw(pd(e)),Qw=e=>Bw(I(()=>{let t=!1;return Qf(()=>t?Sd():(t=!0,e))})),$w=e=>Bw(B(e,()=>Sd())),eT=e=>Bw(F(cw(e))),tT=e=>Rw((t,n)=>nT({scope:n,readable:e.evaluate(),onError:e.onError,releaseLockOnEnd:e.releaseLockOnEnd})),nT=e=>{let t=e.readable.getReader(),n=e.exit??cC(void 0),r=Qf(()=>n.current?n.current:Op(Xf({try:()=>t.read(),catch:e.onError}),{onFailure:e=>n.current??tp(e),onSuccess:({done:e,value:t})=>n.current?n.current:e?Sd():F(Fa(t))}));return dp(Xd(e.scope,e.releaseLockOnEnd?I(()=>t.releaseLock()):Yf(()=>t.cancel().catch(Rt))),r)},rT=/*#__PURE__*/ j(2,(e,t)=>zw(e,e=>I(()=>{let n=0;return V(e,e=>t(e,n++))}))),iT=/*#__PURE__*/ j(2,(e,t)=>aT(e,e=>F(t(e)))),aT=/*#__PURE__*/ j(2,(e,t)=>zw(e,e=>F(If(e,e=>B(t(e),Sd))))),oT=e=>e===void 0||e!==`unbounded`&&e<=1,sT=/*#__PURE__*/ j(e=>Iw(e[0]),(e,t,n)=>oT(n?.concurrency)?cT(e,t):lT(e,t,n)),cT=(e,t)=>Rw((n,r)=>{let i=0;return V(Hw(e)(n,r),B(e=>t(e,i++)))}),lT=(e,t,n)=>Vw(H(function*(r,i,a){let o=0,s=yield*Hw(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*XC(0);yield*Xd(a,ow(l));let u=om(yield*Ap()),d=rC(a);if(n.unordered){let e=jw(c),n=Pt(e.release(1)),r=Op({onFailure:e=>B(nw(l,e),n),onSuccess:e=>B(QC(l,e),n)});yield*e.take(1).pipe(B(()=>s),B(e=>{let n=o++;return d(u(r(Qf(()=>t(e,n))))),L}),Qp({disableYield:!0}),hp(t=>e.withPermits(c-1)(nw(l,t))),rm(a))}else{let e=yield*XC(c-2);yield*Xd(a,ow(e)),yield*dw(e).pipe(tie,B(e=>QC(l,e)),Qp({disableYield:!0}),hp(e=>nw(l,e)),rm(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,rw(l,e.cause))};yield*s.pipe(B(i=>{if(n)return tp(n);let a=o++,s=u(Qf(()=>t(i,a)));return d(s),s.addObserver(r),QC(e,eC(s))}),Qp({disableYield:!0}),hp(t=>QC(e,Od(t)).pipe(sp(nw(e,t)))),rm(a))}return dw(l)})),uT=/*#__PURE__*/ j(e=>Iw(e[0]),(e,t,n)=>oT(n?.concurrency)?dT(e,t):fT(e,t,n)),dT=(e,t)=>Rw((n,r)=>V(Hw(e)(n,r),e=>{let i,a,o=B(e,e=>(a??=Qd(r),Cm(Hw(t(e))(n,a),e=>(i=s(e),i)))),s=If(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=$d(a,Md);return a=void 0,B(t,()=>o)});return Qf(()=>i??o)})),fT=(e,t,n)=>e.pipe(rT(t),yT(n)),pT=e=>uT(e,M),mT=/*#__PURE__*/ j(2,(e,t)=>Rw((n,r)=>{let i=Qd(r);return V(Hw(e)(n,i),e=>{let a=e.pipe(hp(e=>{if(Lf(e))return tp(e);let o=i;return i=Qd(r),$d(o,Od(e)).pipe(sp(Hw(t(e))(n,i)),B(e=>(a=e,e)))}));return Qf(()=>a)})})),hT=/*#__PURE__*/ j(2,(e,t)=>mT(e,e=>$w(B(t(e),t=>tp(e))))),gT=/*#__PURE__*/ j(3,(e,t,n)=>mT(e,e=>{let r=t(e);return Ca(r)?Xw(r.failure):n(r.success,e)})),_T=/*#__PURE__*/ j(2,(e,t)=>gT(e,lre,e=>t(e))),vT=e=>_T(e,Zw),yT=/*#__PURE__*/ j(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>Vw(H(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:jw(s),l=yield*aC(!0),u=/* @__PURE__ */ new Set,d=yield*XC(t);yield*Xd(o,ow(d));let f=yield*Hw(e)(i,a);return yield*R(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*nm(f),yield*Ep(c.take(1),sp(eC(e),ep))));let t=e===void 0?yield*f:yield*eC(e),n=Qd(o),r=yield*Hw(t)(i,n);for(;u.size>=s;){let e=dte(u);u.delete(e),u.size===0&&(yield*l.open),yield*tC(e)}let a=yield*r.pipe(cp(()=>eie),B(e=>QC(d,e)),Qp({disableYield:!0}),Up(H(function*(e){let t=Bf(e),r=yield*up($d(n,t));if(!u.has(a))return;let i=gre([t,r]);Pd(i)&&(yield*nw(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),nm);l.closeUnsafe(),u.add(a)}}).pipe(hp(e=>{let t=zf(e);return wa(t)?l.whenOpen(nw(d,e)):nw(d,e)}),rm(o)),dw(d)}))),bT=/*#__PURE__*/ j(e=>Iw(e[0])&&Iw(e[1]),(e,t,n)=>Vw(H(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*XC(0);yield*Xd(a,ow(s));let c=0;function l(e,t){if(c++,!Lf(t))return nw(s,t);switch(o){case`both`:return c===2?nw(s,t):L;case`left`:case`right`:return e===o?nw(s,t):L;case`either`:return nw(s,t)}}let u=(e,t,n)=>Hw(t)(r,n).pipe(B(e=>e.pipe(B(e=>QC(s,e)),Qp)),Up(t=>Wp(Bf(t),e=>$d(n,e)).pipe(Op({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),rm(a));return yield*u(`left`,e,Qd(a)),yield*u(`right`,t,Qd(a)),dw(s)}))),xT=()=>Rw((e,t)=>I(()=>{let t=``,n=!1,r=Ai();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 Na(r)?r:null}let a=Qf(()=>r._tag===`Some`?Sd(r.value):Wre(e,{onSuccess:o,onFailure:tp,onDone:e=>{if(r=ji(e),t.length>0){let e=t;return t=``,n=!1,F([e])}return Sd(e)}}));function o(e){let t=i(e);return t===null?a:F(t)}return a})),ST=/*#__PURE__*/ j(2,(e,t)=>Rw((n,r)=>B(Hw(e)(n,r),e=>Hw(t)(e,r)))),CT=/*#__PURE__*/ j(2,(e,t)=>Rw((n,r)=>B(Hw(e)(n,r),e=>{let n=hp(e,e=>Lf(e)?tp(e):rp(xd(e)));return V(Hw(t)(n,r),e=>gp(e,e=>bd(e)?tp(e.value):rp(e)))}))),wT=e=>Rw((t,n)=>{let r;return F(Qf(()=>r||e.pipe(Jd(n),B(e=>Hw(e)(t,n)),B(e=>r=e))))}),TT=/*#__PURE__*/ j(2,(e,t)=>Vw((n,r,i)=>Yd(i,t).pipe(sp(Hw(e)(n,r))))),ET=/*#__PURE__*/ j(2,(e,t)=>TT(e,e=>t)),DT=(e,t,n)=>Qf(()=>{let r=qd(),i=Hw(e)(Sd(),r);return If(B(i,t),n||F).pipe(Gp(e=>$d(r,e)))}),OT=/*#__PURE__*/ j(2,(e,t)=>Rw((n,r)=>V(Np(Hw(e)(n,r),t),Np(t)))),kT=/*#__PURE__*/ j(2,(e,t)=>DT(e,e=>Qp(B(e,t),{disableYield:!0}))),AT=/*#__PURE__*/ j(3,(e,t,n)=>Qf(()=>{let r=t();return DT(e,e=>Jf({while:Ft,body:()=>e,step:e=>{r=n(r,e)}}),()=>F(r))})),jT=(e,t)=>Hw(e)(Sd(),t),MT=`~effect/PlatformError`;var NT=class extends (/*#__PURE__*/ Bo(`BadArgument`)){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:``}`}},PT=class extends zo{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor===void 0?``:` (${this.pathOrDescriptor})`}${this.description?`: ${this.description}`:``}`}},FT=class extends (/*#__PURE__*/ Bo(`PlatformError`)){constructor(e){`cause`in e?super({reason:e,cause:e.cause}):super({reason:e})}[MT]=MT;get message(){return this.reason.message}};const IT=e=>new FT(new PT(e)),LT=e=>new FT(new NT(e)),RT={_R:M,_E:M,_A:M},zT=function(e){this.channel=e};zT.prototype={"~effect/Stream":RT,pipe(){return jt(this,arguments)}};const BT=e=>new zT(e),VT=`~effect/Sink`,HT=/*#__PURE__*/ F([void 0]),UT={_A:M,_In:M,_L:M,_E:M,_R:M},WT={[VT]:UT,pipe(){return jt(this,arguments)}},GT=e=>N(e,VT),KT=e=>qT((t,n)=>Hw(e)(t,n).pipe(B(Qp({disableYield:!0})),If(F))),qT=e=>{let t=Object.create(WT);return t.transform=e,t},JT=e=>Rw((t,n)=>F(B(e.transform(t,n),Sd))),YT=/*#__PURE__*/ qT(e=>If(Qp(e,{disableYield:!0}),()=>HT)),XT=e=>ZT(qf(t=>e(t),{discard:!0})),ZT=e=>qT(t=>t.pipe(B(e),Qp({disableYield:!0}),If(()=>HT))),QT=e=>KT(wT(V(e,JT))),$T=`~effect/RcMap`,eE=e=>({[$T]:$T,lookup:e.lookup,context:e.context,scope:e.scope,idleTimeToLive:e.idleTimeToLive,capacity:e.capacity,state:{_tag:`Open`,map:Jre()},pipe(){return jt(this,arguments)}}),tE=e=>ap(t=>{let n=t.context,r=da(n,Kd),i=eE({lookup:e.lookup,context:n,scope:r,idleTimeToLive:typeof e.idleTimeToLive==`function`?Bt(e.idleTimeToLive,Ja):Pt(Ja(e.idleTimeToLive??oo)),capacity:Math.max(e.capacity??1/0,0)});return dp(Yd(r,()=>{if(i.state._tag===`Closed`)return L;let e=i.state.map;return i.state={_tag:`Closed`},qf(e,([,e])=>up(iE(e))).pipe(cp(()=>I(()=>{Qre(e)})))}),i)}),nE=/*#__PURE__*/ j(2,(e,t)=>Zp(n=>{if(e.state._tag===`Closed`)return qp;let r=e.state,i=nC(),a=Hf(r.map,t),o;if(a._tag===`Some`)o=a.value,o.refCount++;else if(Number.isFinite(e.capacity)&&$re(e.state.map)>=e.capacity)return z(new pre(`RcMap attempted to exceed capacity of ${e.capacity}`));else{o={deferred:Ld(),scope:qd(),idleTimeToLive:e.idleTimeToLive(t),finalizer:void 0,fiber:void 0,expiresAt:0,refCount:1},o.finalizer=aE(e,t,o),Xre(r.map,t,o);let n=new Map(e.context.mapUnsafe);i.context.mapUnsafe.forEach((e,t)=>{n.set(t,e)}),n.set(Kd.key,o.scope);let a=ta(n);Qf(()=>e.lookup(t)).pipe(om(a),rC(o.scope)).addObserver(n=>{hre(n)&&rE(e,t,o,a),Wd(o.deferred,n)})}let s=ua(i.context,Kd);return Xd(s,o.finalizer).pipe(sp(n(zd(o.deferred))))})),rE=(e,t,n,r)=>{if(e.state._tag===`Closed`)return;let i=Hf(e.state.map,t);i._tag!==`None`&&i.value===n&&(Wf(e.state.map,t),!(n.refCount>0)&&iE(n).pipe(om(r),rC(e.scope)))},iE=e=>e.fiber?tC(e.fiber).pipe(sp($d(e.scope,Md))):$d(e.scope,Md),aE=(e,t,n)=>ap(r=>{if(n.refCount--,n.refCount>0)return L;if(e.state._tag===`Closed`)return iE(n);let i=Hf(e.state.map,t);if(i._tag===`None`||i.value!==n)return iE(n);if(ro(n.idleTimeToLive))return Wf(e.state.map,t),iE(n);if(!no(n.idleTimeToLive))return L;let a=r.getRef(Tf);return n.expiresAt=a.currentTimeMillisUnsafe()+_o(n.idleTimeToLive),n.fiber||=Zp(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=Hf(e.state.map,t);return r._tag===`None`||r.value!==n?L:(Wf(e.state.map,t),$d(n.scope,Md))}return B(i(a.sleep(uo(s))),()=>r(i))}).pipe(Hp(I(()=>{n.fiber=void 0})),om(r.context),rC(e.scope)),L}),oE={_tag:`Empty`},sE={_tag:`Closed`},cE={_A:M,_E:M};var lE=class{"~effect/RcRef"=cE;pipe(){return jt(this,arguments)}state=oE;acquire;context;scope;idleTimeToLive;constructor(e,t,n,r){this.acquire=e,this.context=t,this.scope=n,this.idleTimeToLive=r}};const uE=e=>ap(t=>{let n=t.context,r=da(n,Kd),i=new lE(e.acquire,n,r,e.idleTimeToLive===void 0?void 0:Ja(e.idleTimeToLive));return dp(Yd(r,()=>{let e=i.state;return i.state=sE,e._tag===`Acquired`?$d(e.scope,Md):e._tag===`Acquiring`?tC(e.fiber):L}),i)}),dE=(e,t)=>{switch(e.state._tag){case`Closed`:return qp;case`Acquired`:{let t=e.state;return t.refCount++,t.fiber?dp(tC(t.fiber),t):F(t)}case`Acquiring`:{let n=e.state;return n.awaiters++,fE(e,n,t)}case`Empty`:{let n={_tag:`Acquiring`,fiber:void 0,awaiters:1,acquired:void 0};e.state=n;let r=qd(),i=Np(e.acquire,oa(e.context,Kd,r)).pipe(B(t=>{if(e.state!==n)return qp;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)}),Gp(t=>Nd(t)?L:(e.state===n&&(e.state=oE),$d(r,t))));return n.fiber=om(nC().context)(i),fE(e,n,t)}}},fE=(e,t,n)=>Gp(n(eC(t.fiber)),n=>{let r=t.acquired;return r===void 0?--t.awaiters>0||e.state!==t?L:(e.state=oE,tC(t.fiber)):Pd(n)?mE(e,r):L}),pE=e=>{let t=e;return Zp(e=>B(Rp,n=>B(dE(t,e),e=>dp(Yd(n,()=>mE(t,e)),e.value))))},mE=(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=oE),$d(t.scope,Md)):(no(n)&&(t.fiber=Zp(r=>B(r(Tp(n)),()=>e.state===t&&t.refCount===0?(e.state=oE,$d(t.scope,Md)):L)).pipe(Hp(I(()=>{t.fiber=void 0})),om(e.context),rC(e.scope))),L)},hE=uE,gE=pE,_E=e=>N(e,`~effect/Stream`),vE=BT,yE=e=>vE(Qw(V(e,Fa))),bE=e=>xE(I(()=>{let t=!0,n=F(Fa(void 0)),r=sie(n,e);return Qf(()=>t?(t=!1,n):r)})),xE=e=>vE(Bw(e)),SE=(e,t)=>vE(Rw((n,r)=>B(jT(e.channel,r),e=>t(e,r)))),CE=e=>e.channel,wE=(e,t)=>vE(Ww(e,t)),TE=/*#__PURE__*/ vE(Jw),EE=e=>vE(Gw(()=>e().channel)),DE=e=>vE(Yw(e)),OE=e=>Na(e)?vE(qw(e)):TE,kE=e=>vE(eT(e)),AE=e=>vE(tT(e)),jE=e=>vE(wT(V(e,CE))),ME=/*#__PURE__*/ j(2,(e,t)=>EE(()=>{let n=0;return vE(rT(e.channel,Ia(e=>t(e,n++))))})),NE=/*#__PURE__*/ j(2,(e,t)=>vE(sT(e.channel,t))),PE=/*#__PURE__*/ j(2,(e,t)=>{let n=vE(pT(Kw(()=>IE(e,t))));return FE.set(n,[e,t]),n}),FE=/*#__PURE__*/ new WeakMap;function*IE(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=FE.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}const LE=/*#__PURE__*/ j(e=>_E(e[0])&&_E(e[1]),(e,t,n)=>vE(bT(CE(e),CE(t),n))),RE=/*#__PURE__*/ j(2,(e,t)=>e.channel.pipe(mT(e=>t(e).channel),vE)),zE=/*#__PURE__*/ j(2,(e,t)=>e.channel.pipe(hT(t),vE)),BE=e=>vE(vT(e.channel)),VE=/*#__PURE__*/ j(2,(e,t)=>{let n=ya(t);return n===0?e:SE(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}))}),HE=/*#__PURE__*/ j(2,(e,t)=>SE(e,(e,n)=>I(()=>{let r,i,a=Qf(()=>{if(i!==void 0){let e=i;return i=void 0,F(e)}return e}).pipe(pp(e=>(r=kd(e),Sd()))),o=V(Qf(()=>t.transform(a,n)),([e,t])=>(i=t,Fa(e)));return Qf(()=>r||o)}))),UE=/*#__PURE__*/ j(2,(e,t)=>vE(CT(e.channel,t))),WE=/*#__PURE__*/ j(e=>_E(e[0]),(e,t)=>EE(()=>{let n=new TextDecoder(t?.encoding);return ME(e,e=>n.decode(e,{stream:!0}))})),GE=e=>EE(()=>{let t=new TextEncoder;return ME(e,e=>t.encode(e))}),KE=e=>e.channel.pipe(ST(xT()),vE),qE=/*#__PURE__*/ j(2,(e,t)=>vE(ET(e.channel,t))),JE=/*#__PURE__*/ j(2,(e,t)=>vE(OT(e.channel,t))),YE=/*#__PURE__*/ j(2,(e,t)=>pie(n=>jT(e.channel,n).pipe(B(e=>t.transform(e,n)),V(([e])=>e)))),XE=e=>AT(e.channel,()=>[],(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n]);return e}),ZE=/*#__PURE__*/ j(2,(e,t)=>kT(e.channel,e=>{let n=0;return Jf({while:()=>n<e.length,body:()=>t(e[n++]),step:Rt})})),QE=/*#__PURE__*/ j(2,(e,t)=>kT(e.channel,t)),$E=e=>AT(e.channel,()=>``,(e,t)=>e+t.join(``)),eD=/*#__PURE__*/ j(e=>_E(e[0]),(e,t,n)=>{let r,i,a=!1,o=iC(!1),s=n?.signal,c=()=>i.interruptUnsafe();return new ReadableStream({start(n){i=am(Np(QE(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(_d(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,sm(fp(tC(i)))}},n?.strategy)}),tD=/*#__PURE__*/ j(e=>_E(e[0]),(e,t)=>V(Ap(),n=>eD(e,n,t))),nD=`~effect/FileSystem`,rD=/*#__PURE__*/ P(`effect/FileSystem`),iD=e=>rD.of({...e,[nD]:nD,exists:t=>zt(e.access(t),dp(!0),mp(`PlatformError`,e=>e.reason._tag===`NotFound`?F(!1):z(e))),readFileString:(t,n)=>B(e.readFile(t),e=>ip({try:()=>new TextDecoder(n).decode(e),catch:e=>LT({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:sh(n.offset);i&&(yield*r.seek(i,`start`));let a=n?.bytesToRead===void 0?void 0:sh(n.bytesToRead),o=BigInt(0),s=Number(BigInt(n?.chunkSize??65536)),c=r.readAlloc(s);return xE(F(B(Qf(()=>a!==void 0&&a<=o?Sd():a!==void 0&&a-o<s?r.readAlloc(Number(a-o)):c),Pi({onNone:()=>Sd(),onSome:e=>(o+=BigInt(e.length),F(Fa(e)))}))))},jE),sink:(t,n)=>zt(e.open(t,{...n,flag:n?.flag??`w`}),V(e=>XT(t=>e.writeAll(t))),QT),writeFileString:(t,n,r)=>B(ip({try:()=>new TextEncoder().encode(n),catch:e=>LT({module:`FileSystem`,method:`writeFileString`,description:`could not encode string`,cause:e})}),n=>e.writeFile(t,n,r))}),aD=`~effect/FileSystem/File`;var oD=class extends (/*#__PURE__*/ P()(`effect/FileSystem/WatchBackend`)){};const sD=`~effect/Path`,cD=/*#__PURE__*/ P(`effect/Path`),lD=e=>cD.of({...e,[sD]:sD,resolveWithin(t,n){if(e.parse(n).root!==``)return Ai();let r=e.resolve(t),i=e.resolve(r,n),a=e.relative(r,i);return a===`..`||a.startsWith(`..${e.sep}`)||e.isAbsolute(a)?Ai():ji(i)}});function uD(e){return{_tag:`Value`,value:e}}function dD(e,t){return{_tag:`Record`,keys:e,value:t}}function fD(e,t){return{_tag:`Array`,length:e,value:t}}const pD=/*#__PURE__*/ _a(`effect/ConfigProvider`,{defaultValue:()=>xD()}),mD={...vr,toJSON(){return{_id:`ConfigProvider`}}},hD=e=>e;function gD(e,t){let n=Object.create(mD);return n.load=e,n.mapInput=t,n}function _D(e,t){return gD(n=>e(t(n)),n=>_D(e,e=>n(t(e))))}function vD(e){return _D(e,hD)}function yD(e,t){return e===``&&!t?void 0:e}function bD(e,t){let n=t?.preserveEmptyStrings===!0,r=SD(e);return vD(t=>F(CD(r,e,t,n)))}function xD(e){return bD(e?.env??{...globalThis.process?.env,...import.meta.env},{preserveEmptyStrings:e?.preserveEmptyStrings})}function SD(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 CD(e,t,n,r){let i=n.map(String).join(`_`),a=yD(Object.hasOwn(t,i)?t[i]:void 0,r),o=wD(e,n),s=o?.children?Object.keys(o.children):[];return s.length===0?a===void 0?void 0:uD(a):s.every(yte)?fD(Math.max(...s.map(e=>parseInt(e,10)))+1,a):dD(new Set(s),a)}function wD(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 TD=/*#__PURE__*/ ki(Yu),ED=`~effect/Config`;var DD=class{_tag=`ConfigError`;name=`ConfigError`;cause;constructor(e){this.cause=e}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}};const OD={.../*#__PURE__*/ ii({label:`Config`,evaluate(e){return this.parse(e.getRef(pD))}}),[ED]:ED,toJSON(){return{_id:`Config`}}};function kD(e){let t=Object.create(OD);return t.evaluator=e,t.parse=t=>Cm(e(t,[]),op),t}const AD=(e,t,n)=>e.evaluator(t,n),jD=/*#__PURE__*/ j(2,(e,t)=>kD((n,r)=>bm(AD(e,n,r),e=>Ca(e)?ba(t):e))),MD=e=>ln(e,`SourceError`),ND=()=>`<configuration>`,PD=e=>t=>hp(t,t=>tp(fd(t.reasons.map(e)))),FD=(e,t)=>e.load(t).pipe(PD(e=>dd(e)?hd(e.error).annotate(wd(e)):e),bm(n=>({provider:e,path:t,node:n,toString:ND}))),ID=(e,t)=>FD(e.provider,[...e.path,t]),LD=(e,t)=>Wy(Iv,e,new uv(iv(e=>t(e)),nv())),RD=e=>{switch(e._tag){case`Union`:return e.types.every(RD);case`Objects`:case`Arrays`:case`Suspend`:return!1;default:return!0}},zD=(e,t)=>{switch(e._tag){case`Objects`:return t?._tag===`Record`;case`Arrays`:return t?._tag===`Array`;case`Union`:return e.types.some(e=>zD(e,t));case`Suspend`:return zD(e.thunk(),t);default:return t?.value!==void 0}},BD=/*#__PURE__*/ Vt(e=>{let t=/* @__PURE__ */ new WeakSet,n=rae(e=>{switch(t.add(e),e._tag){case`Objects`:{let t=e.indexSignatures.map(e=>wb(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*ID(n,e);t.node!==void 0&&or(a,e,t)}return a});return LD(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*ID(e,n));return t});return LD(e.recur(n),t)}case`Union`:for(let t of e.types)n(t);if(!RD(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 LD(e,e=>F(e.node?.value))});return n(e)});function VD(e,t){let n=XS(e),r=Jy(n.ast),i=Tb(Ax(BD(n.ast))),a=typeof t==`string`?[t]:t??[];return kD((e,t)=>{let n=[...t,...a];return FD(e,n).pipe(Cm(e=>i(e).pipe(bm(ba),wm(t=>{let i=new DD(new yx(n.length>0?new x_(n,t):t));return zD(r,e.node)?z(i):F(xa(i))}))),PD(e=>ire(e)&&MD(e.defect)?md(new DD(e.defect)).annotate(wd(e)):e))})}const HD=/*#__PURE__*/ dS.check(/*#__PURE__*/ uS({minimum:1,maximum:65535})),UD=e=>Jt(e)||globalThis.Array.isArray(e);function WD(e){return VD(U,e)}function GD(e,t,n){let r=UD(t),i=r?n:t,a=G(e),o=i?.separator??`,`;return VD(K([U.pipe($x(XS(a),{decode:bie(i),encode:Z_(nv({strict:!1}),rv(e=>e.join(o)))})),a]),r?t:void 0)}function KD(e){return VD(zoe,e)}function qD(e){return VD(HD,e)}function JD(e){return VD(LS(U),e)}const YD=2**48-1,XD=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,ZD=(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)),YD),r=``;for(let e=45;e>=0;e-=5)r+=XD[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+=XD[i>>>a&31];i&=(1<<a)-1}return r},QD=e=>e.toString(16).padStart(2,`0`),$D=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,QD).join(``)).join(`-`),eO=()=>globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));function tO(e=eO()){return e[6]=e[6]&15|64,e[8]=e[8]&63|128,e}const nO=2**48-1;function rO(e,t=eO()){let n=Math.min(Math.max(0,Math.trunc(e)),nO);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 iO=`~effect/Crypto`,aO=/*#__PURE__*/ P(`effect/Crypto`),oO=e=>{let t=e.randomBytes,n=e=>V(sO(`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 aO.of({[iO]:iO,randomBytes:n,nextDoubleUnsafe:i,nextIntUnsafe:a,digest:e.digest,random:I(()=>i()),randomBoolean:I(()=>i()>.5),randomInt:I(()=>a()),randomBetween:(e,t)=>I(()=>Hre(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=tO(t(16));return e?.format===`bytes`?n:$D(n)}),randomUUIDv7:e=>fm(n=>{let r=rO(n.currentTimeMillisUnsafe(),t(16));return F(e?.format===`bytes`?r:$D(r))}),randomULID:fm(e=>F(ZD(e.currentTimeMillisUnsafe(),t(10))))})},sO=(e,t)=>Number.isSafeInteger(t)&&t>=0?F(t):z(LT({module:`Crypto`,method:e,description:`size must be a non-negative safe integer`})),cO=e=>ap(t=>(ud(t,e),L)),lO=`~effect/ErrorReporter/ignore`,uO=`~effect/Match/Matcher`,dO={[uO]:{_input:M,_filters:M,_remaining:M,_result:M,_return:M,_args:M},_tag:`TypeMatcher`,add(e){return fO(this.select,[...this.cases,e])},pipe(){return jt(this,arguments)}};function fO(e,t){let n=Object.create(dO);return n.select=e,n.cases=t,n}const pO={[uO]:{_input:M,_filters:M,_result:M,_return:M,_flavor:M},_tag:`ValueMatcher`,add(e){return wa(this.value)?this:e._tag===`When`&&e.guard(this.provided)===!0||e._tag===`Not`&&e.guard(this.provided)===!1?mO(this.provided,ba(e.evaluate(this.provided))):this},pipe(){return jt(this,arguments)}};function mO(e,t){let n=Object.create(pO);return n.provided=e,n.value=t,n}const hO=(e,t)=>({_tag:`When`,guard:e,evaluate:t}),gO=e=>{if(typeof e==`function`)return e;if(Array.isArray(e)){let t=e.map(gO),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,gO(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},_O=()=>fO(M,[]),vO=e=>mO(e,xa(e)),yO=(e,t)=>n=>n.add(hO(gO(e),t)),bO=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(hO(i,n))},xO=e=>t=>{let n=hO(n=>n!=null&&Object.hasOwn(t,n[e]),n=>t[n[e]](n));return e=>e.add(n)},SO=/*#__PURE__*/ bO(`_tag`),CO=/*#__PURE__*/ xO(`_tag`),wO=(...e)=>{let t=e.length;return n=>{for(let r=0;r<t;r++)if(n===e[r])return!0;return!1}},TO=e=>t=>{let n=EO(t);return Sa(n)?n._tag===`Success`?n.success:e(n.failure):(...t)=>{let r=n(...t);return wa(r)?r.success:e(r.failure,...t)}},EO=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?ba(t.evaluate(r,...n)):xa(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 ba(t.evaluate(r,...n))}return xa(r)}},DO=`effect/match/Match/exhaustive: absurd`,OO=e=>{let t=EO(e);if(Sa(t)){if(wa(t))return t.success;throw Error(DO)}return(...e)=>{let n=t(...e);if(wa(n))return n.success;throw Error(DO)}},kO=_O,AO=vO,jO=yO,MO=SO,NO=CO,PO=wO,FO=Jt,IO=Yt,LO=Xt,RO=TO,zO=OO,BO={"~effect/Ref":{_A:M},...vr,toJSON(){return{_id:`Ref`,ref:this.ref}}},VO=e=>{let t=Object.create(BO);return t.ref=cC(e),t},HO=e=>I(()=>VO(e)),UO=e=>I(()=>e.ref.current),WO=/*#__PURE__*/ j(2,(e,t)=>I(()=>lC(e.ref,t))),GO=/*#__PURE__*/ j(2,(e,t)=>e===void 0?void 0:t(e)),KO=`~effect/Stdio`,qO=/*#__PURE__*/ P(KO),JO=e=>({[KO]:KO,stdinIsTerminal:F(!1),stdoutIsTerminal:F(!1),stderrIsTerminal:F(!1),...e}),YO=`~effect/Terminal`,XO=`~effect/Terminal/QuitError`;var ZO=class extends (/*#__PURE__*/ KS(`QuitError`)({_tag:/*#__PURE__*/ tS(`QuitError`)})){[XO]=XO};const QO=/*#__PURE__*/ P(`effect/Terminal`),$O=e=>QO.of({...e,[YO]:YO}),ek=/*#__PURE__*/ $S(),tk=/*#__PURE__*/ $S(),nk=`~effect/process/ChildProcessSpawner/ChildProcessHandle`,rk={[nk]:nk,...er,toJSON(){return{_id:`ChildProcessHandle`,pid:this.pid}}},ik=e=>Object.setPrototypeOf({...e},rk),ak=e=>{let t=(t,n)=>e(t).pipe(V(e=>WE(n?.includeStderr===!0?e.all:e.stdout)),jE),n=(e,n)=>KE(t(e,n));return ok.of({spawn:e,exitCode:t=>zp(B(e(t),e=>e.exitCode)),streamString:t,streamLines:n,lines:(e,t)=>XE(n(e,t)),string:(e,n)=>$E(t(e,n))})};var ok=class extends (/*#__PURE__*/ P()(`effect/process/ChildProcessSpawner`)){};const sk=`~effect/process/ChildProcess`,ck={.../*#__PURE__*/ ii({label:`Command`,evaluate(e){return ua(e.context,ok).spawn(this)}}),[sk]:sk},lk=(e,t,n)=>Object.assign(Object.create(ck),{_tag:`StandardCommand`,command:e,args:t,options:n}),uk=function(...e){if(dk(e[0])){let[t,...n]=e,r=mk(t,n);return lk(r[0]??``,r.slice(1),{})}if(typeof e[0]==`object`&&!Array.isArray(e[0])&&!dk(e[0])){let t=e[0];return function(e,...n){let r=mk(e,n);return lk(r[0]??``,r.slice(1),t)}}if(typeof e[0]==`string`&&!Array.isArray(e[1])){let[t,n={}]=e;return lk(t,[],n)}let[t,n=[],r={}]=e;return lk(t,n,r)},dk=e=>Array.isArray(e)&&`raw`in e&&Array.isArray(e.raw),fk=e=>{let t=/^fd(\d+)$/.exec(e);if(t===null)return;let n=parseInt(t[1],10);return n>=3?n:void 0},pk=e=>`fd${e}`,mk=(e,t)=>{let n=[];for(let[r,i]of e.entries())n=hk(e,t,n,i,r);return n},hk=(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}=yk(r,a),l=bk(n,c,o);if(i===t.length)return l;let u=t[i],d=Array.isArray(u)?u.map(e=>gk(e)):[gk(u)];return bk(l,d,s)},gk=e=>typeof e==`string`?e:String(e),_k=/*#__PURE__*/ new Set([` `,` `,`\r`,`
|
|
21
|
+
`]),vk={x:3,u:5},yk=(e,t)=>{if(t.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let n=_k.has(t[0]),r=[],i=0;for(let n=0,a=0;n<e.length;n+=1,a+=1){let o=t[a];if(_k.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+=vk[e]??1}}let a=i===e.length;return a||r.push(e.slice(i)),{tokens:r,hasLeadingWhitespace:n,hasTrailingWhitespace:a}},bk=(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)],xk=(e,t,n)=>{let r=e.detached??n!==`win32`;return{...t,detached:r,shell:e.shell,windowsHide:e.windowsHide??!r}},Sk=(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 IT({_tag:i,module:e,method:t,pathOrDescriptor:r,syscall:n.syscall,cause:n})},Ck=e=>KT(iT(wk(e),e=>[e])),wk=e=>Rw(t=>{let n=e.evaluate();return F(Tk({...e,writable:n,pull:t}))}),Tk=e=>e.pull.pipe(B(t=>{let n=0;return $f(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)})})}),Qp({disableYield:!0}),e.endOnDone===!1?M:If(t=>`closed`in e.writable&&e.writable.closed?Sd(t):$f(n=>{let r=()=>n(Sd(t));return e.writable.once(`finish`,r),e.writable.end(),I(()=>{e.writable.off(`finish`,r)})})),Ep($f(t=>{let n=n=>t(z(e.onError(n)));return e.writable.once(`error`,n),I(()=>{e.writable.off(`error`,n)})}))),Ek=e=>vE(Dk(e)),Dk=e=>Rw((t,n)=>Mk({scope:n,readable:e.evaluate(),onError:e.onError??Nk,chunkSize:e.chunkSize,closeOnDone:e.closeOnDone})),Ok=e=>Rw((t,n)=>{let r=e.evaluate(),i=cC(void 0),a=iC(!1);return Tk({pull:t,writable:r,onError:e.onError??Nk,endOnDone:e.endOnDone,encoding:e.encoding}).pipe(hp(e=>(Lf(e)||(i.current=Od(e),a.openUnsafe()),L)),rm(n),B(()=>Mk({scope:n,exit:i,latch:a,readable:r,onError:e.onError??Nk,chunkSize:e.chunkSize})))}),kk=/*#__PURE__*/ j(2,(e,t)=>UE(e,Ok(t))),Ak=(e,t)=>{let n=Pk(t?.maxBytes),r=t?.onError??Nk;return $f(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()})})},jk=(e,t)=>V(Ak(e,t),e=>new Uint8Array(e)),Mk=e=>{let t=e.readable,n=e.closeOnDone??!0,r=e.exit??cC(void 0),i=e.latch??iC(!1);function a(){i.openUnsafe()}function o(t){r.current=kd(e.onError(t)),i.openUnsafe()}function s(){r.current=kd(xd()),i.openUnsafe()}t.on(`readable`,a),t.once(`error`,o),t.once(`end`,s);let c=Qf(function n(){let a=e.readable.read(e.chunkSize);if(a===null)return r.current?r.current:t.readableEnded?z(xd()):(i.closeUnsafe(),B(i.await,n));let o=Fa(a);for(;a=e.readable.read(e.chunkSize),a!==null;)o.push(a);return F(o)});return dp(Xd(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)},Nk=e=>new mre(e),Pk=e=>e===void 0||e===1/0?void 0:Number(sh(e)),Fk=e=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),Ik=(e,t,n)=>{let{commands:r}=Hk(n),i=r.reduce((e,t)=>{let n=`${t.command} ${t.args.join(` `)}`;return e.length===0?n:`${e} | ${n}`},``);return Sk(`ChildProcess`,e)(t,[i])},Lk=1e3,Rk=e=>{let t=()=>{};e.on(`error`,t),e.once(`close`,()=>e.off(`error`,t))},zk=(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}},Bk=(e,t=()=>{})=>{e.exitCode!==null||e.signalCode!==null?t(null):yt.execFile(`taskkill`,[`/pid`,String(e.pid),`/T`,`/F`],{windowsHide:!0},t)},Vk=/*#__PURE__*/ pf(ok,/* @__PURE__ */ R(function*(){let e=yield*rD,t=yield*cD,n=H(function*(n){if(!en(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=>_E(e)?`pipe`:e,a=e=>GT(e)?`pipe`:e,o=e=>{let t={stream:`pipe`,encoding:`utf-8`,endOnDone:!0};return en(e.stdin)?t:typeof e.stdin==`string`||_E(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 en(n)?{stream:`pipe`}:typeof n==`string`||GT(n)?{stream:n}:{stream:n.stream}},c=e=>{if(en(e.additionalFds))return[];let t=[];for(let[n,r]of Object.entries(e.additionalFds)){let e=fk(n);tn(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:()=>YT,getOutputFd:()=>TE};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=YT;n&&`write`in n&&(Rk(n),t=Ck({evaluate:()=>n,onError:t=>Ik(`fromWritable(fd${o})`,Fk(t),e)})),a.stream&&(yield*im(YE(a.stream,t))),r.set(o,t);break}case`output`:{let t=TE;if(n&&`read`in n){let r=new xt;n.on(`error`,e=>r.destroy(e)),n.pipe(r),t=Ek({evaluate:()=>r,onError:t=>Ik(`fromReadable(fd${o})`,Fk(t),e)})}a.sink&&(t=HE(t,a.sink)),i.set(o,t);break}}}return{getInputFd:e=>r.get(e)??YT,getOutputFd:e=>i.get(e)??TE}}),d=(e,t,n)=>Qf(()=>{let r=YT;return nn(t.stdin)&&(Rk(t.stdin),r=Ck({evaluate:()=>t.stdin,onError:t=>Ik(`fromWritable(stdin)`,Fk(t),e),endOnDone:n.endOnDone,encoding:n.encoding})),_E(n.stream)?dp(im(YE(n.stream,r)),r):F(r)}),f=(e,t,n,r)=>{let i=t.stdout?(()=>{let n=new xt;return t.stdout.on(`error`,e=>n.destroy(e)),t.stdout.pipe(n),Ek({evaluate:()=>n,onError:t=>Ik(`fromReadable(stdout)`,Fk(t),e)})})():TE,a=t.stderr?(()=>{let n=new xt;return t.stderr.on(`error`,e=>n.destroy(e)),t.stderr.pipe(n),Ek({evaluate:()=>n,onError:t=>Ik(`fromReadable(stderr)`,Fk(t),e)})})():TE;GT(n.stream)&&(i=HE(i,n.stream)),GT(r.stream)&&(a=HE(a,r.stream));let o=LE(i,a);return{stdout:i,stderr:a,all:o}},p=(e,t)=>$f(n=>{let r=Ld(),i=yt.spawn(e.command,e.args,t);return i.on(`error`,t=>{n(z(Ik(`spawn`,t,e)))}),i.on(`exit`,(...e)=>{Wd(r,Dd(e))}),i.on(`spawn`,()=>{n(F([i,r]))}),I(()=>{i.kill(`SIGTERM`)})}),m=(e,t,n)=>globalThis.process.platform===`win32`?$f(n=>{Bk(t,t=>{n(t?z(Ik(`kill`,Fk(t),e)):L)})}):ip({try:()=>{globalThis.process.kill(-t.pid,n)},catch:t=>Ik(`kill`,Fk(t),e)}),h=(e,t)=>{if(globalThis.process.platform===`win32`)Bk(e);else try{globalThis.process.kill(-e.pid,t)}catch{}},g=(e,t,n)=>Qf(()=>{if(!t.kill(n)){let t=new globalThis.Error(`Failed to kill child process`);return z(Ik(`kill`,t,e))}return L}),_=(e,t,n)=>$f(r=>{let i=Date.now()+n,a,o=()=>{clearTimeout(a),e.removeListener(`exit`,s)},s=()=>{clearTimeout(a),Date.now()>=i||!zk(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(pp(()=>g(e,t,n)));yield*i(r?.killSignal??`SIGTERM`),en(r?.forceKillAfter)?yield*_(t,n,Lk):(yield*_(t,n,_o(r.forceKillAfter)),zk(t,n)&&(yield*i(`SIGKILL`),yield*_(t,n,Lk))),yield*zd(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=fk(n);return tn(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*Bp(p(e,xk(e.options,{cwd:_,env:y,stdio:b},process.platform)),H(function*([t,n]){if(yield*Vd(n)){let[r]=yield*zd(n);(r!==0&&nn(r)||g&&process.platform!==`win32`&&e.options.detached!==!1)&&(yield*Sp(v(e,t,n,e.options)))}else g&&(yield*Sp(v(e,t,n,e.options)))})),ee=tk(x.pid);x.on(`exit`,t=>{t!==0&&nn(t)&&h(x,e.options.killSignal??`SIGTERM`)});let C=I(()=>{g||=(x.ref(),!0)}),te=I(()=>(g&&=(x.unref(),!1),C)),w=yield*d(e,x,t),{all:ne,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(zd(S),([t,n])=>{if(nn(t))return F(ek(t));let r=new globalThis.Error(`Process interrupted due to receipt of signal: '${n}'`);return z(Ik(`exitCode`,r,e))});return ik({pid:ee,exitCode:se,isRunning:oe,kill:t=>v(e,x,S,t),stdin:w,stdout:re,stderr:T,all:ne,getInputFd:ie,getOutputFd:ae,unref:te})}case`PipedCommand`:{let{commands:t,pipeOptions:n}=Hk(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=jE(F(y(a[a.length-1],r.from))),l=r.to??`stdin`;if(l===`stdin`)a.push(yield*b(uk(t.command,t.args,{...t.options,stdin:{...s,stream:c}})));else{let e=fk(l);if(tn(e)){let n=pk(e),r=t.options.additionalFds??{};a.push(yield*b(uk(t.command,t.args,{...t.options,additionalFds:{...r,[n]:{type:`input`,stream:c}}})))}else a.push(yield*b(uk(t.command,t.args,{...t.options,stdin:{...s,stream:c}})))}}let s=a[a.length-1],c=e=>qf([...a].reverse(),t=>Sp(t.kill(e)),{discard:!0}),l=R(function*(){let e=[];for(let t of a)e.push(yield*t.unref);return qf([...e].reverse(),e=>e,{discard:!0})});return ik({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 ak(b)})),Hk=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}},Uk=`~effect/http/HttpBody`,Wk=`~effect/http/HttpBody/HttpBodyError`;var Gk=class extends (/*#__PURE__*/ Bo(`HttpBodyError`)){[Wk]=Wk},Kk=class{[Uk];constructor(){this[Uk]=Uk}[Qn](){return this.toJSON()}toString(){return qn(this,{ignoreToString:!0})}};const qk=/*#__PURE__*/ new class extends Kk{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}};var Jk=class extends Kk{_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 Yk=(e,t)=>new Jk(e,t?.contentType,t?.contentLength);var Xk=class extends Kk{_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??=eA(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 Zk=(e,t)=>new Xk(e,t??`application/octet-stream`,e.length),Qk=/*#__PURE__*/ new TextEncoder,$k=globalThis.Buffer,eA=$k===void 0?e=>Qk.encode(e):e=>$k.from(e,`utf8`),tA=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),$k!==void 0)return new Xk(void 0,t??`text/plain`,$k.byteLength(e,`utf8`),e);let n=Qk.encode(e);return new Xk(n,t??`text/plain`,n.length,e)},nA=(e,t)=>tA(JSON.stringify(e),t??`application/json`),rA=(e,t)=>ip({try:()=>tA(JSON.stringify(e),t??`application/json`),catch:e=>new Gk({reason:{_tag:`JsonError`},cause:e})}),iA=(e,t)=>{let n=Eb(YS(e));return(e,r)=>n(e,t).pipe(vp(e=>new Gk({reason:{_tag:`SchemaError`,issue:e},cause:e})),B(e=>rA(e,r)))};var aA=class extends Kk{_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 oA=(e,t,n)=>new aA(e,t??`application/octet-stream`,n),sA=`~effect/http/HttpClientError`;var cA=class extends (/*#__PURE__*/ Bo(`HttpClientError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[sA]=sA;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 lA=e=>e.endsWith(`Error`)?e.slice(0,-5):e,uA=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,dA=e=>`${e.method} ${Hg(e.url)}`;var fA=class extends (/*#__PURE__*/ Bo(`TransportError`)){get methodAndUrl(){return dA(this.request)}get message(){return uA(lA(this._tag),this.description,this.methodAndUrl)}},pA=class extends (/*#__PURE__*/ Bo(`InvalidUrlError`)){get methodAndUrl(){return dA(this.request)}get message(){return uA(lA(this._tag),this.description,this.methodAndUrl)}},mA=class extends (/*#__PURE__*/ Bo(`StatusCodeError`)){get methodAndUrl(){return dA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return uA(lA(this._tag),this.description,e)}},hA=class extends (/*#__PURE__*/ Bo(`DecodeError`)){get methodAndUrl(){return dA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return uA(lA(this._tag),this.description,e)}},Xoe=class extends (/*#__PURE__*/ Bo(`EmptyBodyError`)){get methodAndUrl(){return dA(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return uA(lA(this._tag),this.description,e)}};const gA=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,Zoe=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],_A=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?xg(xg(e,`content-type`),`content-length`):(e=t.contentType===void 0?xg(e,`content-type`):vg(e,`content-type`,t.contentType),t.contentLength===void 0?xg(e,`content-length`):vg(e,`content-length`,t.contentLength.toString())),Qoe=e=>{if(e==null||!/^\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0};var $oe=class extends (/*#__PURE__*/ Bo(`UrlError`)){};const vA=(e,t,n)=>ote({try:()=>{let r=new URL(e,ese());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Eg(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new $oe({cause:e})}),ese=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname},yA=`~effect/http/HttpClientRequest`,tse={[yA]:yA,...er,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:Hg(this.url),urlParams:this.urlParams,hash:this.hash,headers:Un(this.headers),body:this.body.toJSON()}},pipe(){return jt(this,arguments)}};function bA(e,t,n,r,i,a){let o=Object.create(tse);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}const nse=/*#__PURE__*/ bA(`GET`,``,Ig,/*#__PURE__*/ Ai(),hg,qk),xA=e=>(t,n)=>ise(nse,{method:e,url:t,...n??void 0}),rse=/*#__PURE__*/ xA(`GET`),SA=/*#__PURE__*/ xA(`POST`),ise=/*#__PURE__*/ j(2,(e,t)=>{let n=e;return t.method&&(n=ase(n,t.method)),t.url&&(n=cse(n,t.url)),t.headers&&(n=CA(n,t.headers)),t.urlParams&&(n=lse(n,t.urlParams)),t.hash&&(n=use(n,t.hash)),t.body&&(n=TA(n,t.body)),t.accept&&(n=wA(n,t.accept)),t.acceptJson&&(n=sse(n)),n}),ase=/*#__PURE__*/ j(2,(e,t)=>bA(t,e.url,e.urlParams,e.hash,e.headers,e.body)),ose=/*#__PURE__*/ j(3,(e,t,n)=>bA(e.method,e.url,e.urlParams,e.hash,vg(e.headers,t,n),e.body)),CA=/*#__PURE__*/ j(2,(e,t)=>bA(e.method,e.url,e.urlParams,e.hash,yg(e.headers,t),e.body)),wA=/*#__PURE__*/ j(2,(e,t)=>ose(e,`Accept`,t)),sse=/*#__PURE__*/ wA(`application/json`),cse=/*#__PURE__*/ j(2,(e,t)=>{if(typeof t==`string`)return bA(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=jg(n.searchParams),i=Li(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,bA(e.method,n.toString(),r,i,e.headers,e.body)}),lse=/*#__PURE__*/ j(2,(e,t)=>bA(e.method,e.url,Lg(e.urlParams,t),e.hash,e.headers,e.body)),use=/*#__PURE__*/ j(2,(e,t)=>bA(e.method,e.url,e.urlParams,ji(t),e.headers,e.body)),TA=/*#__PURE__*/ j(2,(e,t)=>bA(e.method,e.url,e.urlParams,e.hash,_A(e.headers,t),t)),EA=/*#__PURE__*/ j(2,(e,t)=>TA(e,nA(t)));function dse(e){let t=vA(e.url,e.urlParams,zi(e.hash));return wa(t)?ji(t.success):Ai()}const DA=`~effect/http/HttpIncomingMessage`,OA=(e,t)=>{let n=wx(YS(e)),r=t?.reviver===void 0?void 0:wx(SS(YS(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))},kA=/*#__PURE__*/ _a(`effect/http/HttpIncomingMessage/MaxBodySize`,{defaultValue:()=>void 0}),AA=(e,t)=>{let n=e.headers[`content-type`]??``,r;if(n.includes(`application/json`))try{r=lm(e.json)}catch{}else if(n.includes(`text/`)||n.includes(`urlencoded`))try{r=lm(e.text)}catch{}let i={...t,headers:Un(e.headers),remoteAddress:e.remoteAddress};return r!==void 0&&(i.body=r),i},jA=`~effect/http/HttpClientResponse`,fse=(e,t)=>new pse(e,t);var pse=class extends tr{[DA];[jA];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[DA]=DA,this[jA]=jA}toJSON(){return AA(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=dse(this.request);return Mi(e)?``:(e.value.hash=``,e.value.href)}get headers(){return gg(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=Rh(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return Ai()}get stream(){return this.source.body?AE({evaluate:()=>this.source.body,onError:e=>new cA({reason:new hA({request:this.request,response:this,cause:e})})}):DE(new cA({reason:new Xoe({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return B(this.text,e=>ip({try:()=>e===``?null:JSON.parse(e),catch:e=>new cA({reason:new hA({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=>ip({try:()=>jg(new URLSearchParams(e)),catch:e=>new cA({reason:new hA({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Xf({try:()=>this.source.formData(),catch:e=>new cA({reason:new hA({request:this.request,response:this,cause:e})})}).pipe(Kp,lm)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Xf({try:()=>this.source.arrayBuffer(),catch:e=>new cA({reason:new hA({request:this.request,response:this,cause:e})})}).pipe(Kp,lm),this.arrayBufferBody}pipe(){return jt(this,arguments)}};const mse=e=>_g({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${Pi(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),hse=e=>{let t=bse(e);return Ni(t)||(t=gse(e),Ni(t))?t:_se(e)},gse=e=>{if(!(`b3`in e))return Ai();let t=e.b3.split(`-`);return t.length<2||NA(t[0],t[1])===!1?Ai():ji(Qo({traceId:t[0],spanId:t[1],sampled:!t[2]||t[2]===`1`||t[2]===`d`}))},_se=e=>!e[`x-b3-traceid`]||!e[`x-b3-spanid`]||NA(e[`x-b3-traceid`],e[`x-b3-spanid`])===!1?Ai():ji(Qo({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`})),vse=/^[0-9a-f]{32}$/i,MA=/^[0-9a-f]{16}$/i,yse=/^(?:[0-9a-f]{16}|[0-9a-f]{32})$/i,NA=(e,t)=>yse.test(e)&&MA.test(t),bse=e=>{if(!e.traceparent)return Ai();let t=e.traceparent.split(`-`);if(t.length!==4)return Ai();let[n,r,i,a]=t;switch(n){case`00`:return vse.test(r)===!1||MA.test(i)===!1||r===`00000000000000000000000000000000`||i===`0000000000000000`?Ai():ji(Qo({traceId:r,spanId:i,sampled:(parseInt(a,16)&1)==1}));default:return Ai()}},xse={"http:":80,"https:":443,"ws:":80,"wss:":443},PA=(e,t,n)=>{let r=Hg(t.search,n).slice(1);if(e.attribute(`url.full`,Hg(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===``?xse[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},Sse=(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()]},FA=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,wg(a,i)?`<redacted>`:n[a])},IA=`~effect/http/HttpClient`,LA=/*#__PURE__*/ P(`effect/HttpClient`),Cse=/*#__PURE__*/ j(2,(e,t)=>RA(B(n=>t(e.postprocess(F(n)),n)),e.preprocess)),wse=/*#__PURE__*/ j(2,(e,t)=>RA(n=>t(e.postprocess(n)),e.preprocess)),RA=(e,t)=>{let n=Object.create(Tse);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},Tse={[IA]:IA,pipe(){return jt(this,arguments)},...er,toJSON(){return{_id:`effect/HttpClient`}},.../*#__PURE__*/ Object.fromEntries(/*#__PURE__*/ Zoe.map(([e,t])=>[t,function(t,n){return this.execute(xA(e)(t,n))}]))},Ese=e=>RA(t=>B(t,t=>ap(n=>{let r=BA.get(t),i=r??new AbortController,a=vA(t.url,t.urlParams,zi(t.hash));if(Ca(a))return z(new cA({reason:new pA({request:t,cause:a.failure})}));let o=a.success;if(n.getRef($o)||n.getRef(kse)(t)){let a=e(t,o,i.signal,n);return r?a:Zp(e=>Op(e(a),{onSuccess(e){return zA.register(e,i),F(new VA(e,i))},onFailure(e){return yd(e)&&i.abort(),tp(e)}}))}return $p(n.getRef(Mse)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Tg);PA(a,o,Sse(t.urlParams,n.getRef(Xg)));let c=n.getRef(Ase);return FA(a,`request`,t.headers,c,s),t=n.getRef(jse)?CA(t,mse(a)):t,Zp(l=>l(e(t,o,i.signal,n)).pipe(tm(a,{captureStackTrace:!1}),Op({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),FA(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),Dse(n,a,t,e)),r?F(e):(zA.register(e,i),F(new VA(e,i)))),onFailure(e){return!r&&yd(e)&&i.abort(),tp(e)}})))})})),F),Dse=(e,t,n,r)=>{let i=nr();rr(0);let a;try{a=kd(new cA({reason:new mA({request:n,response:r})}))}finally{rr(i)}t.end(e.getRef(Sre)?e.getRef(Tf).currentTimeNanosUnsafe():BigInt(0),a)},Ose=e=>Cse(e,(e,t)=>{let n=new AbortController;return BA.set(t,n),sp(Vp(()=>I(()=>n.abort())),e)}),kse=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>It}),Ase=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>It}),jse=/*#__PURE__*/ _a(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:Ft}),Mse=/*#__PURE__*/ _a(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),Nse=e=>pf(LA)(jp(t=>V(e,e=>wse(e,Ip(e=>ha(t,e)))))),zA=/*#__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))}}})(),BA=/*#__PURE__*/ new WeakMap;var VA=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[jA]=jA;[DA]=DA;applyInterrupt(e){return Qf(()=>(zA.unregister(this.original),Yp(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 EE(()=>(zA.unregister(this.original),qE(this.original.stream,I(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Qn](){return this.original[Qn]()}pipe(){return jt(this,arguments)}};const HA=/\+/g,UA=function(){};UA.prototype=/*#__PURE__*/ Object.create(null);function WA(e){let t=new UA;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(HA,` `)),s)try{r=decodeURIComponent(r)||r}catch{}if(d&&(i=e.slice(o+1,p),u&&(i=i.replace(HA,` `)),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 Pse=/^https?:\/\/.*?\//,GA=/(\/:[^/()]*?)\?(\/?)/,Fse=[],Ise=/^[^:*(]*\/:[^/:*(.-]+$/,Lse=e=>Ise.test(e),Rse=(e={})=>new zse(e);var zse=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(GA);if(r&&r.index!==void 0){Use(t.length===r.index+r[0].length,`Optional Parameter needs to be the last parameter of the path`);let i=t.replace(GA,`$1$2`),a=t.replace(GA,`$2`)||`/`;this.on(e,i,n),this.on(e,a,n);return}this.options.ignoreDuplicateSlashes&&(t=YA(t)),this.options.ignoreTrailingSlash&&(t=XA(t));let i=typeof e==`string`?[e]:e;for(let e of i)this._on(e,t,n)}all(e,t){this.on(Jse,e,t)}_on(e,t,n){this.trees[e]===void 0&&(this.trees[e]=new JA(`/`));let r=t;if(r===`*`&&this.trees[e].prefix.length!==0){let t=this.trees[e];this.trees[e]=new JA(``),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=ZA(r,d),t=r.slice(d,e+1);c.push(Gse(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=Kse(_))),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(Lse(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(Pse,`/`));let e;try{e=qse(t),t=e.path,r=e.querystring,i=e.shouldDecodeParam}catch{return}this.options.ignoreDuplicateSlashes&&(t=YA(t)),this.options.ignoreTrailingSlash&&(t=XA(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(Fse),searchParams:WA(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=$A(t)),t.length<=s)return this.singleParamArray[0]=t,{handler:n.handler,params:n.createParams(this.singleParamArray),searchParams:WA(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:WA(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=$A(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=$A(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}}}},Bse=class{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:Wse(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}},KA=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 Bse),this.isLeafNode=!0,this.handlerStorage.add(e)}},qA=class extends KA{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 JA(e),this.staticChildren[n]}},JA=class e extends qA{_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 Vse(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 Hse),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}},Vse=class extends qA{_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)}},Hse=class extends KA{_tag=`WildcardNode`;getNextNode(e,t,n,r){}};const Use=(e,t)=>{if(!e)throw Error(t)};function YA(e){return e.indexOf(`//`)===-1?e:e.replace(/\/\/+/g,`/`)}function XA(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function Wse(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 ZA(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 Gse(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 Kse(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function QA(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 qse(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);QA(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 $A(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=QA(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 Jse=/* @__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(`.`),ej=Rse,tj=e=>{switch(e._tag){case`Weak`:return`W/"${e.value}"`;case`Strong`:return`"${e.value}"`}};var nj=class extends (/*#__PURE__*/ P()(`effect/http/Etag/Generator`)){};const rj=e=>{let t=Pi(e.mtime,{onNone:()=>`0`,onSome:e=>e.getTime().toString(16)});return`${e.size.toString(16)}-${t}`},ij=e=>`${e.size.toString(16)}-${e.lastModified.toString(16)}`,Yse=/*#__PURE__*/ uf(nj)({fromFileInfo(e){return I(()=>({_tag:`Strong`,value:rj(e)}))},fromFileWeb(e){return I(()=>({_tag:`Strong`,value:ij(e)}))}}),Xse=/*#__PURE__*/ uf(nj)({fromFileInfo(e){return I(()=>({_tag:`Weak`,value:rj(e)}))},fromFileWeb(e){return I(()=>({_tag:`Weak`,value:ij(e)}))}}),Zse=/*#__PURE__*/ Object.getPrototypeOf(hg),Qse=()=>Object.create(Zse),aj=`~effect/http/HttpServerResponse`,oj=e=>N(e,aj),sj=e=>Sj({status:e?.status??204,statusText:e?.statusText,headers:e?.headers?gg(e.headers):void 0,cookies:e?.cookies}),cj=(e,t)=>{let n=_g({location:e.toString()});return Sj({status:t?.status??302,statusText:t?.statusText,headers:t?.headers?bg(n,gg(t.headers)):n,cookies:t?.cookies??Bh})},lj=(e,t)=>{let n=t?.headers?gg(t.headers):hg;return Sj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??Bh,body:Zk(e,uj(t,n))})},uj=(e,t)=>{if(e?.contentType)return e.contentType;if(e?.headers)return t[`content-type`]},dj=(e,t)=>{let n=t?.headers?gg(t.headers):hg;return Sj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies??Bh,body:tA(e,uj(t,n))})},$se=(e,t)=>{let n=iA(e,t);return(e,t)=>{let r=t?.headers?gg(t.headers):hg;return V(n(e,uj(t,r)),e=>Sj({status:t?.status??200,statusText:t?.statusText,headers:r,cookies:t?.cookies,body:e}))}},fj=(e,t)=>{let n=t?.headers?gg(t.headers):hg;return Sj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:nA(e,uj(t,n))})},ece=(e,t)=>{let n=t?.headers?gg(t.headers):hg;return Sj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:tA(Rg(jg(e)),uj(t,n)??`application/x-www-form-urlencoded`)})},pj=(e,t)=>Sj({status:t?.status??200,statusText:t?.statusText,headers:t?.headers&&gg(t.headers),cookies:t?.cookies,body:Yk(e,{contentType:t?.contentType,contentLength:t?.contentLength})}),mj=(e,t)=>{let n=t?.headers?gg(t.headers):hg;return Sj({status:t?.status??200,statusText:t?.statusText,headers:n,cookies:t?.cookies,body:oA(e,uj(t,n),t?.contentLength)})},hj=/*#__PURE__*/ j(3,(e,t,n)=>Sj(e,vg(e.headers,t,n))),gj=/*#__PURE__*/ j(2,(e,t)=>Sj({...e,headers:xg(e.headers,t)})),_j=/*#__PURE__*/ j(2,(e,t)=>Sj(e,yg(e.headers,t))),vj=/*#__PURE__*/ j(e=>oj(e[0]),(e,t,n,r)=>V(op(Xh(e.cookies,t,n,r)),t=>Sj({...e,cookies:t}))),yj=/*#__PURE__*/ j(2,(e,t)=>Sj({...e,cookies:Yh(e.cookies,t)})),bj=/*#__PURE__*/ j(2,(e,t)=>Sj({...e,body:t},_A(e.headers,t))),tce=/*#__PURE__*/ j(e=>oj(e[0]),(e,t,n)=>Sj({...e,status:t,statusText:n??e.statusText})),nce=(e,t=!1)=>t||e.status===204||e.status===205||e.status===304,xj=(e,t)=>{for(let[n,r]of t)n===`set-cookie`?e.append(n,r):e.set(n,r);return e},rce=(e,t)=>{let n=new globalThis.Headers(e.headers);if(!Vh(e.cookies)){let t=eg(e.cookies);for(let e of t)n.append(`set-cookie`,e)}let r=e.body,i=nce(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 xj(e.headers,n),e}let o=i?e:t;return new Response(void 0,{status:o.status,statusText:o.statusText,headers:xj(new globalThis.Headers(t.headers),n)})}if(a)return r._tag===`Raw`&&ice(r.body)&&r.body.cancel().catch(Rt),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(eD(r.stream,t?.context??ia(),{signal:t?.signal}),{status:e.status,statusText:e.statusText,headers:n})}},ice=e=>typeof ReadableStream<`u`&&e instanceof ReadableStream,ace={...vr,[aj]:aj,[lO]:!0,toJSON(){return{_id:`HttpServerResponse`,status:this.status,statusText:this.statusText,headers:Un(this.headers),cookies:this.cookies.toJSON(),body:this.body.toJSON()}}},Sj=(e,t)=>{let n=Object.create(ace);if(n.status=e.status,n.statusText=e.statusText,n.cookies=e.cookies??Bh,n.body=e.body??qk,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===hg?Qse():_g({...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??hg;return n},oce=e=>{let t=new globalThis.Headers(e.headers),n=t.getSetCookie();t.delete(`set-cookie`);let r=sj({status:e.status,statusText:e.statusText,headers:t,cookies:Rh(n)});if(e.body){let t=e.headers.get(`content-type`);r=bj(r,oA(AE({evaluate:()=>e.body,onError:e=>e}),t??void 0,Qoe(e.headers.get(`content-length`))))}return r},sce=(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}`},cce=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:sce(e.headers,`Accept-Encoding`)},i=e.headers.etag;return i!==void 0&&!i.startsWith(`W/`)&&(r.etag=`W/${i}`),_j(e,r)})}}),Cj={"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(Cj);let wj;const lce=()=>{if(wj!==void 0)return wj;let e=/* @__PURE__ */ new Map,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let[r,i]of Object.entries(Cj)){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 wj={extensionToType:e,typeToExtension:t,typeToExtensions:n},wj},Tj=e=>{if(typeof e!=`string`)return Ai();let t=e.replace(/^.*[/\\]/s,``).toLowerCase(),n=t.replace(/^.*\./s,``).toLowerCase(),r=t.length<e.length;return!(n.length<t.length-1)&&r?Ai():Ri(lce().extensionToType.get(n))};var Ej=class extends (/*#__PURE__*/ P()(`effect/http/HttpPlatform`)){};const uce=/*#__PURE__*/ H(function*(e){let t=yield*rD,n=yield*nj;return Ej.of({platform:e.platform,compression:cce(e.compression),fileResponse:H(function*(r,i){let a=yield*t.stat(r),o=yield*n.fromFileInfo(a),s=i?.offset===void 0?nh:yield*Oj(i.offset,`offset`),c=s>a.size?a.size:s,l=a.size-c,u=i?.bytesToRead===void 0?void 0:yield*Oj(i.bytesToRead,`bytesToRead`),d=u===void 0||u>l?l:u,f=u===void 0?void 0:c+d,p=yield*kj(c,`offset`),m=f===void 0?void 0:yield*kj(f,`end`),h=vg(Dj(i),`etag`,tj(o));return Ni(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=bg(Dj(r),_g({etag:tj(n),"last-modified":new Date(t.lastModified).toUTCString()}));return e.fileWebResponse(t,r?.status??200,r?.statusText,i,r)})}})}),Dj=e=>{let t=e?.headers?gg(e.headers):hg;return e?.contentType?vg(t,`content-type`,e.contentType):t},Oj=(e,t)=>{let n=ch(e);return Ni(n)?F(n.value):z(LT({module:`HttpPlatform`,method:`fileResponse`,description:`Invalid ${t}: ${e}`}))},kj=(e,t)=>{let n=Number(e);return Number.isSafeInteger(n)?F(n):z(LT({module:`HttpPlatform`,method:`fileResponse`,description:`${t} exceeds the safe integer range: ${e}`}))},Aj=`~effect/http/HttpServerRespondable`,jj=e=>N(e,Aj),dce=/*#__PURE__*/ sj({status:400}),fce=/*#__PURE__*/ sj({status:404}),pce=(e,t)=>oj(e)?F(e):jj(e)?hp(e[Aj](),()=>F(t)):hx(e)?F(dce):fre(e)?F(fce):F(t),mce=(e,t)=>oj(e)?F(e):jj(e)?hp(e[Aj](),()=>F(t)):F(t),Mj=`~effect/http/HttpServerError`;var Nj=class extends (/*#__PURE__*/ Bo(`HttpServerError`)){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[Mj]=Mj;stack=`${this.name}: ${this.message}`;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}[Aj](){return this.reason[Aj]()}get[lO](){return this.reason[`~effect/ErrorReporter/ignore`]??!1}get message(){return this.reason.message}},Pj=class extends (/*#__PURE__*/ Bo(`RequestParseError`)){[Aj](){return F(sj({status:400}))}get methodAndUrl(){return Lj(this.request)}get message(){return Rj(this._tag,this.description,this.methodAndUrl)}},hce=class extends (/*#__PURE__*/ Bo(`RouteNotFound`)){[Aj](){return F(sj({status:404}))}[lO]=!0;get methodAndUrl(){return Lj(this.request)}get message(){return Rj(this._tag,this.description,this.methodAndUrl)}};const gce=e=>N(e,Mj);var Fj=class extends (/*#__PURE__*/ Bo(`ResponseError`)){[Aj](){return F(sj({status:500}))}get methodAndUrl(){return Lj(this.request)}get message(){let e=`${this._tag} (${this.response.status} ${this.methodAndUrl})`;return this.description?`${e}: ${this.description}`:e}},Ij=class extends (/*#__PURE__*/ P()(`effect/http/HttpServerError/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ oa(Td,{name:`ClientAbort`,stack:Lt,parent:void 0}))};const Lj=e=>`${e.method} ${Hg(e.url)}`,Rj=(e,t,n)=>{let r=`${e} (${n})`;return t?`${r}: ${t}`:r},zj=e=>{let t,n=vce,r=[],i=[],a=!1;for(let o=0;o<e.reasons.length;o++){let s=e.reasons[o];switch(s._tag){case`Fail`:n=pce(s.error,Bj),r.push(s);break;case`Die`:oj(s.defect)?t=s.defect:(n=mce(s.defect,Bj),r.push(s));break;case`Interrupt`:if(a=s.annotations.has(Ij.key),r.length>0)break;i.push(s)}}return t?F([t,fd(r)]):(i.length>0&&r.length===0&&(r.push(...i),n=a?yce:bce),bm(n,e=>(r.push(hd(e)),[e,fd(r)])))},_ce=e=>{let t,n=e.reasons.filter(e=>e._tag===`Die`&&oj(e.defect)?(t=e.defect,!1):!0);return[t??Bj,n.length>0?ji(fd(n)):Ai()]},Bj=/*#__PURE__*/ sj({status:500}),vce=/*#__PURE__*/ F(Bj),yce=/*#__PURE__*/ F(/*#__PURE__*/ sj({status:499})),bce=/*#__PURE__*/ F(/*#__PURE__*/ sj({status:503})),Vj=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,Hj=/\\([\v\u0020-\u{10ffff}])/gu,xce=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,Sce=/^[!#$%&'*+.^\w|~-]+$/u,Uj={value:``,parameters:/*#__PURE__*/ Object.create(null)};function Wj(e,t=!1){if(typeof e!=`string`)return Uj;let n=e.indexOf(`;`),r=n===-1?e.trim():e.slice(0,n).trim();if((t?Sce:xce).test(r)===!1)return Uj;let i={value:r.toLowerCase(),parameters:Object.create(null)};if(n===-1)return i;let a,o,s;for(Vj.lastIndex=n;o=Vj.exec(e);){if(o.index!==n)return Uj;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:Uj}const Gj=16384,Kj={key:0,whitespace:1,value:2},qj={_tag:`Continue`},Jj=/*#__PURE__*/ new Uint8Array(256);for(let e of"!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")Jj[/*#__PURE__*/ e.charCodeAt(0)]=1;const Yj=/*#__PURE__*/ new Uint8Array(256);Yj[9]=1;for(let e=32;e<=126;e++)Yj[e]=1;for(let e=128;e<=255;e++)Yj[e]=1;function Cce(){let e=new TextDecoder,t={state:Kj.key,headers:Object.create(null),key:``,value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function n(e){return t.state=Kj.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===Kj.key){let n=o;for(;n<l;n++){if(t.size++>Gj)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=Kj.value,t.size++):a[n+1]!==32&&a[n+1]!==9?(o=n+1,t.state=Kj.value):(o=n+1,t.state=Kj.whitespace);break}if(Jj[a[n]]!==1)return i(`InvalidHeaderName`)}if(n===l)return t.key+=e.decode(a.subarray(o,l)).toLowerCase(),qj}if(t.state===Kj.whitespace){for(;o<l;o++){if(t.size++>Gj)return i(`HeaderTooLarge`);if(a[o]!==32&&a[o]!==9){t.state=Kj.value;break}}if(o===l)return qj}if(t.state===Kj.value){let u=o;for(c!==void 0&&(u=c,c=void 0);u<l;u++){if(t.size++>Gj)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),qj;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=Kj.key;continue outer}}else if(Yj[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)),qj}}return o>l&&(t.size+=l-o),qj}}function wce(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 Tce(e,t,n,r){let i=wce(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 Xj={headers:0,body:1},Ece={_tag:`InvalidDisposition`},Dce={_tag:`EndNotReached`},Oce={_tag:`ReachedLimit`,limit:`MaxParts`},kce={_tag:`ReachedLimit`,limit:`MaxTotalSize`},Ace={_tag:`ReachedLimit`,limit:`MaxPartSize`},Zj={_tag:`ReachedLimit`,limit:`MaxFieldSize`},jce=/*#__PURE__*/ new TextEncoder().encode(`\r
|
|
23
|
+
`);function Qj(e){return e.filename!==void 0||e.contentType===`application/octet-stream`}function Mce(e){return Wj(e[`content-type`]).parameters.boundary}function $j(e){}const eM=e=>e===1/0?1/0:Number(sh(e));function Nce({headers:e,onFile:t,onField:n,onError:r,onDone:i,isFile:a=Qj,maxParts:o=1/0,maxTotalSize:s=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=eM(s),d=eM(c),f=eM(l),p=Mce(e);if(p===void 0)return r({_tag:`InvalidBoundary`}),{write:$j,end(){}};let m={state:Xj.headers,index:0,parts:0,onChunk:$j,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0,done:!1,stopped:!1};function h(){m.state=Xj.body,m.isFile=!0,m.onChunk=$j}function g(e){m.stopped=!0,m.state===Xj.body&&m.isFile&&m.onChunk(null),r(e)}let _=Cce(),v=Tce(`\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=Xj.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(Oce)}if((m.partSize+=s.length)>d)return g(Ace);if(m.state===Xj.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=Wj(e.headers[`content-type`]),i=Wj(e.headers[`content-disposition`],!0);if(i.value===`form-data`&&!(`name`in i.parameters))return h(),r(Ece);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=Xj.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(Zj);m.fieldChunks.push(t)}}}else if(m.isFile)m.onChunk(s);else{if((m.fieldSize+=s.length)>f)return g(Zj);m.fieldChunks.push(s)}}}},jce,2);return{write(e){if(!m.stopped)return(m.totalSize+=e.length)>u?g(kce):v.write(e)},end(){v.end(),!m.done&&!m.stopped&&g(Dce),m.state=Xj.headers,m.index=0,m.parts=0,m.onChunk=$j,m.info=void 0,m.totalSize=0,m.partSize=0,m.fieldChunks=[],m.fieldSize=0,m.done=!1,m.stopped=!1}}}const tM=/*#__PURE__*/ new TextDecoder(`utf-8`);function Pce(e){if(e===`utf-8`||e===`utf8`||e===``)return tM;try{return new TextDecoder(e)}catch{return tM}}function Fce(e,t){return Pce(e.contentTypeParameters.charset??`utf-8`).decode(t)}const Ice=Nce,Lce=Qj,Rce=Fce,nM=`~effect/http/Multipart`,rM=`~effect/http/Multipart/MultipartError`,zce=e=>Hce(e)?e:iM.fromReason(`InternalError`,e);var Bce=class extends zo{};const Vce={FileTooLarge:413,FieldTooLarge:413,BodyTooLarge:413,TooManyParts:413,InternalError:500,Parse:400};var iM=class e extends (/*#__PURE__*/ Bo(`MultipartError`)){static fromReason(t,n){return new e({reason:new Bce({_tag:t,cause:n})})}[rM]=rM;[lO]=!0;[Aj](){return F(sj({status:Vce[this.reason._tag]}))}get message(){return this.reason._tag}};const Hce=e=>N(e,rM),Uce=e=>ap(t=>{let n=da(t.context,lM);return F({headers:e,maxParts:t.getRef(oM),maxFieldSize:t.getRef(sM),maxPartSize:t.getRef(cM),maxTotalSize:t.getRef(kA),isFile:n.length===0?void 0:e=>!n.some(t=>e.contentType.includes(t))&&Lce(e)})});var Wce=class extends tr{[nM];constructor(){super(),this[nM]=nM}};const Gce=(e,t)=>B(rD,n=>vp(YE(t.content,n.sink(e)),zce)),Kce=/*#__PURE__*/ new TextEncoder,qce=e=>{let t=Array.from(e),n=``,r=0;for(let e=t.length-1;e>=0&&(r+=Kce.encode(t[e]).length,!(r>128));e--)n=t[e]+n;return n===``||n===`.`||n===`..`?`file`:n},Jce=(e,t=Gce)=>R(function*(){let n=yield*rD,r=yield*cD,i=yield*n.makeTempDirectoryScoped(),a=Object.create(null),o=/* @__PURE__ */ new Set,s=0;return yield*ZE(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=qce(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 Yce(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(mp(`PlatformError`,e=>z(iM.fromReason(`InternalError`,e))));var Yce=class extends Wce{_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 aM=e=>{let t=/* @__PURE__ */ new Map;return e.maxParts!==void 0&&t.set(oM.key,e.maxParts),e.maxFieldSize!==void 0&&t.set(sM.key,sh(e.maxFieldSize)),e.maxFileSize!==void 0&&t.set(cM.key,sh(e.maxFileSize)),e.maxTotalSize!==void 0&&t.set(kA.key,sh(e.maxTotalSize)),e.fieldMimeTypes!==void 0&&t.set(lM.key,e.fieldMimeTypes),ta(t)},oM=/*#__PURE__*/ _a(`effect/http/Multipart/MaxParts`,{defaultValue:()=>void 0}),sM=/*#__PURE__*/ _a(`effect/http/Multipart/MaxFieldSize`,{defaultValue:/*#__PURE__*/ Pt(/*#__PURE__*/ uh(10))}),cM=/*#__PURE__*/ _a(`effect/http/Multipart/MaxFileSize`,{defaultValue:()=>void 0}),lM=/*#__PURE__*/ _a(`effect/http/Multipart/FieldMimeTypes`,{defaultValue:/*#__PURE__*/ Pt([`application/json`])}),uM=`~effect/http/HttpServerRequest`,dM=/*#__PURE__*/ P(`effect/http/HttpServerRequest`);var fM=class extends (/*#__PURE__*/ P()(`effect/http/ParsedSearchParams`)){};const Xce=(e,t)=>{let n=Cx(e);return B(dM,e=>n(e.cookies,t))},Zce=(e,t)=>{let n=Cx(e);return B(dM,e=>n(e.headers,t))},Qce=(e,t)=>{let n=Cx(e);return B(fM,e=>n(e,t))},$ce=e=>{let t=e.headers.host??`localhost`,n=e.headers[`x-forwarded-proto`]===`https`?`https`:`http`;try{return ji(new URL(e.url,`${n}://${t}`))}catch{return Ai()}},pM=/*#__PURE__*/ new WeakMap,ele=(e,t)=>{let n=pM.get(e.source),r=n?(e,r)=>B(n(e,r),n=>t(e,n)):t;pM.set(e.source,r)},tle=e=>e,nle=/*#__PURE__*/ new WeakSet,rle=e=>ap(t=>{let n=ua(t.context,dM);return nle.add(n.source),e}),ile=/*#__PURE__*/ _a(`effect/http/HttpMiddleware/TracerDisabledWhen`,{defaultValue:()=>It}),ale=/*#__PURE__*/ _a(`@effect/platform/HttpMiddleware/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),ole=/*#__PURE__*/ _a(`effect/http/HttpMiddleware/TracerHeaderFilter`,{defaultValue:()=>It}),mM=(e,t)=>!e.cache.tracerEnabled||e.getRef(ile)(t),hM=(e,t)=>{if(!(t.status>=500&&t.status<600))return Dd(t);let n=nr();rr(0);try{return kd(new Nj({reason:new Fj({request:e,response:t})}))}finally{rr(n)}},gM=/*#__PURE__*/ tle(e=>ap(t=>{let n=ua(t.context,dM);if(mM(t,n))return e;let r=t.getRef(ale),i=bu(t,r(n),{parent:zi(hse(n.headers)),kind:`server`}),a=t.context;return t.setContext(oa(t.context,Xo,i)),Sl(t,e=>{t.setContext(a);let r=t.getRef(Tf).currentTimeNanosUnsafe();if(Nd(e)&&(!i.sampled||t.getRef(rs)===is)){i.end(r,hM(n,e.value));return}let o=t.getRef(Tg),s=t.getRef(ole),c,l;if(Pd(e)){let[t,r]=_ce(e.cause);c=t,l=Ni(r)&&(c.status>=500||yd(r.value))?Od(r.value):hM(n,c)}else c=e.value,l=hM(n,c);if(i.sampled){i.attribute(`http.request.method`,n.method);let e=$ce(n);Ni(e)&&PA(i,e.value,t.getRef(Xg)),n.headers[`user-agent`]!==void 0&&i.attribute(`user_agent.original`,n.headers[`user-agent`]),FA(i,`request`,n.headers,s,o),Ni(n.remoteAddress)&&i.attribute(`client.address`,n.remoteAddress.value),i.attribute(`http.response.status_code`,c.status),FA(i,`response`,c.headers,s,o)}i.end(r,l)}),e})),sle=(e,t,n)=>{let r=(e,n)=>{e.cause=n;let r=e.request;return Cm(zj(n),([e,n])=>{let i=nC();ud(i,n);let a=pM.get(r.source),o=n.reasons.length===0?F(e):tp(n);return a===void 0?(r[_M]=!0,Cm(t(r,e),()=>o)):Cm(Cm(a(r,e),e=>(r[_M]=!0,t(r,e))),()=>o)})},i=(e,n)=>{let r=pM.get(e.source);return r===void 0?(e[_M]=!0,bm(t(e,n),e=>oj(e)?e:n)):Cm(r(e,n),r=>(e[_M]=!0,bm(t(e,r),e=>oj(e)?e:n)))},a=a=>{let o=a.request,s=Op(e,{onSuccess:e=>i(o,e),onFailure:e=>r(a,e)});return n===void 0?s:Op(gM(n(s)),{onFailure(e){return ud(nC(),e),_M in o?L:die(zj(e),{onFailure(e){return t(o,sj({status:500}))},onSuccess([e]){return t(o,e)}})},onSuccess(e){return _M in o?L:t(o,e)}})},o=e=>gM(a(e)),s=(e,t,n)=>Wp(n,n=>{if(t.setContext(e.prev),!(vM in e.scope))return ef(e.scope,e.cause===void 0?n:Od(e.cause))},!0);class c{scope;prev;request;cause;constructor(e,t,n){this.scope=e,this.prev=t,this.request=n}[mr](e,t){let n=i(this.request,e);if(vc(n)&&n._tag===`Success`){if(t.setContext(this.prev),vM in this.scope)return n;let e=ef(this.scope,n);return e===void 0?n:B(e,()=>n)}return s(this,t,n)}[hr](e,t){return s(this,t,r(this,e))}}return ap(t=>{Rl(t);let r=qd(),i=new c(r,t.context,ua(t.context,dM));t.setContext(oa(i.prev,Kd,r));let l=t.cache.tracer;return n===void 0&&(l===void 0||l===is||mM(t,i.request))?(t._stack.push(i),e):s(i,t,n===void 0?o(i):a(i))})},_M=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/handled`),vM=/*#__PURE__*/ Symbol.for(`effect/http/HttpEffect/scopeEjected`),cle=e=>dM.use(t=>(yM(t,e),L)),yM=ele,lle=/*#__PURE__*/ j(2,(e,t)=>dM.use(n=>(yM(n,t),e))),bM=`~effect/http/HttpRouter`,xM=/*#__PURE__*/ P(`effect/http/HttpRouter`),ule=/*#__PURE__*/ R(function*(){let e=yield*ple,t=e.ignoreDuplicateSlashes??!0,n=ej(e),r=/* @__PURE__ */ new Set,i=e=>jp(r=>{let i=PM(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]:EM({...e[r],handler:a(e[r].handler)}),s={route:o,prefixSegments:Ni(o.prefix)?fle(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 xM.of({[bM]:bM,prefixed(e){return e=OM(e),xM.of({...this,prefixed:t=>this.prefixed(kM(t,e)),addAll:t=>i(t.map(gle(e))),add:(t,n,r,a)=>i([EM({method:t,path:kM(n,e),handler:oj(r)?F(r):Gf(r)?r:B(dM,r),uninterruptible:a?.uninterruptible??!1,prefix:e})])})},addAll:i,add:(e,t,n,r)=>i([DM(e,t,n,r)]),addGlobalMiddleware:e=>I(()=>{r.add(e)}),asHttpEffect(){let e=ap(e=>{let r=e.context,i=ua(r,dM),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 Nj({reason:new hce({request:i})}));let{route:o,prefixSegments:s}=a.handler;if(s!==void 0&&(r=oa(r,dM,dle(i,s,t))),r=oa(r,fM,a.searchParams),r=oa(r,SM,{route:o,params:a.params}),e.getRef(rs)!==is){let e=ca(r,Xo);e!==void 0&&e._tag===`Span`&&e.sampled&&e.attribute(`http.route`,o.path)}if(e.setContext(r),!o.uninterruptible){let t=zl(e);if(t!==void 0)return t}return o.handler});if(r.size===0)return e;for(let t of Ste(r))e=t(e);return e}})});function dle(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 fle(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=ZA(e,i),r=!1)}return n}const ple=/*#__PURE__*/ _a(`effect/http/HttpRouter/RouterConfig`,{defaultValue:()=>({})});var SM=class extends (/*#__PURE__*/ P()(`effect/http/HttpRouter/RouteContext`)){};const CM=e=>gf(B(xM,e)),wM=(e,t,n,r)=>CM(i=>i.add(e,t,n,r)),mle=/*#__PURE__*/ pf(xM)(ule),hle=e=>jp(t=>{let n=da(t,Kd),r=cf.forkOrCreate(t);return V(lf(wf(e,mle),r,n),e=>da(e,xM).asHttpEffect())}),TM=`~effect/http/HttpRouter/Route`,EM=e=>({...e,uninterruptible:e.uninterruptible??!1,prefix:typeof e.prefix==`string`?ji(e.prefix):e.prefix??Ai(),[TM]:TM}),DM=(e,t,n,r)=>EM({...r,method:e,path:t,handler:oj(n)?F(n):Gf(n)?n:B(dM,n),uninterruptible:r?.uninterruptible??!1}),OM=e=>e.endsWith(`/`)?e.slice(0,-1):e,kM=/*#__PURE__*/ j(2,(e,t)=>(t=OM(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),gle=/*#__PURE__*/ j(2,(e,t)=>EM({...e,path:kM(e.path,t),prefix:Pi(e.prefix,{onNone:()=>OM(t),onSome:e=>kM(e,t)})})),AM=function(){return arguments.length===0?jM:jM(arguments[0],arguments[1])},jM=(e,t)=>t?.global?gf(R(function*(){let t=yield*xM,n=Gf(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new vle(Gf(e)?hf(V(e,e=>ta(/* @__PURE__ */ new Map([[MM,e]])))):df(ta(/* @__PURE__ */ new Map([[MM,e]]))));let _le=0;const MM=`effect/http/HttpRouter/MiddlewareFn`;var vle=class e{"~effect/http/HttpRouter/Middleware"={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++_le}`;this.layer=hf(R({self:this},function*(){let e=yield*Ap(),t=[la(e,MM)];if(this.dependencies){let n=yield*cf,r=da(e,Kd),i=yield*lf(this.dependencies,n,r);t.push(...PM(i))}return ta(/* @__PURE__ */ new Map([[n,t]]))})).pipe(Cf(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?wf(this.dependencies,t.layer):t.layer)}};const NM=/*#__PURE__*/ new WeakMap,PM=e=>{let t=NM.get(e);if(t)return t;let n=Pa(),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=ka(e).reverse()}return NM.set(e,t),t};(/*#__PURE__*/ AM(rle)).layer;var FM=class extends (/*#__PURE__*/ P()(`effect/workers/Transferable/Collector`)){};const IM=()=>{let e=[],t=t=>{e.push(...t)},n=()=>e,r=()=>{let t=e;return e=[],t};return FM.of({addAllUnsafe:t,addAll:e=>I(()=>t(e)),readUnsafe:n,read:I(n),clearUnsafe:r,clear:I(r)})},LM=(e,t)=>e===void 0?t:`${e}.${t}`,RM=(e,t)=>({"rpc.system.name":`effect_rpc`,"rpc.method":e,...t}),zM=`~effect/rpc/RpcSchema/StreamSchema`;function BM(e){return N(e,zM)}function VM(e){return BM(e)?ji({success:e.success,error:e.error}):Ai()}const yle=/*#__PURE__*/ vx(_E);function ble(e,t){return Ax(yle.ast,{[zM]:zM,success:e,error:t})}var xle=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSchema/ClientAbort`)){static annotation=/*#__PURE__*/ this.context(!0).pipe(/*#__PURE__*/ oa(Td,{name:`ClientAbort`,stack:Lt,parent:void 0}))};const HM=`~effect/rpc/Rpc`;var UM=class{id;annotations;constructor(e){this.id=e,this.annotations=ia()}annotate(e,t){return this.annotations=oa(this.annotations,e,t),this}};const Sle={[HM]:HM,pipe(){return jt(this,arguments)},setSuccess(e){return WM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return WM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return WM({_tag:this._tag,payloadSchema:jx(e)?e:W(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return WM({_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 WM({_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 WM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:oa(this.annotations,e,t)})},annotateMerge(e){return WM({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:ha(this.annotations,e)})}},WM=e=>{function t(){}return Object.setPrototypeOf(t,Sle),Object.assign(t,e),t.key=`effect/rpc/Rpc/${e._tag}`,t},J=(e,t)=>{let n=t?.success??Hx,r=t?.error??Lx,i=t?.defect??bS(),a;return a=t?.primaryKey?class extends GS(`effect/rpc/Rpc/${e}`)(t.payload){"~effect/PrimaryKey"(){return t.primaryKey(this)}}:jx(t?.payload)?t?.payload:t?.payload?W(t?.payload):Hx,WM({_tag:e,payloadSchema:a,successSchema:t?.stream?ble(n,r):n,errorSchema:t?.stream?Lx:r,defectSchema:i,annotations:ia(),middlewares:/* @__PURE__ */ new Set})},GM=/*#__PURE__*/ new WeakMap,KM=e=>{if(GM.has(e))return GM.get(e);let t=e,n=/* @__PURE__ */ new Set([t.errorSchema]),r=VM(t.successSchema);Ni(r)&&n.add(r.value.error);for(let e of t.middlewares)n.add(e.error);let i=IS(Ni(r)?Hx:t.successSchema,K([...n]),t.defectSchema);return GM.set(e,i),i},qM=e=>`~effect/rpc/Rpc/Wrapper`in e,JM=e=>e,Cle={_tag:`Eof`},YM=e=>({_tag:`Defect`,defect:e}),wle={_tag:`Pong`},XM=YS;let Tle;const ZM=e=>(Tle??=new TextDecoder).decode(e);var QM=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcSerialization`)){};const Ele=/*#__PURE__*/ QM.of({contentType:`application/json`,includesFraming:!1,codecFor:XM,makeUnsafe:()=>({decode:e=>{let t=JSON.parse(typeof e==`string`?e:ZM(e));return Array.isArray(t)?t:[t]},encode:e=>JSON.stringify(e)})}),$M=e=>QM.of({contentType:e?.contentType??`application/json`,includesFraming:!1,codecFor:XM,makeUnsafe:()=>{let e=/* @__PURE__ */ new Map;return{decode:t=>Dle(JSON.parse(typeof t==`string`?t:ZM(t)),e),encode:t=>{let n=Ole(t,e);return n&&JSON.stringify(n)}}}});function Dle(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(!on(a))continue;let o=eN(a);r.push(o),o._tag===`Request`&&!o.isNotification&&(n.size++,t.set(o.id,n))}return r}return on(e)?[eN(e)]:[]}function eN(e){if(Object.hasOwn(e,`method`)){let t=e;if(rn(t.id)&&Jt(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 tN(e,t){if(!(`requestId`in e))return nN(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(),nN):void 0):nN(e)}function Ole(e,t){if(Array.isArray(e)===!1)return tN(e,t);if(e.length===0)return;let n=[];for(let r=0;r<e.length;r++){let i=tN(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 nN(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:kle,error:{_tag:`Defect`,code:1,message:`A defect occurred`,data:e.defect}};case`ClientProtocolError`:return{}}}const kle=-32603,Ale=e=>uf(QM)($M(e)),jle=()=>e=>Qf(()=>{let t=jw(1),n=[],r=(...e)=>jp(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*Np(Qf(()=>e(...t)),r);return n=[],r=e,yield*Gp(ep,()=>(r=t,L))}))}}))}),Mle=e=>Qf(()=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=(e,t)=>jp(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*Np(Qf(()=>i(e)),t)}return yield*Gp(ep,()=>(t.delete(e),r.delete(e),L))})}}))});let Nle=0;const rN=/*#__PURE__*/ H(function*(e,t){let n=t.spanPrefix,r=t?.supportsAck??!0,i=t?.disableTracing??!1,a=t?.generateRequestId??(()=>Nle++),o=yield*Ap(),s=da(o,Kd),c=/* @__PURE__ */ new Map,l=!1;yield*Xd(s,ap(e=>(l=!0,u(jd(e.id)))));let u=H(function*(e){for(let[t,n]of c)c.delete(t),n._tag===`Queue`?yield*e._tag===`Success`?iw(n.queue):nw(n.queue,e.cause):n.resume(e)}),d=e=>{let r=BM(e.successSchema),a=m(e);return(o,s)=>{let c=s?.headers?gg(s.headers):hg,l=s?.context??ia();if(!r){let r=t=>f(e,a,t,e.payloadSchema.make(o),c,l,s?.discard??!1);return i?r(void 0):$p(LM(n,e._tag),{kind:`client`,attributes:RM(e._tag,t.spanAttributes)},r)}let u=p(e,a,e.payloadSchema.make(o),c,s?.streamBufferSize??16,l);return s?.asQueue?u:jE(V(u,kE))}},f=(e,n,r,i,o,s,u)=>ap(d=>{if(l)return qp;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:bg(d.getRef(iN),o)});if(u)return p;let m;return Yp($f(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?tm(r,{captureStackTrace:!1}):M,om(d.context)),m.addObserver(e=>{if(e._tag===`Failure`)return t(e)})}),e=>(c.delete(f),sp(tC(m),h(f,Array.from(e),s))))}),p=H(function*(e,r,o,s,u,d){if(l)return yield*qp;let f=i?void 0:yield*hie(LM(n,e._tag),{kind:`client`,attributes:RM(e._tag,t.spanAttributes)}),p=nC(),m=a(),g=ua(p.context,Kd),_=yield*XC(u);return yield*Yd(g,e=>(sw(_),c.has(m)?(c.delete(m),h(m,Pd(e)?Array.from(ure(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:bg(p.getRef(iN),s)}).pipe(f?tm(f,{captureStackTrace:!1}):M,Up(e=>nw(_,e)),Jp,rm(g,{startImmediately:!0})),_}),m=e=>{let t=[];for(let n of e.middlewares.values()){let e=la(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)=>$f(i=>{let a=nC();t.onFromClient({message:{_tag:`Interrupt`,requestId:e,interruptors:n},context:r,discard:!1}).pipe(oie(1e3),om(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:ew(i.queue,e.values).pipe(r?B(()=>t.onFromClient({message:{_tag:`Ack`,requestId:e.requestId},context:i.context,discard:!1})):M,hp(e=>nw(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`?iw(n.queue):nw(n.queue,e.exit.cause)):L}case`Defect`:return u(Ad(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=>{or(_,e._tag,d(e))});return{client:_,write:g}});let Ple=0;const Fle=/*#__PURE__*/ H(function*(e,t){let n=Ple++,{codecFor:r,run:i,send:a,supportsAck:o,supportsTransferables:s}=yield*aN,c=Ile(r),l=Aoe(r(bS())),u=/* @__PURE__ */ new Map,d=e=>u.has(e)?(u.delete(e),a(n,{_tag:`Interrupt`,requestId:e})):L,{client:f,write:p}=yield*rN(e,{...t,supportsAck:o,onFromClient({message:t}){switch(t._tag){case`Request`:{let r=e.requests.get(t.tag),i=s?IM():void 0,o=nC(),l={rpc:r,context:i?oa(o.context,FM,i):o.context,schemas:c(r)};return u.set(t.id,l),l.schemas.encodePayload(t.payload).pipe(Np(l.context),yp,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=JM(e.requestId),n=u.get(t);if(!n||Mi(n.schemas.decodeChunk))return L;let r=n.schemas.decodeChunk.value;return Zp(i=>i(r(e.values).pipe(Np(n.context),yp,B(e=>p({_tag:`Chunk`,clientId:0,requestId:t,values:e})))).pipe(Up(e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Od(e)}).pipe(sp(yd(e)?L:Sp(d(t))))),iie(e=>!yd(e),()=>L)))}case`Exit`:{let t=JM(e.requestId),n=u.get(t);return n?(u.delete(t),n.schemas.decodeExit(e.exit).pipe(Np(n.context),yp,Op({onSuccess:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:e}),onFailure:e=>p({_tag:`Exit`,clientId:0,requestId:t,exit:Od(e)})}))):L}case`Defect`:return p({_tag:`Defect`,clientId:0,defect:l(e.defect)});case`ClientProtocolError`:{let t=kd(e.error);return qf(Array.from(u.keys()),e=>p({_tag:`Exit`,clientId:0,requestId:e,exit:t}))}default:return L}}).pipe(hp(hm),Jp,im),f}),Ile=e=>{let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=VM(n.successSchema);return r={decodeChunk:Vi(i,t=>Cx(e(Jx(t.success)))),encodePayload:Dx(e(n.payloadSchema)),decodeExit:Cx(e(KM(n)))},t.set(n,r),r}},iN=/*#__PURE__*/ _a(`effect/rpc/RpcClient/CurrentHeaders`,{defaultValue:()=>hg});var aN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcClient/Protocol`)){static make=Mle};const Lle=/*#__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*Ap(),l=da(c,Kd),u=rC(Qd(l,`parallel`)),d=o===`unbounded`?void 0:yield*Pw(o),f=/* @__PURE__ */ new Map,p=!1,m=iC(!1);yield*Xd(l,ap(e=>{p=!0;for(let t of f.values())if(t.ended=!0,t.fibers.size===0)u(om(c)(_(t)));else for(let n of t.fibers.values())n.interruptUnsafe(e.id);return f.size===0?L:m.await}));let h=e=>ap(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)=>gp(ap(i=>{if(p)return qp;let a=f.get(e);if(!a)a={id:e,latches:void 0,fibers:/* @__PURE__ */ new Map,ended:!1,serverClient:new UM(e)},f.set(e,a);else if(a.ended&&(n._tag!==`Interrupt`&&n._tag!==`Ack`||!a.fibers.has(n.requestId)))return qp;switch(n._tag){case`Request`:return v(i,a,n,r);case`Ack`:{let e=a.latches?.get(n.requestId);return e?fp(e.open):L}case`Interrupt`:{let r=a.fibers.get(n.requestId);return r?(r.interruptUnsafe(i.id,xle.annotation),L):t.onFromServer({_tag:`Exit`,clientId:e,requestId:n.requestId,exit:jd()})}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?sp(n,m.open):n},v=(i,o,l,f)=>{if(o.fibers.has(l.id))return qp;let p=e.requests.get(l.tag),m=la(c,p?.key);if(!p||!m){let e=gp(t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:Ad(`Unknown request tag: ${l.tag}`)}),e=>b(o,e));return!o.ended||o.fibers.size>0?e:Hp(e,_(o))}let h=BM(p.successSchema),g={rpc:p,client:o.serverClient,requestId:l.id,headers:l.headers,payload:l.payload},v=m.handler(l.payload,g),x=qM(v),S=x&&v.fork,ee=x&&v.uninterruptible,C=x?v.value:v,te,w=h?y(o,l,C,e=>{te=e}):C,ne=p.middlewares.size===0?w:h?B(up(dN(c,w,g)),e=>te?tp(te):e):dN(c,w,g),T=!1,re=qd(),ie,ae=Gp(ne,e=>{T=!0;let n;if(e._tag===`Success`)_re(e.value)?(ie=e.value,n=L):n=t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});else if(te)return ef(re,e)??L;else n=!s&&vd(e.cause)&&!yd(e.cause)?b(o,_d(e.cause)):t.onFromServer({_tag:`Exit`,clientId:o.id,requestId:l.id,exit:e});let r=ef(re,e);return e._tag===`Failure`&&ud(nC(),e.cause),r?Hp(n,r):n});if(f?.onRequest&&(ae=f.onRequest(ae)),n){let e=ca(i.context,Xo);ae=em(ae,LM(a,l.tag),{captureStackTrace:!1,kind:`server`,attributes:RM(l.tag,t.spanAttributes),parent:r&&l.spanId?Qo({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=om(oa(Ble(m,i.context),Kd,re));return u(oe(ap(e=>(o.fibers.set(l.id,e),ae)),ee?{uninterruptible:!0}:void 0)).addObserver(function e(n){if(ie){let n=u(oe(Gp(zd(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:jd()}))),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=>Up(t.onFromServer({_tag:`Chunk`,clientId:e.id,requestId:n.id,values:r}),e=>(sre(e)||a(e),L)),s;return i&&(e.latches??=/* @__PURE__ */ new Map,s=e.latches.get(n.id),s||(s=iC(!1),e.latches.set(n.id,s))),Gf(r)?r.pipe(B(e=>Jf({while:Ft,body:Pt(B(cw(e),e=>{let t=o(e);return s?(s.closeUnsafe(),B(t,()=>s.await)):t})),step:Rt})),If(()=>L),zp):QE(r,e=>{let t=o(e);return s?(s.closeUnsafe(),sp(t,s.await)):t})},b=(e,n)=>Qf(()=>{let r=e.ended&&e.fibers.size===0,i=t.onFromServer({_tag:`Defect`,clientId:e.id,defect:n});return r?sp(i,_(e)):i});return M({write:g,disconnect:h})}),oN=e=>e===Ele.codecFor,sN=/*#__PURE__*/ new WeakMap,Rle=(e,t)=>{let n=oN(e),r=n?sN.get(t):void 0;if(r===void 0){let i=VM(t.successSchema);r={decode:Cx(e(t.payloadSchema)),encodeChunk:Ex(e(Jx(Ni(i)?i.value.success:Rx))),encodeExit:Ex(e(KM(t)))},n&&sN.set(t,r)}return r};let zle;const cN=e=>({encodeDefectUnsafe:kx(e(bS())),encodeUnknownRequestExit:Ex(e(IS(Lx,Lx,bS())))}),lN=e=>oN(e)?zle??=cN(e):cN(e),uN=/*#__PURE__*/ new WeakMap,Ble=(e,t)=>{let n=uN.get(e);n===void 0&&(n=/* @__PURE__ */ new WeakMap,uN.set(e,n));let r=n.get(t);return r===void 0&&(r=ha(e.context,t),n.set(t,r)),r},dN=(e,t,n)=>{for(let r of n.rpc.middlewares)t=ua(e,r)(t,n);return t},Vle=/*#__PURE__*/ H(function*(e,t){let{codecFor:n,disconnects:r,end:i,run:a,send:o,supportsAck:s,supportsSpanPropagation:c,supportsTransferables:l}=yield*fN,{encodeDefectUnsafe:u,encodeUnknownRequestExit:d}=lN(n),f=yield*Ap(),p=yield*Cre(),m=yield*Lle(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(Jd(p));yield*nm(Jf({while:Ft,body:Pt(B(dw(r),e=>(_.delete(e),m.disconnect(e)))),step:Rt}));let h=/* @__PURE__ */ new WeakMap,g=e=>{let t=h.get(e);if(!t){let r=la(f,e.key);t={tag:e._tag,...Rle(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=Ed(r)&&Nd(r)?o(e.id,v(t,i,r.value),a&&a.clearUnsafe()):B(pp(Np(a?Lp(r,FM,a):r,n.context),e=>ap(t=>{let r=pd(`Failed to encode response for RPC "${n.tag}": ${U_(e.issue)}`);return ud(t,r),s=!0,tp(r)})),n=>o(e.id,v(t,i,n),a&&a.clearUnsafe()));return hp(c,r=>(e.schemas.delete(t),sp(b(e,t,n.encodeExit,_d(r)),s?tp(r):m.write(e.id,{_tag:`Interrupt`,requestId:t,interruptors:[]}))))},b=(e,t,n,r)=>hp(B(n(Ad(r)),n=>o(e.id,v(t,`Exit`,n))),t=>x(e,_d(t))),x=(e,t)=>hp(o(e.id,YM(u(t))),e=>vm(_m(e),{module:`RpcServer`,method:`sendDefect`})),S=(e,t,n,r,i)=>{e.schemas.set(t,l?{...n,collector:IM()}:n);let a=r;return a.id=t,a.payload=i,a.headers=gg(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=JM(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 Ed(s)&&Nd(s)?S(r,i,o,n,s.value):kp(Np(s,o.context),{onFailure:e=>b(r,i,o.encodeExit,U_(e.issue)),onSuccess:e=>S(r,i,o,n,e)})}case`Ping`:return hp(o(r.id,wle),e=>x(r,_d(e)));case`Eof`:return m.write(t,n);case`Ack`:return m.write(t,n);case`Interrupt`:return m.write(t,{...n,requestId:JM(n.requestId),interruptors:[]});default:return x(r,`Unknown request tag: ${n._tag}`)}}).pipe(xp(e=>pm(`BUG: RpcServer protocol crashed`,e)),Gp(e=>$d(p,e)))});var fN=class extends (/*#__PURE__*/ P()(`effect/rpc/RpcServer/Protocol`)){static make=/*#__PURE__*/ jle()};const pN=/*#__PURE__*/ H(function*(e={}){let t=yield*QM,{encodeDefectUnsafe:n}=lN(t.codecFor),r=t.includesFraming,i=!t.contentType.includes(`json`),a=yield*YC(),o,s=0,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=new TextEncoder,d=R(function*(){let d=nC(),f=ua(d.context,dM),p=ua(d.context,Kd),m=Object.entries(f.headers),h=yield*yp(i?V(f.arrayBuffer,e=>new Uint8Array(e)):f.text),g=s++,_=yield*YC({capacity:r&&e.streamBufferSize!==`unbounded`?e.streamBufferSize??16:void 0}),v=t.makeUnsafe(),y=[],b=e=>typeof e==`string`?QC(_,u.encode(e)):QC(_,e),x={write:r?e=>{try{let t=v.encode(e);return t===void 0?L:b(t)}catch(e){return b(v.encode(YM(n(e))))}}:e=>e._tag===`Request`&&e.isNotification===!0?L:QC(_,e),end:iw(_)};yield*Yd(p,()=>(c.delete(g),l.delete(g),$C(a,g),_.state._tag===`Done`?L:sp(ow(_),qf(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(JM(n.id)),n.headers=m.concat(n.headers)),yield*o(g,n)}}catch(e){yield*x.write(YM(n(e)))}if(yield*o(g,Cle),!r){let e=yield*lw(_),n=v.encode(e);return dj(n===void 0?``:n,{contentType:t.contentType})}let S=yield*If(cw(_),()=>F([]));return _.state._tag===`Done`?lj(Hle(S),{contentType:t.contentType}):mj(OE(S).pipe(PE(kE(_))),{contentType:t.contentType})});return{protocol:yield*fN.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:Zf,supportsAck:!1,supportsTransferables:!1,supportsSpanPropagation:!1,supportsNotifications:r,codecFor:t.codecFor}))),httpEffect:d}}),Hle=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},Ule={add(...e){let t=new Map(this.requests);for(let n of e)t.set(n._tag,n);return mN({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 mN({requests:t,annotations:ta(n)})},omit(...e){let t=new Map(this.requests);for(let n of e)t.delete(n);return mN({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 mN({requests:t,annotations:this.annotations})},toHandlers(e){let t=this;return R(function*(){let n=yield*Ap(),r=Gf(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})}),ta(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 mN({requests:t,annotations:this.annotations})},toLayer(e){return hf(this.toHandlers(e))},of:M,toLayerHandler(e,t){let n=this;return hf(R(function*(){let r=yield*Ap(),i=Gf(t)?yield*t:t,a=/* @__PURE__ */ new Map,o=n.requests.get(e);return a.set(o.key,{handler:i,context:r}),ta(a)}))},accessHandler(e){return jp(t=>{let n=this.requests.get(e),{handler:r,context:i}=la(t,n.key);return F((e,t)=>{t.rpc=n;let a=r(e,t),o=qM(a)?a.value:a;return Gf(o)?Mp(o,i):JE(o,i)})})},annotate(e,t){return mN({requests:this.requests,annotations:oa(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsMerge(aa(e,t))},annotateMerge(e){return mN({requests:this.requests,annotations:ha(this.annotations,e)})},annotateRpcsMerge(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.requests)t.set(n,r.annotateMerge(ha(e,r.annotations)));return mN({requests:t,annotations:this.annotations})}},mN=e=>Object.assign(function(){},Ule,{requests:e.requests,annotations:e.annotations}),hN=(...e)=>mN({requests:new Map(e.map(e=>[e._tag,e])),annotations:ia()}),Wle=e=>{switch(e){case`SHA-1`:return`sha1`;case`SHA-256`:return`sha256`;case`SHA-384`:return`sha384`;case`SHA-512`:return`sha512`}},Gle=/* @__PURE__ */ uf(aO,/* @__PURE__ */ oO({randomBytes:st.randomBytes,digest:(e,t)=>ip({try:()=>Uint8Array.from(st.createHash(Wle(e)).update(t).digest()),catch:e=>IT({module:`Crypto`,method:`digest`,_tag:`Unknown`,description:`Could not compute digest`,cause:e})})})),gN=e=>t=>LT({module:`FileSystem`,method:e,description:t.message??String(t)}),_N=(e,t)=>{let n=Number(e);if(!Number.isSafeInteger(n))throw RangeError(`${t} exceeds the safe integer range: ${e}`);return n},vN=e=>Hi(Li(e),Gm),yN=e=>BigInt.asUintN(64,e),bN=e=>Vi(Li(e),yN),xN=(e,t)=>ip({try:()=>_N(e,`position`),catch:gN(t)}),Kle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.access,/*#__PURE__*/ Sk(`FileSystem`,`access`),/*#__PURE__*/ gN(`access`));return(t,n)=>{let r=Et.constants.F_OK;return n?.readable&&(r|=Et.constants.R_OK),n?.writable&&(r|=Et.constants.W_OK),e(t,r)}})(),qle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.cp,/*#__PURE__*/ Sk(`FileSystem`,`copy`),/*#__PURE__*/ gN(`copy`));return(t,n,r)=>e(t,n,{force:r?.overwrite??!1,preserveTimestamps:r?.preserveTimestamps??!1,recursive:!0})})(),Jle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.copyFile,/*#__PURE__*/ Sk(`FileSystem`,`copyFile`),/*#__PURE__*/ gN(`copyFile`));return(t,n)=>e(t,n)})(),Yle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.chmod,/*#__PURE__*/ Sk(`FileSystem`,`chmod`),/*#__PURE__*/ gN(`chmod`));return(t,n)=>e(t,n)})(),Xle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.chown,/*#__PURE__*/ Sk(`FileSystem`,`chown`),/*#__PURE__*/ gN(`chown`));return(t,n,r)=>e(t,n,r)})(),Zle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.glob,/*#__PURE__*/ Sk(`FileSystem`,`glob`),/*#__PURE__*/ gN(`glob`));return(t,n)=>e(t,{cwd:n?.root,exclude:n?.exclude})})(),Qle=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.link,/*#__PURE__*/ Sk(`FileSystem`,`link`),/*#__PURE__*/ gN(`link`));return(t,n)=>e(t,n)})(),$le=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.mkdir,/*#__PURE__*/ Sk(`FileSystem`,`makeDirectory`),/*#__PURE__*/ gN(`makeDirectory`));return(t,n)=>e(t,{recursive:n?.recursive??!1,mode:n?.mode})})(),SN=e=>{let t=ym(Et.mkdtemp,Sk(`FileSystem`,e),gN(e));return e=>Qf(()=>{let n=e?.prefix??``,r=typeof e?.directory==`string`?ut.join(e.directory,`.`):vt.tmpdir();return t(n?ut.join(r,n):r+`/`)})},eue=/*#__PURE__*/ SN(`makeTempDirectory`),CN=e=>{let t=ym(Et.rm,Sk(`FileSystem`,e),gN(e));return(e,n)=>t(e,{recursive:n?.recursive??!1,force:n?.force??!1})},tue=/*#__PURE__*/ CN(`remove`),nue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ SN(`makeTempDirectoryScoped`),t=/*#__PURE__*/ CN(`makeTempDirectoryScoped`);return n=>Bp(e(n),e=>yp(t(e,{recursive:!0})))})(),rue=e=>{let{O_APPEND:t,O_CREAT:n,O_EXCL:r,O_RDONLY:i,O_RDWR:a,O_TRUNC:o,O_WRONLY:s}=Et.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}},iue=(e,t)=>Qf(()=>{let{O_NOFOLLOW:n}=Et.constants;return process.platform===`win32`||typeof n!=`number`||n===0?z(LT({module:`FileSystem`,method:e,description:`noFollow is not supported on this platform`})):F(rue(t)|n)}),aue=/*#__PURE__*/ (e=>{let t=ym(Et.open,Sk(`FileSystem`,e),gN(e)),n=ym(Et.close,Sk(`FileSystem`,e),gN(e));return(r,i)=>zt(Bp(i?.noFollow===!0?B(iue(e,i.flag??`r`),e=>t(r,e,i.mode)):t(r,i?.flag??`r`,i?.mode),e=>yp(n(e))),V(e=>oue(e,i?.flag?.startsWith(`a`)??!1)))})(`open`),wN=e=>LT({module:`FileSystem`,method:e,description:`Cannot read before the start of the file`}),oue=/*#__PURE__*/ (()=>{let e=e=>ym(Et.read,Sk(`FileSystem`,e),gN(e)),t=/*#__PURE__*/ e(`read`),n=/*#__PURE__*/ e(`readAlloc`),r=/*#__PURE__*/ ym(Et.fstat,/*#__PURE__*/ Sk(`FileSystem`,`stat`),/*#__PURE__*/ gN(`stat`)),i=/*#__PURE__*/ ym(Et.ftruncate,/*#__PURE__*/ Sk(`FileSystem`,`truncate`),/*#__PURE__*/ gN(`truncate`)),a=/*#__PURE__*/ ym(Et.fsync,/*#__PURE__*/ Sk(`FileSystem`,`sync`),/*#__PURE__*/ gN(`sync`)),o=e=>ym(Et.write,Sk(`FileSystem`,e),gN(e)),s=/*#__PURE__*/ o(`write`),c=/*#__PURE__*/ o(`writeAll`);class l{[aD];fd;append;position=/*#__PURE__*/ BigInt(0);constructor(e,t){this[aD]=aD,this.fd=e,this.append=t}get stat(){return B(r(this.fd,{bigint:!0}),EN)}get sync(){return a(this.fd)}seek(e,t){return Qf(()=>{let n=t===`start`?e:this.position+e;return n<BigInt(0)?z(LT({module:`FileSystem`,method:`seek`,description:`Cannot seek before the start of the file`})):(this.position=n,F(n))})}read(e,n){return Qf(()=>{let r=n?.position;if(r!==void 0)return r<BigInt(0)?z(wN(`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 Qf(()=>{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(wN(`readAlloc`));let i=Buffer.allocUnsafeSlow(e),a=r??this.position;return V(n(this.fd,{buffer:i,position:a}),t=>{if(t===0)return Ai();if(r===void 0&&(this.position=a+BigInt(t)),t===e)return ji(i);let n=Buffer.allocUnsafeSlow(t);return i.copy(n,0,0,t),ji(n)})}catch(e){return z(gN(`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 Qf(()=>{let t=this.position;return B(this.append?F(void 0):xN(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 Qf(()=>{let t=this.position;return B(this.append?F(void 0):xN(t,`writeAll`),n=>B(c(this.fd,e,void 0,void 0,n),n=>n===0?z(IT({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)})(),TN=e=>{let t=SN(e);return H(function*(e){let n=yield*t(e),r=st.randomBytes(6).toString(`hex`),i=ut.join(n,e?.suffix?`${r}${e.suffix}`:r);return yield*ON(i,/* @__PURE__ */ new Uint8Array),i})},sue=/*#__PURE__*/ TN(`makeTempFile`),cue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ TN(`makeTempFileScoped`),t=/*#__PURE__*/ CN(`makeTempFileScoped`);return n=>Bp(e(n),e=>yp(t(ut.dirname(e),{recursive:!0})))})(),lue=(e,t)=>Xf({try:()=>Et.promises.readdir(e,t),catch:t=>Sk(`FileSystem`,`readDirectory`)(t,[e])}),uue=e=>$f((t,n)=>{try{Et.readFile(e,{signal:n},(n,r)=>{t(n?z(Sk(`FileSystem`,`readFile`)(n,[e])):F(r))})}catch(e){t(z(gN(`readFile`)(e)))}}),due=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.readlink,/*#__PURE__*/ Sk(`FileSystem`,`readLink`),/*#__PURE__*/ gN(`readLink`));return t=>e(t)})(),fue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.realpath,/*#__PURE__*/ Sk(`FileSystem`,`realPath`),/*#__PURE__*/ gN(`realPath`));return t=>e(t)})(),pue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.rename,/*#__PURE__*/ Sk(`FileSystem`,`rename`),/*#__PURE__*/ gN(`rename`));return(t,n)=>e(t,n)})(),EN=e=>ip({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:Li(e.mtime),atime:Li(e.atime),birthtime:Li(e.birthtime),dev:yN(e.dev),rdev:bN(e.rdev),ino:bN(e.ino),mode:_N(e.mode,`mode`),nlink:bN(e.nlink),uid:vN(e.uid),gid:vN(e.gid),size:lh(e.size),blksize:e.blksize===void 0?Ai():ji(lh(e.blksize)),blocks:Li(e.blocks)}),catch:gN(`stat`)}),DN=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.stat,/*#__PURE__*/ Sk(`FileSystem`,`stat`),/*#__PURE__*/ gN(`stat`));return t=>B(e(t,{bigint:!0}),EN)})(),mue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.symlink,/*#__PURE__*/ Sk(`FileSystem`,`symlink`),/*#__PURE__*/ gN(`symlink`));return(t,n)=>e(t,n)})(),hue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.truncate,/*#__PURE__*/ Sk(`FileSystem`,`truncate`),/*#__PURE__*/ gN(`truncate`));return(t,n)=>e(t,n)})(),gue=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ ym(Et.utimes,/*#__PURE__*/ Sk(`FileSystem`,`utime`),/*#__PURE__*/ gN(`utime`));return(t,n,r)=>e(t,n,r)})(),_ue=(e,t,n)=>wE(r=>Bp(I(()=>{let i=t.type===`Directory`?e:ut.dirname(e),a=Et.watch(e,{recursive:n?.recursive??!1},(e,t)=>{if(t)switch(e){case`rename`:am(kp(DN(ut.resolve(i,t)),{onSuccess:e=>QC(r,{_tag:`Create`,path:t}),onFailure:e=>QC(r,{_tag:`Remove`,path:t})}));return;case`change`:$C(r,{_tag:`Update`,path:t});return}});return a.on(`error`,t=>{rw(r,are(IT({module:`FileSystem`,_tag:`Unknown`,method:`watch`,pathOrDescriptor:e,cause:t})))}),a.on(`close`,()=>{aw(r)}),a}),e=>I(()=>e.close())).pipe(cp(()=>I(()=>n?.onReady?.())))),vue=(e,t,n)=>Kf([DN(t),Fp(oD)]).pipe(V(([r,i])=>Ii(i,()=>e).pipe(Hi(e=>e.register(t,r,n)),Fi(()=>_ue(t,r,n)))),jE),ON=(e,t,n)=>$f((r,i)=>{try{Et.writeFile(e,t,{signal:i,flag:n?.flag,mode:n?.mode},t=>{r(t?z(Sk(`FileSystem`,`writeFile`)(t,[e])):L)})}catch(e){r(z(gN(`writeFile`)(e)))}}),yue=/*#__PURE__*/ V(/*#__PURE__*/ Fp(oD),e=>iD({access:Kle,chmod:Yle,chown:Xle,copy:qle,copyFile:Jle,glob:Zle,link:Qle,makeDirectory:$le,makeTempDirectory:eue,makeTempDirectoryScoped:nue,makeTempFile:sue,makeTempFileScoped:cue,open:aue,readDirectory:lue,readFile:uue,readLink:due,realPath:fue,remove:tue,rename:pue,stat:DN,symlink:mue,truncate:hue,utimes:gue,watch(t,n){return vue(e,t,n)},writeFile:ON})),kN=/* @__PURE__ */ pf(rD)(yue),AN=/*#__PURE__*/ new TextDecoder;var bue=class extends tr{[DA];source;onError;remoteAddressOverride;constructor(e,t,n){super(),this[DA]=DA,this.source=e,this.onError=t,this.remoteAddressOverride=n}get headers(){return gg(this.source.headers)}get remoteAddress(){return this.remoteAddressOverride??Li(this.source.socket?.remoteAddress)}textEffect;get text(){return this.textEffect||=V(this.arrayBuffer,e=>AN.decode(e)),this.textEffect}get textUnsafe(){return lm(this.text)}get json(){return B(this.text,e=>ip({try:()=>e===``?null:JSON.parse(e),catch:this.onError}))}get jsonUnsafe(){return lm(this.json)}get urlParamsBody(){return B(this.text,e=>ip({try:()=>jg(new URLSearchParams(e)),catch:this.onError}))}get stream(){return Ek({evaluate:()=>this.source,onError:this.onError})}arrayBufferEffect;get arrayBuffer(){return this.arrayBufferEffect||(this.arrayBufferEffect=ap(e=>Ak(()=>this.source,{onError:this.onError,maxBytes:e.getRef(kA)})).pipe(Kp,lm),this.textEffect=V(this.arrayBufferEffect,e=>AN.decode(e))),this.arrayBufferEffect}};const jN=/*#__PURE__*/ _a(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch});var MN=class extends (/*#__PURE__*/ P()(`effect/http/FetchHttpClient/RequestInit`)){};const NN=/*#__PURE__*/ Nse(/*#__PURE__*/ F(/* @__PURE__ */ Ese((e,t,n,r)=>{let i=r.getRef(jN),a=ca(r.context,MN)??{},o=a.headers?bg(gg(a.headers),e.headers):e.headers;o[`content-length`]&&(o=xg(o,`content-length`));let s=r=>V(Xf({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 cA({reason:new fA({request:e,cause:t})})}),t=>fse(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(tD(e.body.stream),s)}return s(void 0)}))),xue=/*#__PURE__*/ new Set(typeof Ot.zstdCompress==`function`?[`gzip`,`deflate`,`br`,`zstd`]:[`gzip`,`deflate`,`br`]),PN=(e,t)=>{let n={};return e!==void 0&&(n[Ot.constants.BROTLI_PARAM_QUALITY]=e),t!==void 0&&(n[Ot.constants.BROTLI_PARAM_SIZE_HINT]=t),{params:n}},FN=e=>e===void 0||e===3?void 0:{params:{[Ot.constants.ZSTD_c_compressionLevel]:e}},Sue=(e,t,n)=>$f(r=>{let i=(e,t)=>r(e===null?F(t):rp(e));switch(t){case`gzip`:Ot.gzip(e,{level:n?.level},i);break;case`deflate`:Ot.deflate(e,{level:n?.level},i);break;case`br`:Ot.brotliCompress(e,PN(n?.level,e.byteLength),i);break;case`zstd`:{let t=FN(n?.level);t===void 0?Ot.zstdCompress(e,i):Ot.zstdCompress(e,t,i);break}}}),Cue=e=>({algorithms:e.algorithms,compressResponse(t,n,r){let i=t.body;return i._tag===`Uint8Array`?V(Sue(i.body,n,r),e=>hj(bj(t,Zk(e,t.headers[`content-type`]??i.contentType)),`content-length`,e.byteLength.toString())):e.compressResponse(t,n,r)}}),IN=(e,t)=>{switch(e){case`gzip`:return Ot.createGzip({level:t?.level,flush:Ot.constants.Z_SYNC_FLUSH});case`deflate`:return Ot.createDeflate({level:t?.level,flush:Ot.constants.Z_SYNC_FLUSH});case`br`:return Ot.createBrotliCompress({...PN(t?.level),flush:Ot.constants.BROTLI_OPERATION_FLUSH});case`zstd`:return Ot.createZstdCompress({...FN(t?.level),flush:Ot.constants.ZSTD_e_flush})}},LN=(e,t)=>{let n;return new St({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)}})},RN=(e,t)=>gj(bj(e,t),`content-length`),wue=/*#__PURE__*/ uce({platform:`node`,compression:/* @__PURE__ */ Cue({algorithms:xue,compressResponse(e,t,n){let r=e.body;switch(r._tag){case`Stream`:return F(RN(e,oA(kk(r.stream,{evaluate:()=>IN(t,n)}),e.headers[`content-type`]??r.contentType)));case`Raw`:{let i=r.body instanceof St?r.body:void 0,a=LN(()=>{let e=IN(t,n);return i??=St.fromWeb(new Response(r.body).body),Ct(i,e,e=>{e&&a.destroy(e)})},()=>i?.destroy());return F(RN(e,Yk(a,{contentType:e.headers[`content-type`]??r.contentType})))}default:return F(e)}}}),fileResponse(e,t,n,r,i,a,o){let s=LN(()=>o===BigInt(0)?St.from([]):Et.createReadStream(e,{start:i,end:a===void 0?void 0:a-1}));return pj(s,{headers:{...r,"content-type":r[`content-type`]??Fi(Tj(e),()=>`application/octet-stream`),"content-length":o.toString()},status:t,statusText:n})},fileWebResponse(e,t,n,r,i){return pj(LN(()=>St.fromWeb(e.stream())),{headers:bg(r,_g({"content-type":r[`content-type`]??(e.type===``?Fi(Tj(e.name),()=>`application/octet-stream`):e.type),"content-length":e.size.toString()})),status:t,statusText:n})}}),Tue=/*#__PURE__*/ zt(/*#__PURE__*/ pf(Ej)(wue),/*#__PURE__*/ Cf(kN),/*#__PURE__*/ Cf(Yse));var Eue=class extends bt{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,n;this._parser=Ice({...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 Oue(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 Due=e=>new Eue(e);var Oue=class extends St{_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 zN=(e,t)=>Uce(t).pipe(V(t=>Ek({evaluate(){let n=Due(t);return e.pipe(n),n},onError:e=>Nue(e)})),jE,ME(Aue)),kue=(e,t)=>Jce(zN(e,t),(e,t)=>Xf({try:n=>mee.pipeline(t.file,Et.createWriteStream(e),{signal:n}),catch:e=>iM.fromReason(`InternalError`,e)})),Aue=e=>e._tag===`Field`?new jue(e.info,e.value):new Mue(e);var BN=class extends tr{[nM];constructor(){super(),this[nM]=nM}},jue=class extends BN{_tag=`Field`;key;contentType;value;constructor(e,t){super(),this.key=e.name,this.contentType=e.contentType,this.value=Rce(e,t)}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`Field`,key:this.key,value:this.value,contentType:this.contentType}}},Mue=class extends BN{_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=Ek({evaluate:()=>e,onError:e=>iM.fromReason(`InternalError`,e)}),this.contentEffect=jk(()=>e,{onError:e=>iM.fromReason(`InternalError`,e)})}toJSON(){return{_id:`@effect/platform/Multipart/Part`,_tag:`File`,key:this.key,name:this.name,contentType:this.contentType}}};function Nue(e){switch(e._tag){case`ReachedLimit`:switch(e.limit){case`MaxParts`:return iM.fromReason(`TooManyParts`,e);case`MaxFieldSize`:return iM.fromReason(`FieldTooLarge`,e);case`MaxPartSize`:return iM.fromReason(`FileTooLarge`,e);case`MaxTotalSize`:return iM.fromReason(`BodyTooLarge`,e)}default:return iM.fromReason(`Parse`,e)}}const VN=e=>({fromFileUrl:t=>ip({try:()=>ht.fileURLToPath(t,{windows:e}),catch:e=>new NT({module:`Path`,method:`fromFileUrl`,cause:e})}),toFileUrl:t=>ip({try:()=>ht.pathToFileURL(t,{windows:e}),catch:e=>new NT({module:`Path`,method:`toFileUrl`,cause:e})})});({...ut.posix,.../*#__PURE__*/ VN(!1)}),{...ut.win32,.../*#__PURE__*/ VN(!0)};const Pue=/* @__PURE__ */ uf(cD)(/*#__PURE__*/ lD({...ut,.../*#__PURE__*/ VN(void 0)})),Fue=/* @__PURE__ */ uf(qO,/*#__PURE__*/ JO({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=>Ck({evaluate:()=>process.stdout,onError:e=>IT({module:`Stdio`,method:`stdout`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stderr:e=>Ck({evaluate:()=>process.stderr,onError:e=>IT({module:`Stdio`,method:`stderr`,_tag:`Unknown`,cause:e}),endOnDone:e?.endOnDone??!1}),stdin:/*#__PURE__*/ Ek({evaluate:()=>process.stdin,onError:e=>IT({module:`Stdio`,method:`stdin`,_tag:`Unknown`,cause:e}),closeOnDone:!1})})),Iue=/*#__PURE__*/ pf(QO,/*#__PURE__*/ (/* @__PURE__ */ H(function*(e=HN){let t=process.stdin,n=process.stdout,r=yield*YC(),i=t.readableEnded,a=!1,o=()=>{i=!0,a||aw(r)};t.once(`end`,o),yield*Vp(()=>I(()=>t.off(`end`,o)));let s=yield*hE({acquire:Bp(I(()=>{let e=kt.createInterface({input:t,escapeCodeTimeout:50}),n=e=>$C(r,e),i=()=>{a=!1,aw(r)};return a=!0,kt.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&&aw(r)})),idleTimeToLive:`10 millis`}),c=I(()=>n.columns??0),l=I(()=>n.rows??0),u=R(function*(){let n=yield*YC(),r=(t,r)=>{let i={input:Ri(t),key:{name:r.name??``,ctrl:!!r.ctrl,meta:!!r.meta,shift:!!r.shift}};$C(n,i),e(i)&&aw(n)},a=setInterval(()=>{},2147483647),o=()=>{clearInterval(a),aw(n)};return yield*Vp(()=>I(()=>{clearInterval(a),t.off(`keypress`,r),t.off(`end`,o)})),t.on(`keypress`,r),i?o():(yield*gE(s),t.once(`end`,o)),n}),d=Qf(()=>fw(r).pipe(B(Pi({onNone:()=>zp(sp(gE(s),dw(r))),onSome:F})),vp(()=>new ZO({}))));return $O({columns:c,rows:l,readInput:u,readLine:d,display:e=>Xp($f(t=>{n.write(e,e=>rn(e)?t(L):t(z(LT({module:`Terminal`,method:`display`,description:`Failed to write prompt to stdout`,cause:e}))))}))})}))(HN));function HN(e){let t=e.key;return t.name===`escape`||t.ctrl&&(t.name===`c`||t.name===`d`)}const Lue=/*#__PURE__*/ wf(Vk,/*#__PURE__*/ bf(kN,Gle,Pue,Fue,Iue)),Rue=(e,t)=>{let n=sle(e,Hue,t.middleware);return ap(e=>{let r=e.context;return F(function(i,a){let o=oa(r,dM,new zue(i,a)),s=rC(om(o)(n),t.scope);s.pollUnsafe()===void 0&&a.on(`close`,()=>{a.writableEnded||s.interruptUnsafe(e.id,Ij.annotation)})})})};var zue=class e extends bue{[uM];response;upgradeEffect;upgraded=!1;url;headersOverride;constructor(e,t,n,r=e.url,i,a){super(e,e=>new Nj({reason:new Pj({request:this,cause:e})}),a),this[uM]=uM,this.response=t,this.upgradeEffect=n,this.url=r,this.headersOverride=i}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=tg(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||=lm(Kp(kue(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return zN(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??z(new Nj({reason:new Pj({request:this,description:`not an upgradeable ServerRequest`})}))}toString(){return`ServerRequest(${this.method} ${Hg(this.url)})`}toJSON(){return AA(this,{_id:`HttpServerRequest`,method:this.method,url:Hg(this.originalUrl)})}};const Bue=/*#__PURE__*/ bf(Tue,Xse,Lue),Vue=/*#__PURE__*/ sj({status:101}),Hue=(e,t)=>{if(e.upgraded)return F(Vue);let n=e.resolvedResponse;if(n.writableEnded)return L;let r=t.headers;if(!Vh(t.cookies)){r={...r};let e=eg(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),sp(Uue(t.body),$f(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`?Xf({try:e=>hee(i.body,n,{signal:e,end:!0}),catch:n=>new Nj({reason:new Fj({request:e,response:t,description:`Error writing raw response`,cause:n})})}).pipe(Jp,xp(UN(n,t))):$f(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):$f(e=>{n.end(i.text??i.body,()=>e(L))});case`FormData`:return Qf(()=>{let a=new globalThis.Response(i.formData);return n.writeHead(t.status,t.statusText,{...r,...Object.fromEntries(a.headers)}),$f((r,i)=>{St.fromWeb(a.body,{signal:i}).pipe(n).on(`error`,n=>{r(z(new Nj({reason:new Fj({request:e,response:t,description:`Error writing FormData response`,cause:n})})))}).once(`finish`,()=>{r(L)})}).pipe(Jp,xp(UN(n,t)))});case`Stream`:{n.writeHead(t.status,t.statusText,r);let e=iC();return n.on(`drain`,()=>e.openUnsafe()),i.stream.pipe(BE,QE(t=>{let r=t.length>1?Buffer.concat(t):t[0];return n.write(r)?L:(e.closeUnsafe(),e.await)}),Jp,Op({onSuccess:()=>I(()=>n.end()),onFailure:UN(n,t)}))}}},Uue=e=>{let t=e._tag===`Raw`?e.body:void 0;return t instanceof St?I(()=>t.destroy()):L},UN=(e,t)=>n=>B(zj(n),([r,i])=>{let a=e.headersSent;return a||e.writeHead(r.status,r.statusText),e.writableEnded||e.end(),tp(a?cre(n,pd(t)):i)}),Wue={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},Gue=e=>Wue[e],WN=new TextEncoder,GN=new TextDecoder,KN=new TextDecoder(`utf-8`,{fatal:!0}),qN=2**32;function JN(...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 YN(e,t,n){if(t<0||t>=qN)throw RangeError(`value must be >= 0 and <= ${qN-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function XN(e){let t=Math.floor(e/qN),n=e%qN,r=/* @__PURE__ */ new Uint8Array(8);return YN(r,t,0),YN(r,n,4),r}function ZN(e){let t=/* @__PURE__ */ new Uint8Array(4);return YN(t,e),t}const Kue=/[^\x00-\x7f]/;function QN(e){if(typeof e==`string`&&e.length>=128){if(Kue.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return WN.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 que(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 Jue(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 $N(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}var eP=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)}},tP=class extends eP{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}},nP=class extends eP{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}},rP=class extends eP{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},iP=class extends eP{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},aP=class extends eP{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},oP=class extends eP{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},sP=class extends eP{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},cP=class extends eP{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},lP=class extends eP{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},uP=class extends eP{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},dP=class extends eP{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)}},fP=class extends eP{[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)}},pP=class extends eP{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},mP=class extends eP{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function hP(e){try{return Jue(typeof e==`string`?e:GN.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function gP(e){return que(typeof e==`string`?WN.encode(e):e,!0)}function _P(e,t){if(!(e instanceof Uint8Array))throw TypeError(`${t} must be an instance of Uint8Array`)}function vP(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 yP(e){return vP(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(vP)}function bP(...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 xP(e,t){if(e!==void 0)throw TypeError(`${t} can only be called once`)}function SP(e,t,n){try{return hP(e)}catch(e){throw new n(`Failed to base64url decode the ${t}`,{cause:e})}}function CP(e,t,n){try{return QN(e)}catch(e){throw new n(`The ${t} is not a valid base64url string`,{cause:e})}}function wP(e,t,n){let r;try{r=JSON.parse(KN.decode(hP(e)))}catch(e){throw new t(n,{cause:e})}if(!vP(r))throw new t(n);return r}const TP={__proto__:null,b64:!0},EP={__proto__:null};function DP(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 OP(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 kP(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 iP(`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 AP(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new sP(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}function jP(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(!vP(r))throw new e(`JOSE Header is not a JSON object`);return[r,n]}const Yue=e=>e[Symbol.toStringTag],Xue=(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 MP(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(vP(t)){if(o=KP(t),typeof o.kty!=`string`)throw BP(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(Xue(e,o,n),o.kty===`oct`)return hP(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!LP(t))throw BP(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${Yue(t)} instances must be of type "${e}" for the ${r} algorithm`);if(FP(t))return t;if(s=t,s.type===`secret`)return s.export()}NP||=/* @__PURE__ */ new WeakMap;let c=t,l=NP.get(c);if(l?.[r])return l[r];if(l||NP.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=Zue[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 JP(e,o)}let NP;const Zue={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`};function PP(e){if(!FP(e))throw Error(`CryptoKey instance expected`)}const FP=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},IP=e=>e?.[Symbol.toStringTag]===`KeyObject`,LP=e=>FP(e)||IP(e);function RP(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 zP=(e,...t)=>RP(`Key must be `,e,...t);function BP(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(RP(`Key for the ${e} algorithm must be `,t,...r))}const VP=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function HP(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function UP(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 WP(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw VP(t.name);if(t.hash&&r.hash?.name!==t.hash)throw VP(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw VP(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw VP(t.length,`algorithm.length`);HP(e,n)}function GP(e){return{__proto__:null,...e}}function KP(e){let t=GP(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 qP(e){if(e!==void 0&&typeof e!=`boolean`)throw TypeError(`"extractable" option must be a boolean`);return e}async function JP(e,t,n){if(!e.kty.includes(t.kty))throw new iP(`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 YP(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),WP(e,t,n),e}const XP=e=>crypto.getRandomValues(new Uint8Array(e.cekBits>>3));function ZP(e,t){let n=e.byteLength<<3;if(n!==t)throw new oP(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}const Que=e=>crypto.getRandomValues(new Uint8Array(e.ivBits>>3));function QP(e,t){if(t.length<<3!==e.ivBits)throw new oP(`Invalid Initialization Vector length`)}async function $P(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(zP(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 eF(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function $ue(e,t,n,r,i){let[a,o,s]=await $P(e,n,`encrypt`),c=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},a,t));return{ciphertext:c,tag:await eF(o,JN(i,r,c,XN(i.length*8)),s),iv:r}}async function ede(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 tde(e,t,n,r,i,a){let[o,s,c]=await $P(e,t,`decrypt`),l=await eF(s,JN(a,r,n,XN(a.length*8)),c);try{if(await ede(i,l))return new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},o,n))}catch{}throw new aP}async function tF(e,t,n,r,i){if(!FP(n)&&!(n instanceof Uint8Array))throw TypeError(zP(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(r?QP(e,r):r=Que(e),n instanceof Uint8Array&&ZP(n,e.cekBits),e.cbc)return $ue(e,t,n,r,i);let a=await YP(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 nF(e,t,n,r,i,a){if(!FP(t)&&!(t instanceof Uint8Array))throw TypeError(zP(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new oP(`JWE Initialization Vector missing`);if(!i)throw new oP(`JWE Authentication Tag missing`);if(!e.cbc&&i.length!==16)throw new oP(`Invalid Authentication Tag length`);if(QP(e,r),t instanceof Uint8Array&&ZP(t,e.cekBits),e.cbc)return tde(e,t,n,r,i,a);let o=await YP(t,e.subtle,`decrypt`);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:r,name:`AES-GCM`,tagLength:128},o,JN(n,i)))}catch{throw new aP}}function rF(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const nde=[[`encrypt`,`wrapKey`],[`decrypt`,`unwrapKey`]],rde=[[],[`deriveBits`]],iF=[[],[]];function aF(e){return{kty:[`RSA`],mode:`key-encryption`,subtle:{name:`RSA-OAEP`,hash:`SHA-${e}`},usages:nde,ops:[`wrapKey`,`unwrapKey`]}}function oF(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 iP(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);return{name:`ECDH`,namedCurve:t}},usages:rde,ops:[void 0,`deriveBits`]}}function sF(e,t=!1){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:t?`AES-GCM`:`AES-KW`,length:e},usages:iF,ops:t?[`encrypt`,`decrypt`]:[`wrapKey`,`unwrapKey`]}}function cF(){return{kty:[`oct`],mode:`key-wrapping`,secret:!0,subtle:{name:`PBKDF2`},usages:iF,ops:[`deriveBits`,`deriveBits`]}}const lF=rF({dir:{kty:[`oct`],mode:`direct-encryption`,secret:!0,subtle:{name:`AES-GCM`},usages:iF,ops:[`encrypt`,`decrypt`]},"RSA-OAEP":aF(1),"RSA-OAEP-256":aF(256),"RSA-OAEP-384":aF(384),"RSA-OAEP-512":aF(512),"ECDH-ES":oF(`direct-key-agreement`),"ECDH-ES+A128KW":oF(`key-agreement-with-key-wrapping`),"ECDH-ES+A192KW":oF(`key-agreement-with-key-wrapping`),"ECDH-ES+A256KW":oF(`key-agreement-with-key-wrapping`),A128KW:sF(128),A192KW:sF(192),A256KW:sF(256),A128GCMKW:sF(128,!0),A192GCMKW:sF(192,!0),A256GCMKW:sF(256,!0),"PBES2-HS256+A128KW":cF(),"PBES2-HS384+A192KW":cF(),"PBES2-HS512+A256KW":cF()}),ide=[`encrypt`,`decrypt`];function uF(e,t=!1){return{kty:[`oct`],secret:!0,subtle:{name:t?`AES-CBC`:`AES-GCM`,length:e},usages:iF,ops:ide,cekBits:e,ivBits:t?128:96,cbc:t}}const ade=rF({A128GCM:uF(128),A192GCM:uF(192),A256GCM:uF(256),"A128CBC-HS256":uF(256,!0),"A192CBC-HS384":uF(384,!0),"A256CBC-HS512":uF(512,!0)});function dF(e,t){throw new iP(`Invalid or unsupported "${e}" (JWE ${t}) header value`)}function fF(e){return(typeof e==`string`?lF[e]:void 0)??dF(`alg`,`Algorithm`)}function pF(e){return e.mode===`key-wrapping`||e.mode===`key-encryption`||e.mode===`key-agreement-with-key-wrapping`}function mF(e){return(typeof e==`string`?ade[e]:void 0)??dF(`enc`,`Encryption Algorithm`)}function hF(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`);HP(e,t)}async function ode(e,t,n){let r=await YP(t,fF(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 sde(e,t,n){let r=await YP(t,fF(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 gF(e,t,n){WP(t,fF(e).subtle,n),UP(e,t)}async function _F(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new oP(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new oP(`PBES2 Count Input must be a positive integer`);let i=JN(QN(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 YP(r,fF(t).subtle,`deriveBits`);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}function vF(e){return JN(ZN(e.length),e)}async function cde(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 $N(`sha256`,JN(ZN(t),e,n));a.set(r,(t-1)*32)}return a.slice(0,r)}async function yF(e,t,n,r,i=/* @__PURE__ */ new Uint8Array,a=/* @__PURE__ */ new Uint8Array){hF(e),hF(t,`deriveBits`);let o=JN(vF(QN(n)),vF(i),vF(a),ZN(r));return cde(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 bF(e){PP(e);let t=e.algorithm.namedCurve;if(t!==`P-256`&&t!==`P-384`&&t!==`P-521`&&e.algorithm.name!==`X25519`)throw new iP(`ECDH with the provided key is not allowed or not supported by your javascript runtime`)}function xF(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw new oP(`JOSE Header "${t}" (Agreement Party${t===`apu`?`U`:`V`}Info) invalid`);return SP(n,t,oP)}}function SF(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 oP(`JOSE Header "apu" and "apv" values must be distinct`)}}function lde(e){if(e===void 0)throw new oP(`JWE Encrypted Key missing`)}function CF(e){if(e!==void 0)throw new oP(`Encountered unexpected JWE Encrypted Key`)}function ude(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 dde(e,t,n,r,i,a){let{alg:o}=e,s=e.mode;if(s===`direct-encryption`)return CF(r),n;let c=s===`direct-key-agreement`;switch(c?CF(r):lde(r),e.subtle.name){case`ECDH`:{let{epk:r}=i;if(!vP(r)||[`d`,`k`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`priv`].some(e=>Object.hasOwn(r,e)))throw new oP(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);bF(n);let a=await JP(e,r),s=xF(i,`apu`),l=xF(i,`apv`);SF(s,l);let u=await yF(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 PP(n),gF(o,n,`decrypt`),new Uint8Array(await crypto.subtle.decrypt(`RSA-OAEP`,n,r));case`PBKDF2`:{if(typeof i.p2c!=`number`)throw new oP(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);ude(a);let e=a??1e4;if(i.p2c>e)throw new oP(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof i.p2s!=`string`)throw new oP(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);n=await _F(SP(i.p2s,`p2s`,oP),o,i.p2c,n);break}case`AES-GCM`:{if(typeof i.iv!=`string`)throw new oP(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof i.tag!=`string`)throw new oP(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let e=SP(i.iv,`iv`,oP),t=SP(i.tag,`tag`,oP);if(e.byteLength!==12)throw new oP(`Invalid Initialization Vector length`);if(t.byteLength!==16)throw new oP(`Invalid Authentication Tag length`);return nF(mF(o.slice(0,-2)),n,r,e,t,/* @__PURE__ */ new Uint8Array)}}return sde(o.slice(-6),n,r)}async function fde(e,t,n,r,i,a={}){let{alg:o,mode:s}=e,c=pF(e);if(i!==void 0&&!c)throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);let l=await MP(s===`direct-encryption`?t:e,n,`encrypt`);if(s===`direct-encryption`)return[l,void 0,void 0];let u=c?i??XP(t):void 0;u&&ZP(u,t.cekBits);let d,f;switch(e.subtle.name){case`ECDH`:{bF(l);let{apu:n,apv:i}=a;n!==void 0&&_P(n,`"apu"`),i!==void 0&&_P(i,`"apv"`);let c=n??xF(r,`apu`),u=i??xF(r,`apv`);SF(c,u);let d;d=a.epk===void 0?(await crypto.subtle.generateKey(l.algorithm,!0,[`deriveBits`])).privateKey:await MP(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 yF(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=gP(n)),i!==void 0&&(f.apv=gP(i)),y)return[b,void 0,f];l=b;break}case`RSA-OAEP`:PP(l),gF(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 _F(t,o,e,l),f={p2c:e,p2s:gP(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 tF(mF(o.slice(0,-2)),u,l,e,/* @__PURE__ */ new Uint8Array);d=t.ciphertext,f={iv:gP(t.iv),tag:gP(t.tag)}}}if(d??=await ode(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 wF(e,t){if(e.zip!==void 0&&e.zip!==`DEF`)throw new iP(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(e.zip!==void 0&&!t?.zip)throw new oP(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}function TF(e){if(typeof globalThis[e]>`u`)throw new iP(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function EF(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 oP(`Decompressed plaintext exceeded the configured limit`)}return JN(...i)}async function pde(e){return TF(`CompressionStream`),EF(new CompressionStream(`deflate-raw`),e)}async function mde(e,t){return TF(`DecompressionStream`),EF(new DecompressionStream(`deflate-raw`),e,t)}function hde(e){let{protected:t,ciphertext:n,iv:r,tag:i,aad:a}=e,o;return t!==void 0&&(o=wP(t,oP,`JWE Protected Header is invalid`)),[o,SP(n,`ciphertext`,oP),r===void 0?void 0:SP(r,`iv`,oP),i===void 0?void 0:SP(i,`tag`,oP),CP((t??``)+(a===void 0?``:`.${a}`),`aad`,oP)]}function gde(e){return[e&&DP(`keyManagementAlgorithms`,e.keyManagementAlgorithms),e&&DP(`contentEncryptionAlgorithms`,e.contentEncryptionAlgorithms),e?.crit,e?.maxPBES2Count,e?.maxDecompressedLength]}async function _de(e,t,n,r=hde(e)){let[i,a,o,s,c]=r,{header:l,unprotected:u,aad:d}=e,f;if(l!==void 0||u!==void 0){if(!bP(i,l,u))throw new oP(`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;kP(oP,EP,h,i,f),wF(f,i);let{alg:y,enc:b}=f;if(typeof y!=`string`||!y)throw new oP(`missing JWE Algorithm (alg) in JWE Header`);let x=lF[y];if(v===``&&(!x||!pF(x)))throw new oP(`JWE Encrypted Key incorrect type`);let S=x?.mode===`integrated-encryption`;if(!S&&(typeof b!=`string`||!b))throw new oP(`missing JWE Encryption Algorithm (enc) in JWE Header`);if(p&&!p.has(y)||!p&&y.startsWith(`PBES2`))throw new rP(`"alg" (Algorithm) Header Parameter value not allowed`);let ee;if(S){if(b!==void 0)throw new oP(`JWE "enc" (Encryption Algorithm) Header Parameter must not be present for integrated encryption`);if(o?.byteLength)throw new oP(`JWE Initialization Vector must be empty for integrated encryption`);if(s?.byteLength)throw new oP(`JWE Authentication Tag must be empty for integrated encryption`)}else{if(m&&!m.has(b))throw new rP(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);ee=mF(b)}let C;if(v!==void 0)try{C=SP(v,`encrypted_key`,oP)}catch(e){if(!x||!pF(x))throw e;C=/* @__PURE__ */ new Uint8Array}let te=!1;typeof n==`function`&&(n=await n(i,e),te=!0);let w=x??fF(y);pF(w)&&C===void 0&&(C=/* @__PURE__ */ new Uint8Array);let ne=await MP(w.mode===`direct-encryption`?ee:w,n,`decrypt`),T;if(w.mode===`integrated-encryption`)T=await w.decrypt(ne,C,a,c,i,f);else{let e=ee,t;try{t=await dde(w,e,ne,C,f,g),pF(w)&&t instanceof Uint8Array&&t.byteLength<<3!==e.cekBits&&(t=XP(e))}catch(n){if(n instanceof TypeError||n instanceof oP||n instanceof iP)throw n;t=XP(e)}T=await nF(e,t,a,o,s,c)}if(f.zip===`DEF`){let e=_??25e4;if(e===0)throw new iP(`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 mde(T,e).catch(e=>{throw e instanceof oP?e:new oP(`Failed to decompress plaintext`,{cause:e})})}return{plaintext:T,...i&&{protectedHeader:i},...d!==void 0&&{additionalAuthenticatedData:SP(d,`aad`,oP)},...u&&{sharedUnprotectedHeader:u},...l&&{unprotectedHeader:l},...te&&{key:ne}}}async function vde(e,t,n){if(e instanceof Uint8Array&&(e=GN.decode(e)),typeof e!=`string`)throw new oP(`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 oP(`Invalid Compact JWE`);return _de({ciphertext:o,iv:a||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n)}function DF(e,t,n){if(!bP(e,t,n))throw new oP(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`)}function yde(e,t,n=!1){if(!e[1]&&!e[2]&&!e[3])throw new oP(`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&&_P(o,`JWE Additional Authenticated Data`),s!==void 0&&_P(s,`JWE Content Encryption Key`),c!==void 0&&_P(c,`JWE Initialization Vector`),!n&&r!==void 0&&(r=jP(oP,r)[0],e[1]=r),i!==void 0&&(i=jP(oP,i)[0],e[2]=i),!n&&a!==void 0&&(a=jP(oP,a)[0],e[3]=a),l!==void 0&&!vP(l))throw TypeError(`JWE Key Management Parameters must be an object`);DF(r,i,a);let d={...r,...i,...a};OP(oP,r),kP(oP,EP,u,r,d),wF(d,r);let{alg:f,enc:p}=d;if(typeof f!=`string`||!f)throw new oP(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);let m=lF[f];if(m?.mode===`integrated-encryption`){if(p!==void 0)throw new oP(`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 oP(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);return[d,mF(p),m]}async function bde(e,t,n){let[r,i,a]=t,[o,s,c,l,u,d,f,p,,m]=e,h=s,g=c,_=a??fF(r.alg),v,y,b;_.mode===`integrated-encryption`?b=await MP(_,n,`encrypt`):[b,v,y]=await fde(_,i,n,r,d,p),y&&(m?g=g?{...g,...y}:y:h=h?{...h,...y}:y,DF(h,g,l));let x=h?gP(JSON.stringify(h)):``,S=u?.byteLength?gP(u):void 0,ee=QN(S?`${x}.${S}`:x),C=o;r.zip===`DEF`&&(C=await pde(C).catch(e=>{throw new oP(`Failed to compress plaintext`,{cause:e})}));let te,w,ne;_.mode===`integrated-encryption`?[v,te]=await _.encrypt(b,C,ee,h,r,p):{ciphertext:te,tag:w,iv:ne}=await tF(i,C,b,f,ee);let T={ciphertext:gP(te)};return ne&&(T.iv=gP(ne)),w&&(T.tag=gP(w)),v?.byteLength&&(T.encrypted_key=gP(v)),S&&(T.aad=S),h&&(T.protected=x),l&&(T.unprotected=l),g&&(T.header=g),T}async function xde(e,t,n){return bde(e,yde(e,n),t)}function Sde(e){return[e.protected,e.encrypted_key,e.iv,e.ciphertext,e.tag].join(`.`)}const OF=[[`verify`],[`sign`]];function kF(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:OF}}function AF(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:OF,minRsaBits:2048}}function jF(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:OF}}function MF(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:OF}}function NF(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:OF}}const PF=rF({HS256:kF(256),HS384:kF(384),HS512:kF(512),RS256:AF(256),RS384:AF(384),RS512:AF(512),PS256:AF(256,32),PS384:AF(384,48),PS512:AF(512,64),ES256:jF(`P-256`,256),ES384:jF(`P-384`,384),ES512:jF(`P-521`,512),EdDSA:MF(),Ed25519:MF(),"ML-DSA-44":NF(44),"ML-DSA-65":NF(65),"ML-DSA-87":NF(87)});function FF(e){let t=typeof e==`string`?PF[e]:void 0;if(!t)throw new iP(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function IF(e){return[e&&DP(`algorithms`,e.algorithms),e?.crit]}function Cde(e){return e===void 0?{}:wP(e,sP,`JWS Protected Header is invalid`)}function wde(e){try{return QN(e)}catch(e){throw new sP(`JWS Compact Serialization payload must use only ASCII characters`,{cause:e})}}async function Tde(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??Cde(a);if(!bP(c,o))throw new sP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=AP(c,kP(sP,TP,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new sP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new rP(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new sP(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new sP(`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=FF(d),h=JN(a===void 0?/* @__PURE__ */ new Uint8Array:QN(a),QN(`.`),typeof f==`string`?t[2]??=CP(f,`payload`,sP):f),g=SP(e.signature,`signature`,sP),_=await MP(m,n,`verify`),v=await YP(_,m.subtle,`verify`);m.minRsaBits&&UP(m.alg,v);let y=!1;try{y=await crypto.subtle.verify(m.signing,v,g,h)}catch(e){throw new mP(void 0,{cause:e})}if(!y)throw new mP;let b={payload:typeof f==`string`?SP(f,`payload`,sP):f};return a!==void 0&&(b.protectedHeader=c),o!==void 0&&(b.unprotectedHeader=o),p?[{...b,key:_},u]:[b,u]}async function LF(e,t,n){if(e instanceof Uint8Array&&(e=GN.decode(e)),typeof e!=`string`)throw new sP(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new sP(`Invalid Compact JWS`);return Tde({payload:i,protected:r,signature:a},t,n,wde)}async function RF(e,t,n){let[r]=await LF(e,IF(n),t);return r}const zF=e=>Math.floor(e.getTime()/1e3),Ede={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Dde=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,BF=`check_failed`;function VF(){throw TypeError(`Invalid time period format`)}function HF(e){typeof e!=`string`&&VF();let t=Dde.exec(e);(!t||t[4]&&t[1])&&VF();let n=parseFloat(t[2]),r=Math.round(n*Ede[t[3][0].toLowerCase()]);return Number.isFinite(r)||VF(),t[1]===`-`||t[4]===`ago`?-r:r}function UF(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}function WF(e,t){if(typeof t!=`string`)throw TypeError(`"${e}" claim must be a string`)}function Ode(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 GF(e,t){return typeof e==`number`?UF(t,e):e instanceof Date?UF(t,zF(e)):zF(/* @__PURE__ */ new Date)+HF(e)}const KF=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},kde=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function qF(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new tP(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function JF(e,t){throw new tP(`unexpected "${t}" claim value`,e,t,BF)}function YF(e,t,n={}){let r;try{r=JSON.parse(KN.decode(t))}catch(e){throw new cP(`JWT Claims Set must be a top-level JSON object`,{cause:e})}if(!vP(r))throw new cP(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||KF(e.typ)!==KF(i)))throw new tP(`unexpected "typ" JWT header value`,r,`typ`,BF);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 tP(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&JF(r,`iss`),s!==void 0&&r.sub!==s&&JF(r,`sub`),c!==void 0&&!kde(r.aud,typeof c==`string`?[c]:c)&&JF(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=HF(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}UF(`clockTolerance option`,f);let{currentDate:p}=n,m=UF(`currentDate option`,zF(p===void 0?/* @__PURE__ */ new Date:p)),h=qF(r,`iat`,l!==void 0),g=qF(r,`nbf`);if(g!==void 0&&g>m+f)throw new tP(`"nbf" claim timestamp check failed`,r,`nbf`,BF);let _=qF(r,`exp`);if(_!==void 0&&_<=m-f)throw new nP(`"exp" claim timestamp check failed`,r,`exp`,BF);if(l!==void 0){let e=m-h,t=UF(`maxTokenAge option`,typeof l==`number`?l:HF(l));if(e-f>t)throw new nP(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,BF);if(e<-f)throw new tP(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,BF)}return r}let XF;function ZF(e){return XF.get(e)}function QF(e){let t=ZF(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 WN.encode(JSON.stringify(t))}function $F(e,t){return ZF(e)[t]}var eI=class{constructor(e={}){if(!vP(e))throw TypeError(`JWT Claims Set MUST be an object`);(XF||=/* @__PURE__ */ new WeakMap).set(this,structuredClone(e))}setIssuer(e){return WF(`iss`,e),ZF(this).iss=e,this}setSubject(e){return WF(`sub`,e),ZF(this).sub=e,this}setAudience(e){return Ode(e),ZF(this).aud=e,this}setJti(e){return WF(`jti`,e),ZF(this).jti=e,this}setNotBefore(e){return ZF(this).nbf=GF(e,`setNotBefore`),this}setExpirationTime(e){return ZF(this).exp=GF(e,`setExpirationTime`),this}setIssuedAt(e){let t=ZF(this);return t.iat=e===void 0?zF(/* @__PURE__ */ new Date):typeof e==`string`?UF(`setIssuedAt`,zF(/* @__PURE__ */ new Date)+HF(e)):GF(e,`setIssuedAt`),this}};async function tI(e,t,n){let[r,i]=await LF(e,IF(n),t);if(!i)throw new cP(`JWTs MUST NOT use unencoded payload`);let a=YF(r.protectedHeader,r.payload,n);return{...r,payload:a}}async function nI(e,t,n){let{plaintext:r,...i}=await vde(e,gde(n),t),{protectedHeader:a}=i,o=YF(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 tP(`replicated "${e}" claim header parameter mismatch`,o,e,`mismatch`);return{payload:o,...i}}async function Ade(e,t,n){let[r,i,a,o]=e,s=``;if(i!==void 0){let e=jP(sP,i);i=e[0],s=gP(e[1])}if(a!==void 0&&(a=jP(sP,a)[0]),!i&&!a)throw new sP(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!bP(i,a))throw new sP(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let c={...i,...a};OP(sP,i);let l=AP(i,kP(sP,TP,o,i,c));l||n?.();let{alg:u}=c;if(typeof u!=`string`||!u)throw new sP(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let d=FF(u),f=``,p=r,m;if(l){let t=e[4];t?(f=t[0]??=gP(r),p=t[1]??=QN(f)):(f=gP(r),m=WN.encode(`${s}.${f}`))}m??=JN(QN(s),QN(`.`),p);let h=await YP(await MP(d,t,`sign`),d.subtle,`sign`);d.minRsaBits&&UP(d.alg,h);let g={signature:gP(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 jde(e,t,n,r,i){let[a]=await Ade([e,t,void 0,n],r,i);return`${a.protected}.${a.payload}.${a.signature}`}const Mde=eI;var rI=class extends Mde{#e;setProtectedHeader(e){return xP(this.#e,`setProtectedHeader`),this.#e=e,this}async sign(e,t){return jde(QF(this),this.#e,t?.crit,e,()=>{throw new cP(`JWTs MUST NOT use unencoded payload`)})}};const Nde=eI;var Pde=class extends Nde{#e=[void 0];#t;#n;#r;setProtectedHeader(e){return xP(this.#e[1],`setProtectedHeader`),this.#e[1]=e,this}setKeyManagementParameters(e){return xP(this.#e[7],`setKeyManagementParameters`),this.#e[7]=e,this}setContentEncryptionKey(e){return xP(this.#e[5],`setContentEncryptionKey`),this.#e[5]=e,this}setInitializationVector(e){return xP(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=QF(this);this.#e[1]&&(this.#t||this.#n||this.#r)&&(this.#e[1]={...this.#e[1],iss:this.#t?$F(this,`iss`):void 0,sub:this.#n?$F(this,`sub`):void 0,aud:this.#r?$F(this,`aud`):void 0});let r=[...this.#e];return r[0]=n,Sde(await xde(r,e,t))}};function iI(e=`JWK "alg" (Algorithm) Parameter`){throw new iP(`Invalid or unsupported ${e} value`)}function aI(e,t){return(typeof e==`string`?PF[e]??lF[e]:void 0)??iI(t)}async function oI(e){if(IP(e)){if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`})}if(e instanceof Uint8Array)return{kty:`oct`,k:gP(e)};if(!FP(e))throw TypeError(zP(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 sI=(e,t)=>{if(typeof e!=`string`||!e)throw new lP(`${t} missing or invalid`)};async function cI(e,t){let n;if(vP(e)){if(n=GP(e),typeof n.kty!=`string`)throw TypeError(zP(e,`CryptoKey`,`KeyObject`,`JSON Web Key`))}else if(LP(e))n=GP(await oI(e));else throw TypeError(zP(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`:sI(n.alg,`"alg" (Algorithm) Parameter`),sI(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:sI(n.crv,`"crv" (Curve) Parameter`),sI(n.x,`"x" (X Coordinate) Parameter`),sI(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:sI(n.crv,`"crv" (Subtype of Key Pair) Parameter`),sI(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:sI(n.e,`"e" (Exponent) Parameter`),sI(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 lP(`"k" (Key Value) Parameter missing or invalid`);r={k:n.k,kty:n.kty};break;default:throw new iP(`"kty" (Key Type) Parameter missing or unsupported`)}let i=QN(JSON.stringify(r));return gP(await $N(t,i))}function Fde(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 lI(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=JP(n,t,!0).then(e=>{if(e.type!==`public`)throw new uP(`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 uI(e){let t;try{t=structuredClone(e)}catch(e){throw new uP(`JSON Web Key Set malformed`,{cause:e})}if(!yP(t))throw new uP(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=GP(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`?PF[a]:void 0;if(!s||s.secret)throw new iP(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Fde(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new dP;if(u!==1){let e=new fP;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await lI(r,e,s)}catch{}},e}return lI(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Ide(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let dI;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(dI=`jose/v6.2.13`);const Lde=/* @__PURE__ */ Symbol();async function Rde(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 pP(void 0,{cause:e}):e});if(i.status!==200)throw new eP(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch(e){throw new eP(`Failed to parse the JSON Web Key Set HTTP response as JSON`,{cause:e})}}const zde=/* @__PURE__ */ Symbol();function fI(e,t){return Number.isFinite(e)&&Date.now()<e+t}function pI(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function Bde(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=pI(r.cooldownDuration,3e4,`cooldownDuration`),s=pI(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);dI&&!c.has(`User-Agent`)&&c.set(`User-Agent`,dI),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[Lde],u=r[zde],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;fI(e,s)&&yP(t)&&(d=e,h=uI(t))}let g=async()=>{if(f&&Ide()&&(f=void 0),!f){let e=++p,t=f=Rde(n,c,AbortSignal.timeout(a),l).then(t=>{let n=uI(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||!fI(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof dP&&!fI(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>fI(d,o),enumerable:!0},fresh:{get:()=>fI(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}async function mI(e,t,n){if(!vP(e))throw TypeError(`JWK must be an object`);let r=KP(e),i=qP(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 hP(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 JP(aI(t),r,i);case`RSA`:case`EC`:case`OKP`:return JP(aI(t),r,i);default:throw new iP(`Unsupported "kty" (Key Type) Parameter value`)}}function hI(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 wP(t,TypeError,n)}function gI(e){if(typeof e!=`string`)throw new cP(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new cP(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new cP(`Invalid JWT`);if(!t)throw new cP(`JWTs must contain a payload`);let r;try{r=hP(t)}catch(e){throw new cP(`Failed to base64url decode the payload`,{cause:e})}let i;try{i=JSON.parse(KN.decode(r))}catch(e){throw new cP(`Failed to parse the decoded payload as JSON`,{cause:e})}if(!vP(i))throw new cP(`Invalid JWT Claims Set`);return i}function Vde(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||!Number.isInteger(t)||t<2048)throw new iP(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Hde(e,t){let n=qP(t?.extractable),r=aI(e,`"alg" (Algorithm)`);r.secret&&iI(`"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 iP(`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 iP(`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:Vde(t)}:r.subtle}return crypto.subtle.generateKey(i,n??!1,[...r.usages[1],...r.usages[0]])}const _I=`key-list+jwt`,Ude=W({keys:G(W({id:U,sealed:U}))}),vI=SS(W({keyId:_S,ownerId:_S,scopes:G(_S),expiresAt:Zx(cS)})),yI=new TextEncoder,Wde=async e=>new Uint8Array(await crypto.subtle.digest(`SHA-256`,yI.encode(e))),bI=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:yI.encode(`clankerauth key list\0${t}`)},n,512));return{id:gP(r.subarray(0,32)),key:await crypto.subtle.importKey(`raw`,r.subarray(32),`AES-GCM`,!1,[`encrypt`,`decrypt`])}},Gde=async(e,t,n)=>{let{id:r,key:i}=await bI(e,t),a=crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12)),o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:a},i,yI.encode(kx(vI)(n))),s=new Uint8Array(a.length+o.byteLength);return s.set(a),s.set(new Uint8Array(o),a.length),{id:r,sealed:gP(s)}},Kde=async(e,t,n)=>{let r=await bI(await Wde(e),t),i=n.get(r.id);if(i===void 0)return;let a=new Uint8Array(hP(i)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.subarray(0,12)},r.key,a.subarray(12));return Tx(vI)(new TextDecoder().decode(o))},xI=Symbol.for(`@gjermundgaraba/effect-actions/Anyone`),SI=(e,t)=>{for(let n of e)if(n.caller!==xI&&(t===void 0||n.caller.key!==t.identity.key))throw Error(`Protected action '${n.name}' requires its matching authentication descriptor`)},CI=e=>U.pipe(eS(F(e))),qde=W({path:G(K([U,cS])),message:U}),Jde=I_();var wI=class e extends qS()(`InvalidInput`,{message:CI(`The input does not match the action's input.`),issues:G(qde).pipe(eS(F([])))},{httpApiStatus:400}){static fromSchemaError=({issue:t,message:n})=>new e({message:n,issues:Jde(t).issues.map(e=>({path:(e.path??[]).map(e=>{let t=Qt(e)?e:e.key;return Zt(t)?String(t):t}),message:e.message}))})},TI=class extends qS()(`Unauthenticated`,{message:CI(`Authentication is required.`)},{httpApiStatus:401}){};const EI=/^[\x21\x23-\x5B\x5D-\x7E]+$/,Yde=U.check(sS(EI));var DI=class extends qS()(`Forbidden`,{message:CI(`Not allowed.`),scopes:Mx(Jx(Yde))},{httpApiStatus:403}){};const OI=[TI,DI],Xde=K(OI),kI=[wI,...OI];K(kI);const Zde=/^[A-Za-z0-9_-]{1,128}$/,Qde=(e,t)=>{if(!Zde.test(t)||t===`then`)throw Error(`Invalid ${e}: ${t}`)},AI=(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)}},jI=(e,t)=>AI(e,t,e=>e.name),$de=(e,t,n)=>{let r=t.filter(e=>!n.includes(e));if(r.length>0)throw Error(`Unknown ${e}: ${r.join(`, `)}`)},MI=e=>Ev(e)?MI(e.thunk()):e,NI=e=>{let t=MI(e);return Tv(t)?t.types.flatMap(NI):[t]},efe=e=>xv(e)?[e.literal]:Lie(e)?e.enums.map(([,e])=>e):[void 0],PI=e=>e===void 0?[]:jx(e)?[e]:e,FI=(e,t=[])=>[.../* @__PURE__ */ new Set([...kI,...e.error,...t])],tfe=(e,t)=>FI(e,e.caller===xI||t.authentication===void 0?t.error:[...t.error,...t.authentication.error]),II=e=>NI(Jy(e)).flatMap(e=>{let t=wv(e)?e.propertySignatures.find(e=>e.name===`_tag`)?.type:void 0;return t===void 0?[]:NI(t).flatMap(efe).filter(Jt)}),nfe=new Set(kI.flatMap(e=>II(e.ast))),LI=(e,t)=>{let n=t.flatMap(e=>II(e.ast)).find(e=>nfe.has(e));if(n!==void 0)throw Error(`${e}: error _tag "${n}" is built in, and declared on every surface`)},rfe=(e,t,n)=>{jI(`action`,t);let r=PI(n.error);return LI(e,r),SI(t,n.authentication),{error:r,authentication:n.authentication}},ife=()=>Math.random().toString(36).slice(2),RI=e=>{let t=P(`effect-actions/Implementation/${ife()}`);return{key:t,layer:pf(t,e)}};var zI=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!==xI)?xf(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!==xI)?yield*r.#t.key:()=>L;return n.flatMap(n=>e.flatMap(([e,r])=>e===n?[[n,sfe(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 BI=e=>Aa(e),VI=(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(`, `)}`)}},HI=(e,t)=>t===void 0?e:(VI(`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]:[zI.share(n,e)]})),afe=(e,t,n,r)=>{r!==void 0&&VI(`the binding does not hold it`,r,t);let i=n.flatMap(e=>e.actions),a=HI(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 jI(`served action`,o),a},ofe=(e,t,n,r)=>{let i=afe(e,t.actions,BI(n),r.actions),a=i.flatMap(e=>e.actions);return SI(a,t.authentication),AI(`middleware`,r.middleware??[],e=>e.key),{apps:i,actions:a,authentication:a.some(e=>e.caller!==xI)?t.authentication:void 0}},UI=e=>t=>{let[n,...r]=e.map(e=>zI.layerOf(e));return n===void 0?t:Cf(t,bf(n,...r))},WI=e=>V(qf(e,e=>zI.boundOf(e)),e=>e.flat()),sfe=(e,t,n)=>{let r={"action.name":e.name,"action.read_only":e.readOnly},i=e.caller===xI?L:B(Fp(e.caller),e=>Ni(e)?L:z(new TI)),a=e.caller===xI?L:Qf(()=>n(e)),o=Cx(Px(K(FI(e)))),s=(e,t)=>{let n=ta(e.annotations);return[hd(e.error).annotate(n),hd(_d(t)).annotate(n)]},c=H(function*(e){let t=[];for(let n of e.reasons)if(dd(n)){let e=yield*up(o(n.error));t.push(...Nd(e)?[n]:s(n,e.cause))}else t.push(n);return yield*tp(fd(t))});return n=>zp(i.pipe(sp(a),sp(Qf(()=>t(n))),hp(c))).pipe(vm(r),em(e.name,{attributes:r},{captureStackTrace:!1}))},GI={errors:`all`,onExcessProperty:`error`},KI=`effect-actions/media`,qI=W({data:DS,mimeType:U});qI.annotate({[KI]:`image`});const JI=e=>e.annotations?.[KI]===`image`,YI=e=>JI(e)&&e.encoding===void 0?`image`:void 0,cfe=Gx(U,Lx),XI=e=>jx(e)?e:Reflect.ownKeys(e).length===0?cfe:W(e);function ZI(e,t){Qde(`action name`,e);let{caller:n,readOnly:r}=t;if(n!==xI&&!tte(n))throw Error(`Missing caller: declare Action.Anyone or an identity service key`);if(n!==xI&&ra(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:XI(t.input??{}),success:t.success===void 0?Hx:XI(t.success),error:PI(t.error),readOnly:r,mcp:{...t.mcp}};return LI(`Action "${i.name}"`,i.error),i}const lfe=()=>L,QI=e=>{if(!$t(e))throw Error(`Missing authorize: pass an authorization function, or Action.allowAll`);return e},ufe=e=>{if(e===void 0)throw Error(`Protected actions require authorize, or Action.allowAll`);return e},dfe=e=>{if(e!==void 0)throw Error(`A public-only target takes no authorize`);return lfe},ffe=e=>RI(Gf(e)?V(e,QI):F(QI(e)));function $I(e,t,n){let r=Aa(e),i=r.map(e=>e.name);jI(`action`,r);let a=ffe(r.some(e=>e.caller!==xI)?ufe(n?.authorize):dfe(n?.authorize)),o=t=>{let n=$t(t)?Object.fromEntries(Array.isArray(e)?[]:r.map(({name:e})=>[e,t])):t;$de(`handlers`,Object.keys(n),i);let a=r.flatMap(e=>{let t=Object.hasOwn(n,e.name)?n[e.name]:void 0;return $t(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=Gf(t)?V(t,o):F(o(t));return new zI(r,RI(s),a)}const eL=e=>B(Pp(e[`~provider`]),t=>t.descriptor===e?F(t):rp(/* @__PURE__ */ Error(`Authentication "${e.name}": the binding's descriptor is not its provider's; build both from one descriptor`))),pfe=(e,t)=>B(Fp(e[`~verified`]),n=>Ni(n)?Lp(t,e.identity,n.value):z(new TI)),tL=ob(`httpApiStatus`),nL=e=>tL(e)??(Ev(e)?nL(e.thunk()):void 0),rL=e=>{let t=nL(e.ast);if(t!==void 0)return[tL(e.ast)===void 0?e.annotate({httpApiStatus:t}):e];let n=MI(e.ast);return Tv(n)&&n.checks===void 0&&n.encoding===void 0?n.types.flatMap(e=>rL(Ax(e))):[e.annotate({httpApiStatus:422})]},mfe={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: ${_o(e.duration)}\n\n`}}};function iL(e){let t=typeof e==`string`?Gue(e):e;return e=>e.annotate({httpApiStatus:t})}const hfe=/*#__PURE__*/ (e=>Hx.pipe(iL(e)))(204),aL=e=>jx(e)&&N(e,`~effect/http-api/HttpApiSchema/Stream`),oL=e=>aL(e)&&e._tag===`StreamSse`,gfe=e=>aL(e)&&e._tag===`StreamUint8Array`,sL=`~effect/http-api/HttpApiSchema/WithHeaders`,_fe=e=>N(e,`~effect/http-api/HttpApiSchema/WithHeadersValue`),cL=e=>jx(e)&&N(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function vfe(e,t,n){return Ax(e.ast,{[sL]:sL,schema:t,headers:n})}function lL(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??uL(t._tag)}})}function uL(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 dL(e){return t=>lL(t,{_tag:`Json`,...e})}function fL(e){return t=>lL(t,{_tag:`FormUrlEncoded`,...e})}const pL=e=>{if(bv(e))return!0;let t=Jy(e);if(bv(t))return!0;let n=e.encoding?.[0].to;return n!==void 0&&bv(n)},mL=/*#__PURE__*/ ob(`~httpApiEncoding`),hL=/*#__PURE__*/ ob(`~httpApiWithHeaders`),gL=/*#__PURE__*/ ob(`httpApiStatus`),_L={_tag:`Json`,contentType:`application/json`},vL={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function yL(e){return mL(e)??_L}function bL(e,t){return mL(e)||(gA(t)?_L:vL)}function xL(e){let t=yL(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function SL(e){return gL(e)??200}function CL(e){return cL(e)?gL(e.ast)??SL(e.schema.ast):SL(e.ast)}function wL(e){return cL(e)&&mL(e.ast)===void 0?xL(e.schema.ast):xL(e.ast)}function TL(e){return gL(e)??500}function EL(e){return cL(e)?gL(e.ast)??TL(e.schema.ast):TL(e.ast)}function DL(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}const OL=`~effect/http-api/HttpApiEndpoint`;function kL(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function AL(e){let t=Array.from(e.success);return Ma(t)?t:[hfe]}function jL(e){let t=new Set(e.error),n=e.disableCodecs?M:BL;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}const ML={[OL]:OL,pipe(){return jt(this,arguments)},prefix(e){return PL({...NL(this),path:kM(this.path,e)})},middleware(e){return PL({...NL(this),middlewares:/* @__PURE__ */ new Set([...this.middlewares,e])})},annotate(e,t){return PL({...NL(this),annotations:oa(this.annotations,e,t)})},annotateMerge(e){return PL({...NL(this),annotations:ha(this.annotations,e)})}},NL=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 PL(e){function t(){}return Object.setPrototypeOf(t,ML),Object.assign(t,e)}const FL=e=>(t,n,r)=>{let i=r?.disableCodecs??!1,a=i?M:XS;return PL({identifier:t,path:n,method:e,params:IL(r?.params,a),query:IL(r?.query,a),headers:IL(r?.headers,a),payload:LL(r?.payload,e,i),success:zL(r?.success,e,i),error:VL(r?.error,i),annotations:ia(),middlewares:/* @__PURE__ */ new Set,disableCodecs:i})};function IL(e,t){if(e!==void 0)return jx(e)?t(e):t(W(e))}function LL(e,t,n){let r=/* @__PURE__ */ new Map;if(e===void 0)return r;let i=Array.isArray(e)?e:jx(e)?[e]:[W(e).pipe(fL())],a=n?M:ZL;for(let e of i){let n=bL(e.ast,t),i=DL(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 RL=`effect/http-api/stream/failure`;function zL(e,t,n){if(e===void 0)return/* @__PURE__ */ new Set;let r=Aa(e);return HL(r,t),new Set(n?r:r.map(BL))}const BL=/*#__PURE__*/ Vt(e=>aL(e)?e:cL(e)?vfe(e,aL(e.schema)?e.schema:XL(e.schema,wL(e)),XS(e.headers)):YL(e));function VL(e,t){if(e===void 0)return/* @__PURE__ */ new Set;let n=Aa(e);for(let e of n){let t=cL(e)?e.schema:e;if(aL(t))throw Error(`Streaming schemas are not supported in error responses`)}return WL(n,EL),new Set(t?n:n.map(BL))}function HL(e,t){let n=!1,r=/* @__PURE__ */ new Map;for(let i of e){let e=cL(i)?i.schema:i,a=CL(i);if(aL(e)){if(GL(e,t),n)throw Error(`Multiple streaming success responses are not supported`);n=!0;let i=UL(r,a);if(i.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(i.bufferedContentTypes.has(DL(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=UL(r,a),n=pL(e.ast);if(t.stream!==void 0){if(n)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=wL(i);if(DL(e.contentType)===DL(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}n||t.bufferedContentTypes.add(DL(wL(i).contentType)),t.noContent=t.noContent||n}}WL(e,CL)}function UL(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:/* @__PURE__ */ new Set,noContent:!1},e.set(t,n)),n}function WL(e,t){let n=/* @__PURE__ */ new Map;for(let r of e){let e=t(r),i=hL(r.ast),a=cL(r)?r.schema:i?.body??r,o=pL(a.ast)?``:DL(aL(a)?a.contentType:wL(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(cL(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 GL(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(oL(e)&&KL(e.events.ast))throw Error(`SSE event name is reserved: ${RL}`)}function KL(e){return qL(Jy(e),/* @__PURE__ */ new Set)}function qL(e,t){if(t.has(e))return!1;if(t.add(e),Tv(e))return e.types.some(e=>qL(e,t));if(Ev(e))return qL(e.thunk(),t);if(!wv(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&JL(n.type,t)}function JL(e,t){if(t.has(e))return!1;t.add(e);let n=Jy(e);return n===e?xv(e)?e.literal===RL:Tv(e)?e.types.some(e=>JL(e,t)):Ev(e)?JL(e.thunk(),t):!1:JL(n,t)}function YL(e){let t=xL(e.ast),n=hL(e.ast);return n===void 0?XL(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:XL(n.body,t),headersCodec:XS(n.headers)}})}function XL(e,t){switch(t._tag){case`Json`:return YS(e);case`FormUrlEncoded`:return XS(e);case`Text`:case`Uint8Array`:return e}}function ZL(e,t){switch(bL(e.ast,t)._tag){case`Json`:return YS(e);case`FormUrlEncoded`:return XS(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}const QL=/*#__PURE__*/ FL(`POST`),$L=`~effect/http-api/HttpApi`,eR={[$L]:$L,pipe(){return jt(this,arguments)},add(...e){let t={...this.groups};for(let n of e)or(t,n.identifier,n);return nR({...tR(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];or(t,n,r.annotateMerge(ha(e.annotations,r.annotations)))}return nR({...tR(this),groups:t})},prefix(e){return nR({...tR(this),groups:Ea(this.groups,t=>t.prefix(e))})},middleware(e){return nR({...tR(this),groups:Ea(this.groups,t=>t.middleware(e))})},annotate(e,t){return nR({...tR(this),annotations:oa(this.annotations,e,t)})},annotateMerge(e){return nR({...tR(this),annotations:ha(this.annotations,e)})}},tR=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),nR=e=>{function t(){}return Object.setPrototypeOf(t,eR),Object.assign(t,e)},rR=e=>nR({identifier:e,groups:{},annotations:ia()}),iR=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=ha(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:ha(n,e.annotations),successes:aR(AL(e),CL),errors:aR(jL(e),EL)})}},aR=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach(r),n;function r(e){let r=cL(e)?e.schema:e;if(aL(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}};var oR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/AdditionalSchemas`)){},sR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParseOptions`)){},cR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ParamsParseOptions`)){},lR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/QueryParseOptions`)){},uR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/HeadersParseOptions`)){},dR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/PayloadParseOptions`)){},fR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/SuccessParseOptions`)){},pR=class extends (/*#__PURE__*/ P()(`effect/http-api/HttpApi/ErrorParseOptions`)){};const mR=e=>{let t=ca(e,sR);return{params:ca(e,cR)??t,query:ca(e,lR)??t,headers:ca(e,uR)??t,payload:ca(e,dR)??t,success:ca(e,fR)??t,error:ca(e,pR)??t}},hR=/*#__PURE__*/ sj({status:400}),gR=/*#__PURE__*/ sj({status:500}),_R=`~effect/http-api/HttpApiError/HttpApiSchemaError`;var vR=class e extends (/*#__PURE__*/ Io(`HttpApiSchemaError`)){[_R]=_R;get[lO](){return this.kind!==`Body`&&this.kind!==`ResponseHeaders`}static is(e){return N(e,_R)}static wrap(t,n){return xm(n,n=>new e({kind:t,cause:n}))}name=`HttpApiSchemaError`;message=this.kind;[Aj](){return F(this[`~effect/ErrorReporter/ignore`]?hR:gR)}};const yR=`~effect/http-api/HttpApiMiddleware`,bR=`~effect/http-api/HttpApiMiddleware/Security`,xR=e=>N(e,bR),SR=()=>(e,t)=>{let n=nr(),r;n!==0&&(rr(2),r=new globalThis.Error,rr(n));class i extends P()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[yR]=yR,a.error=CR(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[bR]=bR,a.security=t.security}return a};function CR(e){return e===void 0?/* @__PURE__ */ new Set:new Set(Array.isArray(e)?e:[e])}const wR=(e,t)=>uf(e,(e,n)=>pp(e,e=>vR.is(e)?t(e,n):z(e))),TR=/*#__PURE__*/ new Set;function ER(e){if(e===void 0)return TR;let t=My(e.ast);return wv(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function DR(e,t){if(t===void 0||!e.includes(`:`))return e;let n=ER(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 OR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Identifier`)){},kR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Title`)){},AR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Version`)){},jR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Description`)){},MR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/License`)){},NR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/ExternalDocs`)){},PR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Servers`)){},FR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Format`)){},IR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Summary`)){},LR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Deprecated`)){},RR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Override`)){};const zR=/*#__PURE__*/ _a(`effect/http-api/OpenApi/Exclude`,{defaultValue:It});var BR=class extends (/*#__PURE__*/ P()(`effect/http-api/OpenApi/Transform`)){};const VR={},HR=/*#__PURE__*/ new WeakMap,UR=e=>{if(Array.isArray(e))return e.map(UR);if(typeof e==`object`&&e&&!Object.isFrozen(e)){let t={};for(let n of Object.keys(e))or(t,n,UR(e[n]));return t}return e};function WR(e,t,n){let r=ma(e,t);Ni(r)&&n(r.value)}function GR(e,t){let n=t??VR,r=HR.get(n);r===void 0&&(r=/* @__PURE__ */ new WeakMap,HR.set(n,r));let i=r.get(e);if(i!==void 0)return UR(i);let a=KR(e,n);return r.set(e,UR(a)),a}function KR(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:nz(e,t),target:n}),n}WR(e.annotations,kR,e=>{n.info.title=e}),WR(e.annotations,AR,e=>{n.info.version=e}),WR(e.annotations,jR,e=>{n.info.description=e}),WR(e.annotations,MR,e=>{n.info.license=e}),WR(e.annotations,IR,e=>{n.info.summary=e}),WR(e.annotations,PR,e=>{n.servers=[...e]}),iR(e,{onGroup({group:e}){if(da(e.annotations,zR))return;let t={name:sa(e.annotations,kR,()=>e.identifier)};WR(e.annotations,jR,e=>{t.description=e}),WR(e.annotations,NR,e=>{t.externalDocs=e}),WR(e.annotations,RR,e=>{for(let[n,r]of Object.entries(e))or(t,n,r)}),WR(e.annotations,BR,e=>{t=e(t)}),n.tags.push(t)},onEndpoint({endpoint:e,group:t,mergedAnnotations:c,middleware:l}){if(da(c,zR))return;let u={tags:[sa(t.annotations,kR,()=>t.identifier)],operationId:sa(e.annotations,OR,()=>t.topLevel?e.identifier:`${t.identifier}.${e.identifier}`),parameters:[],security:[],responses:{}},d=ER(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();or(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??={},or(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,ay),a=i.length===1?i[0]:new hy(i);u.responses[n].content??={},or(u.responses[n].content,r,{schema:s(a,t)})})}),c!==void 0&&c.forEach((e,t)=>{u.responses[n].content??={},oL(e)?or(u.responses[n].content,t,{schema:s(e.events.ast),"x-effect-stream":{encoding:`sse`,causeSchema:s(AS(e.error,bS()).ast),errorSchema:s(e.error.ast),failureEvent:ZR}}):or(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})}})}WR(e.annotations,jR,e=>{u.description=e}),WR(e.annotations,IR,e=>{u.summary=e}),WR(e.annotations,LR,e=>{u.deprecated=e}),WR(e.annotations,NR,e=>{u.externalDocs=e}),l.forEach(e=>{if(xR(e))for(let[t,n]of Object.entries(e.security))v(t,n),u.security.push({[t]:[]})});function v(e,t){let r=iz(t);if(!Object.hasOwn(n.components.securitySchemes,e))or(n.components.securitySchemes,e,r);else if(!An(az(n.components.securitySchemes[e]),az(r)))throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${e}`)}let y=gA(e.method);if(y){let t=/* @__PURE__ */ new Map;for(let n of kL(e)){if(pL(n.ast))continue;let r=bL(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(ay);or(e,n,{schema:s(t.length===1?t[0]:new hy(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(QR(e),()=>`Success`),g($R(jL(e),EL,ez),()=>`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)||or(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];WR(e.annotations,RR,e=>{for(let[t,r]of Object.entries(e))or(n,t,r)}),WR(e.annotations,BR,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})}}),WR(e.annotations,oR,e=>{e.forEach(e=>{let t=sb(e.ast);if(t!==void 0){if(Object.hasOwn(n.components.schemas,t))throw new globalThis.Error(`Duplicate component schema identifier: ${t}`);or(n.components.schemas,t,s(e.ast))}})}),qR(r,t,n.components.schemas);for(let e of o)e();return Object.keys(n.components.schemas).forEach(e=>{if(!zb.test(e))throw new globalThis.Error(`Invalid component schema key: ${e}`)}),WR(e.annotations,RR,e=>{for(let[t,r]of Object.entries(e))or(n,t,r)}),WR(e.annotations,BR,e=>{n=e(n)}),n}function qR(e,t,n){if(!Ma(e))return;let r=dx(Ia(e,e=>e.ast),t),i=Ia(r.representations,(t,n)=>{let i=e[n];return i._tag===`schema`?t:JR(t,r.references,i.select)}),a=Kae(goe({representations:i,references:XR(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`){sr(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))or(n,e,t)}function JR(e,t,n){let r=YR(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 YR(e,t,n=/* @__PURE__ */ new Set){if(e._tag===`Suspend`)return YR(e.thunk,t,n);if(e._tag!==`Reference`||n.has(e.$ref))return e;let r=t[e.$ref];return r===void 0?e:YR(r,t,new Set(n).add(e.$ref))}function XR(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;or(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 ZR=`effect/http-api/stream/failure`;function QR(e){return $R(AL(e),CL,ez)}function $R(e,t,n){let r=/* @__PURE__ */ new Map;return e.forEach(i),r;function i(e){let i=hL(e.ast),c=cL(e)?e.schema:i?.body??e,l=cL(e)?e.headers:i?.headersCodec,u=t(e),d=c.ast;aL(c)?s(c,u):pL(d)?a(u,n(e.ast)??n(d)??`<No Content>`):o(c,u,wL(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 ez(e){return yae(e)??sb(e)}const tz=/*#__PURE__*/ U.annotate({format:`binary`});function nz(e,t){switch(t){case`Uint8Array`:return tz.ast;case`Text`:return yv(e)&&e.encoding===void 0?U.ast:e;case`Multipart`:e=rz(e)}return Gb(e)}function rz(e){return yv(e)&&e.annotations?.representation?.id===`effect/http/PersistedFile`?tz.ast:typeof e?.recur==`function`?e.recur(rz):e}const iz=e=>{let t={};switch(WR(e.annotations,jR,e=>{t.description=e}),e._tag){case`Basic`:return{...t,type:`http`,scheme:`basic`};case`Http`:{let n=ma(e.annotations,FR).pipe(Vi(e=>({bearerFormat:e})),zi);return{...t,type:`http`,scheme:e.scheme,...n}}case`ApiKey`:return{...t,type:`apiKey`,name:e.key,in:e.in}}},az=e=>e.type===`http`?{...e,scheme:e.scheme.toLowerCase()}:e.in===`header`?{...e,name:e.name.toLowerCase()}:e,oz=(e,t)=>CM(H(function*(n){let r=yield*Ap(),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*rp(`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=Vt(e=>fj(GR(e)));yield*n.add(`GET`,t.openapiPath,I(()=>r(e)))}})),sz=(e,t,n)=>hf(R(function*(){let r=(yield*Ap()).pipe(ga(Kd)),i=e.groups[t],a=n(mz(i)),o=Gf(a)?yield*a:a,s=[];for(let t of o.handlers.values())s.push(vz(e,i,t,r));return ta(/* @__PURE__ */ new Map([[i.key,{routes:s,handlers:o.handlers}]]))})),cz=`~effect/http-api/HttpApiBuilder/Handlers`,lz=e=>{switch(e._tag){case`Http`:return V(dM,t=>sg(dz(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`?Xce(n):Zce(n);return Dp(r,{onFailure:()=>sg(``),onSuccess:e=>sg(e[t])})}case`Basic`:{let e={username:``,password:sg(``)};return V(dM,t=>{let n=dz(t.headers.authorization,uz);if(n===void 0)return e;let r=lte(xh(n));if(r===void 0)return e;let i=r.indexOf(`:`);return i===-1?e:{username:r.slice(0,i),password:sg(r.slice(i+1))}})}}},uz=`Basic`;function dz(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 fz=(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},pz={[cz]:cz,pipe(){return jt(this,arguments)},handle(e,t,n){return fz(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;fz(this,t,e,!1,r)}return this},handleRaw(e,t,n){return fz(this,e,t,!0,n)}},mz=e=>{let t=Object.create(pz);return t.group=e,t.handlers=/* @__PURE__ */ new Map,t};function hz(e,t){let n=/* @__PURE__ */ new Map;return e.forEach(({encoding:e,schemas:r},i)=>{let a=K(r),o=Cx(e._tag===`FormUrlEncoded`?ZS(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=>Pie(Jy(e.ast)))})}),n}function gz(e,t,n){let r=gA(t.method),i=r?DL(t.headers[`content-type`]??`application/json`):`application/x-www-form-urlencoded`,a=e.get(i);if(!a)return dj(`Unsupported content-type: ${i}`,{status:415});let{_tag:o,decode:s}=a;switch(o){case`Multipart`:if(a.mode===`buffered`){let e=yp(t.multipart);return a.limits&&(e=Np(e,aM(a.limits))),B(e,s)}return F(a.limits?JE(t.multipartStream,aM(a.limits)):t.multipartStream);case`Json`:return B(yp(t.text),e=>{if(e===``)return s(a.nullOnEmpty?null:void 0);try{return s(JSON.parse(e))}catch{return z(new yx(new E_({message:`Expected a valid JSON body`})))}});case`Text`:return B(yp(t.text),s);case`FormUrlEncoded`:{let e=r?V(yp(t.urlParamsBody),zg):F(n);return B(e,s)}case`Uint8Array`:return B(V(yp(t.arrayBuffer),e=>new Uint8Array(e)),s)}}function _z(e,t,n,r,i,a){let o=ha(ha(e.annotations,t.annotations),n.annotations),s=mR(o),c=Ex(Rz(n,s.headers),s.success),l=Ex(zz(n,s.headers),s.error),u=GO(n.params,e=>Cx(e,s.params)),d=GO(n.headers,e=>Cx(e,s.headers)),f=GO(n.query,e=>Cx(ZS(e),s.query)),p=Dz(n,s.success),m=Ez(n,s.success,s.headers),h=n.payload.size>0&&!a?hz(n.payload,s.payload):void 0;return yz(t,n,r,R(function*(){let e=nC().context,r=ua(e,dM),a=ua(e,SM),o=ua(e,fM),s={request:r,endpoint:n,group:t};if(u&&(s.params=yield*vR.wrap(`Params`,u(a.params))),d&&(s.headers=yield*vR.wrap(`Headers`,d(r.headers))),f&&(s.query=yield*vR.wrap(`Query`,f(o))),h){let e=gz(h,r,o);if(oj(e))return e;e!==void 0&&(s.payload=yield*vR.wrap(`Payload`,e))}let l=yield*i(s);if(oj(l))return l;let g;m!==void 0&&_fe(l)&&(g=l.headers,l=l.body);let _=yield*vR.wrap(`Body`,p?.(l,e)??(g===void 0?c(l):m.encodeBody(l)));if(m===void 0||g===void 0)return _;let v=yield*vR.wrap(`ResponseHeaders`,m.encodeHeaders.get(_.status)(g));return _j(_,v)})).pipe(aie,pp(e=>vR.is(e)?rp(e):yp(l(e))),Np(r))}function vz(e,t,n,r){let i=n.endpoint;return DM(i.method,DR(i.path,i.params),_z(e,t,i,r,n.handler,n.isRaw),{uninterruptible:n.uninterruptible})}const yz=(e,t,n,r)=>{let i={group:e,endpoint:t};for(let e of t.middlewares){let t=e,a=ua(n,t);r=(xR(t)?xz(t,a):a)(r,i)}return r},bz=/*#__PURE__*/ new WeakMap,xz=(e,t)=>{let n=bz.get(t);if(n!==void 0)return n;let r=Object.entries(e.security).map(([e,n])=>({decode:lz(n),middleware:t[e]}));if(r.length===0)return M;let i=H(function*(e,t){e=vp(e,e=>new Cz(e));let n;for(let i=0;i<r.length;i++){let{decode:a,middleware:o}=r[i],s=yield*lp(B(a,n=>o(e,{credential:n,endpoint:t.endpoint,group:t.group})));if(Ca(s)){if(wz(s.failure))return yield*z(s.failure.error);n=s}else return s.success}return yield*op(n)});return bz.set(t,i),i},Sz=`~effect/http-api/HttpApiBuilder/HandlerError`;var Cz=class{[Sz]=Sz;error;constructor(e){this.error=e}};const wz=e=>N(e,Sz),Tz=/*#__PURE__*/ vx(oj);function Ez(e,t,n){let r=/* @__PURE__ */ new Map,i=[];for(let t of e.success)cL(t)&&(r.set(CL(t),Ex(t.headers,n)),aL(t.schema)||i.push(Fz(t,n)));return r.size===0?void 0:{encodeBody:Ex(i.length===0?Lx:i.length===1?i[0]:K(i),t),encodeHeaders:r}}function Dz(e,t){let n=Oz(e);if(n===void 0)return;let r=n.body,i=kz(e),a=CL(n.schema),o=r.contentType;if(gfe(r))return(e,t)=>_E(e)?F(mj(JE(e,t),{status:a,contentType:o})):i?void 0:new yx(new E_({message:`Expected a streaming response`}));let s=Az(r,t);return(e,t)=>_E(e)?F(mj(JE(jz(e,s),t),{status:a,contentType:o})):i?void 0:new yx(new E_({message:`Expected a streaming response`}))}function Oz(e){for(let t of e.success){let e=cL(t)?t.schema:t;if(aL(e))return{schema:t,body:e}}}function kz(e){for(let t of e.success){let e=cL(t)?t.schema:t;if(jx(e)&&!aL(e))return!0}return e.success.size===0}function Az(e,t){let n=YS(AS(e.error,bS()));return{sseMode:e.sseMode,encodeEvents:Ex(G(e.events),t),encodeCause:Ex(SS(n),t)}}function jz(e,t){return e.pipe(t.sseMode===`data`?ME(e=>({id:void 0,event:`message`,data:e})):M,NE(e=>yp(t.encodeEvents(e))),RE(e=>yE(Mz(e,t))),ME(Pz),GE)}function Mz(e,t){return t.encodeCause(e).pipe(yp,V(e=>({id:void 0,event:Nz,data:e})))}const Nz=`effect/http-api/stream/failure`;function Pz(e){return mfe.write({_tag:`Event`,event:e.event,id:e.id,data:e.data})}const Fz=/*#__PURE__*/ Bz(CL),Iz=/*#__PURE__*/ Bz(EL);function Lz(e,t){return cL(e)?Hz({schema:e,status:EL(e),encoding:wL(e),body:e.schema,headers:e.headers,headersOptions:t,toPair:e=>e}):Iz(e,t)}function Rz(e,t){let n=AL(e).map(e=>Fz(e,t));return n.length===1?n[0]:K(n)}function zz(e,t){let n=jL(e).map(e=>Lz(e,t));return n.length===0?Lx:n.length===1?n[0]:K(n)}function Bz(e){let t=/* @__PURE__ */ new WeakMap;return(n,r)=>{let i=hL(n.ast);if(i!==void 0)return Hz({schema:Px(n),status:e(i.body),encoding:xL(i.body.ast),body:i.bodyCodec,headers:i.headersCodec,headersOptions:r,toPair:i.transformation.encode});let a=cL(n)?n:n.ast,o=t.get(a);if(o!==void 0)return o;let s=cL(n)?n.schema:n,c=Tz.pipe($x(s,Vz(e,n)));return t.set(a,c),c}}function Vz(e,t){let n=cL(t)?t.schema:t;return fv({decode:(e,t)=>z(new O_({message:`Encode only schema`},e,t)),encode:Uz(e(t),wL(t),pL(n.ast))})}function Hz(e){let t=Ex(e.body),n=Ex(e.headers,e.headersOptions),r=Uz(e.status,e.encoding,pL(e.body.ast)),i=e=>e.issue,a=fv({decode:(e,t)=>z(new O_({message:`Encode only schema`},e,t)),encode:(a,o)=>{let s=e.toPair(a);return t(s.body,o).pipe(vp(i),B(e=>r(e,o)),B(e=>V(vp(n(s.headers),i),t=>_j(e,t))))}});return Tz.pipe($x(e.schema,a))}function Uz(e,t,n){switch(t._tag){case`Json`:return(r,i)=>{if(r===void 0||n)return F(sj({status:e}));try{let n=JSON.stringify(r);return F(dj(n,{status:e,contentType:t.contentType}))}catch{return z(new E_({expected:`a JSON-serializable response body`},r,i))}};case`Text`:return n=>F(dj(n,{status:e,contentType:t.contentType}));case`Uint8Array`:return n=>F(lj(n,{status:e,contentType:t.contentType}));case`FormUrlEncoded`:return n=>F(ece(n,{status:e}).pipe(hj(`content-type`,t.contentType)))}}const Wz=`~effect/http-api/HttpApiGroup`,Gz={[Wz]:Wz,add(...e){let t={...this.endpoints};for(let n of e)or(t,n.identifier,n);return qz({...Kz(this),endpoints:t})},prefix(e){return qz({...Kz(this),endpoints:Ea(this.endpoints,t=>t.prefix(e))})},middleware(e){return qz({...Kz(this),endpoints:Ea(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return qz({...Kz(this),annotations:ha(this.annotations,e)})},annotate(e,t){return qz({...Kz(this),annotations:oa(this.annotations,e,t)})},annotateEndpointsMerge(e){return qz({...Kz(this),endpoints:Ea(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return qz({...Kz(this),endpoints:Ea(this.endpoints,n=>n.annotate(e,t))})},pipe(){return jt(this,arguments)}},Kz=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),qz=e=>{function t(){}return Object.setPrototypeOf(t,Gz),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},Jz=(e,t)=>qz({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ia()}),Yz=`~effect/http-api/HttpApiSecurity`,Xz={[Yz]:Yz,pipe(){return jt(this,arguments)}},Zz=/*#__PURE__*/ (e=>Object.assign(Object.create(Xz),{_tag:`Http`,scheme:e.scheme,schemeLength:e.scheme.length,annotations:ia()}))({scheme:`Bearer`}),Qz=e=>Object.assign(Object.create(Xz),{_tag:`ApiKey`,key:e.key,in:e.in??`header`,annotations:ia()}),$z=/* @__PURE__ */ new Set([`Body`,`ResponseHeaders`]);var eB=class extends SR()(`effect-actions/http/SchemaErrors`,{error:[wI]}){};const tB=()=>wR(eB,e=>z($z.has(e.kind)?e:wI.fromSchemaError(e.cause))),nB=e=>(e??`/api`).split(`/`).filter(e=>e!==``),rB=e=>`/${e.join(`/`)}`,iB=e=>e.join(`/`)||`/`,aB=(e,t)=>{let n=Jz(e,{topLevel:!0}),[r,...i]=t;return rR(`actions`).annotate(sR,{errors:`all`}).add(r===void 0?n:n.add(r,...i))},oB=(e,t,n)=>QL(e.name,t,{payload:e.input.pipe(dL()),success:e.success,error:n.flatMap(rL)}),sB=(e,t=[])=>t.reduce((e,t)=>e.middleware(t),e);function cB(e,t={}){let n=rfe(`ActionHttp binding`,e,t),r=nB(t.prefix),i=n.authentication?.[`~middleware`],a=e.map(e=>{let t=i===void 0||e.caller===xI,a=oB(e,rB([...r,e.name]),tfe(e,n)).annotate(jR,e.description);return t?a:a.middleware(i)}),o=aB(iB(r),a);return{actions:e,...n,prefix:rB(r),api:o}}const lB=e=>af((t,n)=>fie(lf(e,t,n),ia())),uB=()=>AM(V(Ap(),e=>{let t=ga(Kd)(e);return e=>Ip(e,e=>ha(t,e))})).layer;var dB=class extends SR()(`effect-actions/ActionHttp/StepUp`){},fB=class extends SR()(`effect-actions/ActionHttp/JsonContentType`){};const pB=()=>uf(fB,e=>B(dM,t=>t.headers[`content-type`]===void 0?F(dj(`Unsupported content-type: none`,{status:415})):e));function mB(e,t,n={}){let{apps:r,actions:i,authentication:a}=ofe(`HTTP binding`,e,t,n),o=nB(e.prefix),s=iB(o),c=aB(s,i.map(t=>{let r=sB(oB(t,rB([...o,t.name]),FI(t,e.error)).middleware(fB).middleware(eB),n.middleware);return t.caller===xI||a===void 0?r:r.middleware(dB).middleware(a[`~middleware`])})).annotate(dR,GI),l=vf(R(function*(){let e=yield*WI(r),t=a===void 0?ff:yield*V(eL(a),e=>bf(uf(a[`~middleware`],e.middleware),uf(dB,e.stepUp))),i=yield*qf(n.middleware??[],e=>V(Pp(e),t=>uf(e,t))),o=Object.fromEntries(e.map(([e,t])=>[e.name,e=>t(e.payload)]));return sz(c,s,e=>e.handleAll(o)).pipe(Cf([tB(),pB(),t,...i]),lB)})).pipe(UI(r));return oz(c).pipe(Cf(l),Cf(uB()))}const hB=(e,t)=>fj(Ox(YS(e))(t),{status:tL(e.ast)??422}),gB=(e,t)=>{let n=e.flatMap(rL).find(e=>Sx(e)(t));return n===void 0?void 0:hB(n,t)},_B=/^[\x20\x21\x23-\x5B\x5D-\x7E]+$/,vB=(e,t)=>{let n=t.flatMap(([e,t])=>t===void 0?[]:[`${e}="${t.replace(/["\\]/g,`\\$&`)}"`]);return n.length===0?e:`${e} ${n.join(`, `)}`},yB=e=>vB(`Bearer`,e),bB=Sx(Xde),xB=(e,t)=>ln(e,`Forbidden`)&&e.scopes!==void 0?yB([[`error`,`insufficient_scope`],[`scope`,e.scopes.join(` `)],[`resource_metadata`,t],[`error_description`,_B.test(e.message)?e.message:void 0]]):void 0,SB={Unauthenticated:TI,Forbidden:DI},CB=e=>hB(SB[e._tag],e),wB=(e,t)=>{let n=CB(e),r=xB(e,t);return r===void 0?n:hj(n,`www-authenticate`,r)};var TB=class extends P()(`effect-actions/SteppedUp`){};const EB=e=>bB(e)&&(!ln(e,`Forbidden`)||e.scopes!==void 0),DB=e=>bp(e,e=>EB(e)?B(Fp(TB),t=>Ni(t)?WO(t.value,ji(e)):L):L),OB=(e,t)=>R(function*(){let n=yield*HO(Ai()),r=yield*up(Lp(e,TB,n)),i=yield*UO(n),a=Pd(r)&&(vd(r.cause)||yd(r.cause));return Ni(i)&&!a?wB(i.value,t):yield*r}),kB=/^[ \t]*Bearer +(.*[^ \t])[ \t]*$/i,AB=e=>Vi(Li(kB.exec(e??``)?.[1]),e=>sg(e)),jB=e=>{let t=new URL(e.resource),n=new URL(t);return n.pathname=`/.well-known/oauth-protected-resource${t.pathname===`/`?``:t.pathname}`,n},MB=e=>({scope:e?.scopesRequired?.join(` `),metadataUrl:e===void 0?void 0:jB(e).href}),NB=e=>Ni(AB(e)),PB=(e,t)=>yB([[`error`,t?`invalid_token`:void 0],[`scope`,e.scope],[`resource_metadata`,e.metadataUrl]]),FB=(e,t)=>{if(t!==void 0){if(!e)throw Error(`A protected resource is published only for a Bearer scheme`);if(!Gf(t)){for(let e of[`scopesSupported`,`scopesRequired`]){let n=t[e]?.find(e=>!EI.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}`)}}},IB=(e,t)=>_j(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}:{}}),LB=(e,t)=>{let n=t?.authentication,r=n===void 0||VB(n.security);FB(r,t?.protectedResource);let i=MB(t?.protectedResource),a=n!==void 0&&!r?UB(n.security,n.name):PB(i,NB(t?.authorization));if(!bB(e)){let t=gB(n?.error??[],e);if(t===void 0)throw Error(`Not a refusal, nor an error the authentication declares`);return IB(t,a)}return IB(r?wB(e,i.metadataUrl):CB(e),a)},RB=/\.well-known|[\t\n\r]/,zB=e=>{let t=jB(e),n=t.href.slice(t.origin.length),r=fj({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 sj({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(dM,a=>{let o=RB.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})},BB=e=>{let t=MB(e);return{metadataUrl:t.metadataUrl,invalid:PB(t,!0),anonymous:PB(t,!1),published:e===void 0?void 0:zB(e)}},VB=e=>ln(e,`Http`)&&e.scheme.toLowerCase()===`bearer`,HB=/^[\w.-]+$/,UB=(e,t)=>AO(e).pipe(MO(`Http`,({scheme:e})=>vB(e,[])),MO(`Basic`,()=>vB(`Basic`,[[`realm`,t]])),MO(`ApiKey`,()=>void 0),zO),WB=(e,t,...n)=>{let r=n[0]?.security??Zz,i=PI(n[0]?.error);if(!HB.test(e))throw Error(`Invalid authentication name: ${JSON.stringify(e)}, not an OpenAPI key`);if(LI(`Authentication "${e}"`,i),!ln(r,`Http`)&&!ln(r,`ApiKey`)&&!ln(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":SR()(`effect-actions/Authentication/Security/${e}`,{security:{[e]:r}}),"~verified":P(`effect-actions/Authentication/Verified/${e}`)}},GB=e=>og(e)?lg(e)!==``:e.username!==``||lg(e.password)!==``;function KB(e,t,n={}){let{security:r}=e,i=VB(r),a=n.protectedResource;FB(i,a);let o=Gf(a)?V(a,e=>(FB(i,e),BB(e))):F(BB(a)),s=new TI({message:i?`A bearer token is required.`:`A credential is required.`});return pf(e[`~provider`],R(function*(){let{metadataUrl:n,invalid:a,anonymous:c,published:l}=yield*o;l!==void 0&&(yield*(yield*xM).addGlobalMiddleware(l));let u=Gf(t)?yield*t:t;if(!$t(u))return yield*rp(/* @__PURE__ */ Error(`Missing verify: pass a verify function, or an Effect building one`));let d=e=>GB(e)?u(e):z(s),f=cle((e,t)=>F(hj(t,`cache-control`,`no-store`))),p=t=>i?GB(t)?a:c:UB(r,e.name),m=t=>bB(t)?F(i?wB(t,n):CB(t)):Qf(()=>{let n=gB(e.error,t);return n===void 0?rp(t):F(n)}),h=(e,t,n)=>{let r=p(e);return kp(d(e),{onFailure:m,onSuccess:e=>Lp(t,n,e)}).pipe(Up(()=>f),lle((e,t)=>F(IB(t,r))))};return{descriptor:e,authenticate:d,middleware:{[e.name]:(t,{credential:n})=>h(n,t,e.identity)},stepUp:e=>i?_p(e,EB,e=>F(wB(e,n))):e,http:((t,a)=>B(lz(r),r=>a&&!GB(r)?t:h(r,i?OB(t,n):t,e[`~verified`]))),route:(t=>B(lz(r),n=>h(n,_p(t,bB,m),e.identity)))}}))}var qB=class e extends qS()(`InternalServerError`,{message:U},{httpApiStatus:500}){cause;static of=t=>{let n=new e({message:`Request could not be completed`});return n.cause=t,n}},JB=class extends qS()(`ServiceUnavailable`,{message:U},{httpApiStatus:503}){},YB=class e extends qS()(`ClientNotFound`,{clientId:U,message:U},{httpApiStatus:404}){static of=t=>new e({clientId:t,message:`No client ${t} is registered`})},XB=class e extends qS()(`ResourceNotFound`,{identifier:U,message:U},{httpApiStatus:404}){static of=t=>new e({identifier:t,message:`No resource ${t} exists`})},ZB=class e extends qS()(`ApiKeyNotFound`,{keyId:U,message:U},{httpApiStatus:404}){static of=t=>new e({keyId:t,message:`No API key ${t} exists`})},QB=class e extends qS()(`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`})},$B=class e extends qS()(`OwnerExists`,{message:U},{httpApiStatus:409}){static of=()=>new e({message:`Setup already completed`})},eV=class extends qS()(`ProviderRefused`,{message:U},{httpApiStatus:400}){},tV=class extends qS()(`UnreadableRequest`,{message:U},{httpApiStatus:400}){};const nV=[JB,qB];var rV=class extends P()(`clankerauth/CurrentOwner`){};const iV=e=>WB(`clankerauth.OwnerSession`,rV,{security:Qz({in:`cookie`,key:e}),error:nV}),aV=iV(`better-auth.session_token`),oV=WB(`clankerauth.OwnerToken`,rV,{error:nV}),sV=e=>new URL(`/`,e).href,cV={read:`clankerauth:read`,write:`clankerauth:write`},lV=`Passwords have 8 to 128 characters`,uV=W({email:U.check(sS(/\S/u,{message:`Setup requires an email`})),password:U.check(fS(8,{message:lV}),mS(128,{message:lV}))}),dV=Xx([`none`,`client_secret_basic`,`client_secret_post`]),fV=Xx([`web`,`native`]),pV=G(U).check(gS({message:`Choose unique Resources`})),mV=W({client_name:U,redirect_uris:G(U),resources:pV,token_endpoint_auth_method:dV,application_type:fV}),hV=W({client_id:U,client_name:U,redirect_uris:G(U),application_type:fV}),gV=W({client_id:U}),_V=W({client_id:U,resource:Nx(U)}),vV=W({client_id:U,blocked:Vx}),yV=W({onboarding:Nx(Xx([`managed`,`dcr`,`cimd`])),blocked:Nx(Vx),client_id:U,client_name:Nx(U),redirect_uris:G(U),token_endpoint_auth_method:Nx(U),application_type:Nx(Zx(U)),scope:Nx(U),grant_types:Nx(G(U))}),bV=yV.pipe(Wx({client_secret:Nx(U),client_secret_expires_at:Nx(Bx)})),xV=W({identifier:U,name:U,scopes:G(U)}),SV=xV.pipe(Wx({builtIn:Vx})),CV=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`})))}),wV=W({identifier:U}),TV=W({resource:xV,created:Vx}),EV=W({client_id:U,resource:U}),DV=W({client_id:U,resources:pV}),OV=W({clientAccess:G(EV)}),kV=Gx(U,G(U)),AV=Gx(U,G(U).check(fS(1,{message:`Select explicitly granted, currently available Resource scopes`}),gS({message:`Select explicitly granted, currently available Resource scopes`}))).check(Joe(1,{message:`Select at least one Resource and scope`})),jV=U.check(mS(100,{message:`Key names require 1–100 characters`}),sS(/\S/u,{message:`Key names require 1–100 characters`})),MV=FS,NV=W({client_id:U,resource:U,scopes:G(U),approvedAt:Zx(MV),refreshedAt:Zx(MV)}),PV=W({name:jV,permissions:AV,expiresAt:Zx(MV)}),FV=W({keyId:U}),IV=W({keyId:U,name:Nx(jV),permissions:Nx(AV),enabled:Nx(Vx)}),LV=W({keyId:U,name:U,enabled:Vx,permissions:kV,expiresAt:Zx(MV),createdAt:MV}),RV={caller:xI},zV={caller:rV},BV=[ZI(`setupStatus`,{description:`Check whether the issuer needs its first owner account.`,readOnly:!0,...RV,error:[qB],success:W({required:Vx})}),ZI(`setupOwner`,{description:`Create the first owner account.`,readOnly:!1,...RV,error:[$B,eV,qB],input:uV,success:W({created:Vx}).pipe(iL(201))}),ZI(`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,...RV,error:[qB],input:W({resource:U}),success:W({list:U})})],VV=W({clients:G(yV),resources:G(SV),clientAccess:G(EV),connections:G(NV),email:U,issuer:U}),HV=[ZI(`listClients`,{description:`List clients, resources, managed clients' resource access (what they may obtain), and every client's connections (what it holds).`,readOnly:!0,...zV,error:[qB],success:VV}),ZI(`createClient`,{description:`Register a first-party OAuth client. Returns its secret once when confidential.`,readOnly:!1,...zV,error:[eV,qB],input:mV,success:bV.pipe(iL(201))}),ZI(`updateClient`,{description:`Rename a first-party client or change its redirect URIs and application type.`,readOnly:!1,...zV,error:[YB,QB,eV,qB],input:hV,success:yV}),ZI(`deleteClient`,{description:`Delete a client and its stored authorization. An automatic client can register again; block it to keep it out.`,readOnly:!1,...zV,error:[YB,qB],input:gV,success:W({deleted:Vx})}),ZI(`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,...zV,error:[YB,qB],input:_V,success:W({revoked:Vx})}),ZI(`blockClient`,{description:`Block or unblock OAuth authorization for a client.`,readOnly:!1,...zV,error:[YB,qB],input:vV,success:W({blocked:Vx})}),ZI(`rotateClientSecret`,{description:`Rotate a confidential client secret. Returns the new secret once.`,readOnly:!1,...zV,error:[YB,QB,eV,qB],input:gV,success:bV}),ZI(`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,...zV,error:[YB,QB,qB],input:DV,success:OV}),ZI(`getResource`,{description:`Get one resource and its scopes by identifier.`,readOnly:!0,...zV,error:[XB,qB],input:wV,success:SV}),ZI(`putResource`,{description:`Create an OAuth resource, or update the one with its identifier, to exactly these name and scopes.`,readOnly:!1,...zV,error:[eV,qB],input:CV,success:TV}),ZI(`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,...zV,error:[XB,qB],input:wV,success:W({deleted:Vx})}),ZI(`listApiKeys`,{description:`List API key metadata without secret values.`,readOnly:!0,...zV,error:[qB],success:W({keys:G(LV)})}),ZI(`createApiKey`,{description:`Create a scoped API key. Returns its secret once.`,readOnly:!1,...zV,error:[eV,qB],input:PV,success:LV.pipe(Wx({key:U}),iL(201))}),ZI(`updateApiKey`,{description:`Update an API key’s name, permissions or enabled state.`,readOnly:!1,...zV,error:[ZB,eV,qB],input:IV,success:LV}),ZI(`deleteApiKey`,{description:`Delete an API key.`,readOnly:!1,...zV,error:[ZB,qB],input:FV,success:W({deleted:Vx})})],UV=[.../* @__PURE__ */ new Set([...[...BV,...HV].flatMap(e=>e.error),...nV,tV])],WV=e=>cB([...HV,...BV],{authentication:e});WV(aV);const GV=cB(HV,{prefix:`/api/owner`,authentication:oV});var KV=/* @__PURE__ */ e({NodeSqliteDialect:()=>QV}),qV=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},JV=class{#e;#t=new XV;#n;#r;constructor(e){this.#e={...e}}async init(){this.#n=this.#e.database,this.#r=new YV(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()}},YV=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.`)}},XV=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?.()}},ZV=class extends r{getCurrentParameterPlaceholder(){return`?`}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}},QV=class{#e;constructor(e){this.#e={...e}}createDriver(){return new JV(this.#e)}createQueryCompiler(){return new ZV}createAdapter(){return new qV}createIntrospector(e){return n(e)}};const $V=e=>{let t=Cx(e);return e=>vp(t(e),qB.of)};function eH(e){return(n,...r)=>Xf({try:async()=>(await t(n,...r).execute(e)).rows,catch:qB.of})}const tH=dm(`Database.transaction`)(function*(e,t){let n=yield*Xf({try:()=>e.startTransaction().execute(),catch:qB.of}),r=yield*up(t(eH(n))),i=Sp(Xf({try:()=>n.rollback().execute(),catch:qB.of})),a=Xf({try:()=>n.commit().execute(),catch:qB.of}).pipe(bp(()=>i));return yield*Nd(r)?a:i,yield*r},Xp);async function nH(e){let n=new gee(e);try{n.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;`);let e=new i({dialect:new QV({database:n})});return await t`SELECT 1`.execute(e),{kysely:e,sql:eH(e),close:()=>e.destroy()}}catch(e){throw n.close(),e}}var rH=class e extends P()(`clankerauth/Database`){static layer=t=>pf(e,R(function*(){yield*ip(()=>fee(ft(t),{recursive:!0,mode:448}));let e=yield*Bp(Xf(()=>nH(t)),e=>Yf(()=>e.close()));return{kysely:e.kysely,sql:e.sql,transaction:t=>tH(e.kysely,t)}}))};let iH,aH=!1;function oH(){try{return globalThis.process?.getBuiltinModule?.(`node:async_hooks`)?.AsyncLocalStorage}catch{return}}async function sH(){if(iH)return iH;let e=oH();if(e)return iH??=e,iH;try{let{AsyncLocalStorage:e}=await import(
|
|
26
|
+
/* @vite-ignore */
|
|
27
|
+
/* webpackIgnore: true */
|
|
28
|
+
`node:async_hooks`);return iH??=e,iH}catch(e){let t=globalThis.AsyncLocalStorage;if(typeof t==`function`)return iH??=t,iH;throw typeof window<`u`?Error(`getAsyncLocalStorage is only available in server code`):(aH||(aH=!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 cH=()=>b().context.endpointContextAsyncStorage,lH=async()=>{let e=cH();if(e)return e;let t=await sH(),n=b().context;return n.endpointContextAsyncStorage??=new t};function uH(){return ce()}function dH(){let e=uH();if(!e)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return e}async function fH(e,t){return(await lH()).run(e,t)}const pH=async()=>{let e=b(),t=e.context.requestStateAsyncStorage;if(t)return t;let n=await sH();return e.context.requestStateAsyncStorage??=new n,e.context.requestStateAsyncStorage};async function mH(){return(await pH()).getStore()!==void 0}async function hH(){let e=(await pH()).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 gH(e,t){return(await pH()).run(e,t)}function _H(e){let t=Object.freeze({});return{get ref(){return t},async get(){let n=await hH();if(!n.has(t)){let r=await e();return n.set(t,r),r}return n.get(t)},async set(e){(await hH()).set(t,e)}}}function vH(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}const Y=vH({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`}),yH=async()=>{let e=b(),t=e.context.adapterAsyncStorage;if(t)return t;let n=await sH();return e.context.adapterAsyncStorage??=new n,e.context.adapterAsyncStorage},bH=async e=>yH().then(t=>t.getStore()?.adapter||e).catch(()=>e),xH=async(e,t)=>{let n=!1;return yH().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})},SH=async(e,t,n)=>{let r=!1;return yH().then(async i=>{if(r=!0,i.getStore()?.isTransactionActive)return t();let a=ot(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{C.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})},CH=async(e,t)=>{let n=async()=>{try{await e()}catch(e){if(!t?.onError)throw e;await t.onError(e)}},r;try{r=await yH()}catch{return n()}let i=r.getStore();if(!i?.isTransactionActive)return n();i.pendingHooks.push(n)};function wH(e){return e===`-`||e===`^`||e===`$`||e===`+`||e===`.`||e===`(`||e===`)`||e===`|`||e===`[`||e===`]`||e===`{`||e===`}`||e===`*`||e===`?`||e===`\\`?`\\${e}`:e}function TH(e){let t=``;for(let n=0;n<e.length;n++)t+=wH(e[n]);return t}function EH(e,t=!0){if(Array.isArray(e))return`(?:${e.map(e=>`^${EH(e,t)}$`).join(`|`)})`;let n=``,r=``,i=`.`;t===!0?(n=`/`,r=`[/\\\\]`,i=`[^/\\\\]`):t&&(n=t,r=TH(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+=wH(n[e+1]),e++):c+=t===`?`?i:t===`*`?`${i}*?`:wH(t)}c+=l}}}return c}function DH(e,t){if(typeof t!=`string`)throw TypeError(`Sample must be a string, but ${typeof t} given`);return e.test(t)}function OH(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=EH(e,t.separator),r=RegExp(`^${n}$`,t.flags),i=DH.bind(null,r);return i.options=t,i.pattern=e,i.regexp=r,i}function kH(e){let t=e.replace(/:\d+$/,``).replace(/^\[|\]$/g,``).toLowerCase();return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t.startsWith(`127.`)}function AH(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}function jH(e){try{return(AH(new URL(e).pathname)||`/`)!==`/`}catch{throw new D(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function MH(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 NH(e,t=`/api/auth`){if(MH(e),jH(e))return e;let n=AH(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function PH(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 FH(e,t,n,r,i){if(e)return NH(e,t);if(r!==!1){let e=S.BETTER_AUTH_URL||S.NEXT_PUBLIC_BETTER_AUTH_URL||S.PUBLIC_BETTER_AUTH_URL||S.NUXT_PUBLIC_BETTER_AUTH_URL||S.NUXT_PUBLIC_AUTH_URL||(S.BASE_URL===`/`?void 0:S.BASE_URL);if(e)return NH(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&PH(o,`proto`)&&PH(a,`host`))try{return NH(`${o}://${a}`,t)}catch{}if(n){let e=IH(n.url);if(!e)throw new D(`Could not get origin from request. Please provide a valid base URL.`);return NH(e,t)}if(typeof window<`u`&&window.location)return NH(window.location.origin,t)}function IH(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}function LH(e){try{return new URL(e).protocol}catch{return null}}function RH(e){try{return new URL(e).host}catch{return null}}function zH(e){return typeof e==`object`&&!!e&&`allowedHosts`in e&&Array.isArray(e.allowedHosts)}function BH(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 VH(e,t){let n=BH(e)?e.headers:e;if(t){let e=n.get(`x-forwarded-host`);if(e&&PH(e,`host`))return e}let r=n.get(`host`);if(r&&PH(r,`host`))return r;if(BH(e))try{return new URL(e.url).host}catch{return null}return null}function HH(e,t,n){if(t===`http`||t===`https`)return t;let r=BH(e)?e.headers:e;if(n){let e=r.get(`x-forwarded-proto`);if(e&&PH(e,`proto`))return e}if(BH(e))try{let t=new URL(e.url);if(t.protocol===`http:`||t.protocol===`https:`)return t.protocol.slice(0,-1)}catch{}let i=VH(e,n);return i&&kH(i)?`http`:`https`}const UH=(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(`?`)?OH(r)(n):n.toLowerCase()===r.toLowerCase()};function WH(e,t,n,r){let i=VH(t,r);if(!i){if(e.fallback)return NH(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=>UH(i,e)))return NH(`${HH(t,e.protocol,r)}://${i}`,n);if(e.fallback)return NH(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 GH(e,t,n,r,i){if(zH(e))return n?WH(e,n,t,i):e.fallback?NH(e.fallback,t):FH(void 0,t,void 0,r,i);let a=BH(n)?n:void 0;return FH(typeof e==`string`?e:void 0,t,a,r,i)}const KH=f(`a-z`,`0-9`,`A-Z`,`-_`);var qH=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(de(e),Te(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),Ee(r)}update(e){return Oe(this),this.iHash.update(e),this}digestInto(e){Oe(this),T(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 JH=/* @__PURE__ */ (()=>{let e=((e,t,n)=>new qH(e,t).update(n).digest());return e.create=(e,t)=>new qH(e,t),e})(),YH=/* @__PURE__ */ Uint8Array.of(0),XH=/* @__PURE__ */ Uint8Array.of();function ZH(e,t,n,r=32,i){de(e),De(r,`length`),Te(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=XH:Te(n,void 0,`info`),!o)return i&&Ee(t),/* @__PURE__ */ new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=JH.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++){YH[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(YH).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(YH[0]=o,o>1&&c.update(u),c.update(n).update(YH).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&Ee(u),Ee(YH),r===s.length)return s;let f=s.slice(0,r);return Ee(s),f}const QH=(e,t,n,r,i)=>{de(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=JH.create(e,n).update(t);return ZH(e,a.digest(),r,i,a)},$H=e=>e/2**32|0,eU=e=>e>>>0;function tU(e,t,n,r){let i=$H(n),a=eU(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function nU(e,t,n){return e&t^~e&n}function rU(e,t,n){return e&t^e&n^t&n}var iU=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=g(this.buffer)}update(e){Oe(this),Te(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=g(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){Oe(this),T(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)),tU(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:g(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 aU=/* @__PURE__ */ Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),oU=/* @__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]),sU=/* @__PURE__ */ new Uint32Array(64);var cU=class extends iU{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)sU[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=sU[e-15],n=sU[e-2],r=te(t,7)^te(t,18)^t>>>3,i=te(n,17)^te(n,19)^n>>>10;sU[e]=i+sU[e-7]+r+sU[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=te(o,6)^te(o,11)^te(o,25),u=l+t+nU(o,s,c)+oU[e]+sU[e]|0,d=(te(n,2)^te(n,13)^te(n,22))+rU(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(){Ee(sU)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ee(this.buffer)}},lU=class extends cU{constructor(){super(32,aU)}};const uU=/* @__PURE__ */ re(()=>new lU,/* @__PURE__ */ h(1));async function dU(e,t,n=3600){return await new rI(e).setProtectedHeader({alg:`HS256`}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+n).sign(new TextEncoder().encode(t))}async function fU(e,t){try{return(await tI(e,new TextEncoder().encode(t))).payload}catch{return null}}const pU=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]),mU=()=>Date.now()/1e3|0,hU=`A256CBC-HS512`;function gU(e,t){return QH(uU,new TextEncoder().encode(e),new TextEncoder().encode(t),pU,64)}function _U(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 vU(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 yU(e,t,n,r=3600){let i=gU(_U(t),n),a=await cI({kty:`oct`,k:gP(i)},`sha256`);return await new Pde(e).setProtectedHeader({alg:`dir`,enc:hU,kid:a}).setIssuedAt().setExpirationTime(mU()+r).setJti(crypto.randomUUID()).encrypt(i)}const bU={clockTolerance:15,keyManagementAlgorithms:[`dir`],contentEncryptionAlgorithms:[hU,`A256GCM`]};async function xU(e,t,n){if(!e)return null;let r=!1;try{r=hI(e).kid!==void 0}catch{return null}try{let r=vU(t),{payload:i}=await nI(e,async e=>{let t=e.kid;if(t!==void 0){for(let e of r){let r=gU(e.value,n);if(t===await cI({kty:`oct`,k:gP(r)},`sha256`))return r}throw Error(`no matching decryption secret`)}return r.length,gU(r[0].value,n)},bU);return i}catch{if(r)return null;let i=vU(t);if(i.length<=1)return null;for(let t=1;t<i.length;t++)try{let r=i[t],{payload:a}=await nI(e,gU(r.value,n),bU);return a}catch{continue}return null}}function SU(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 CU={N:16384,r:16,p:1,dkLen:64};function wU(e,t){return new Promise((n,r)=>{lt(e.normalize(`NFKC`),t,CU.dkLen,{N:CU.N,r:CU.r,p:CU.p,maxmem:128*CU.N*CU.r*2},(e,t)=>{e?r(e):n(t)})})}async function TU(e){let t=ct(16).toString(`hex`);return`${t}:${(await wU(e,t)).toString(`hex`)}`}async function EU(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await wU(t,n)).toString(`hex`)===r}const DU=TU,OU=async({hash:e,password:t})=>EU(e,t);function kU(){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 AU(e,t){return{digest:async n=>{let r=le(n),i=await kU().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`)?me.encode(i,{padding:t!==`base64urlnopad`}):he.encode(i):i}}}
|
|
29
|
+
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
30
|
+
function jU(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const MU=e=>e?`"${e}" `:``;function NU(e,t=``){if(typeof e!=`boolean`)throw TypeError(MU(t)+`expected boolean, got type=`+typeof e);return e}function PU(e,t=``){if(typeof e!=`number`)throw TypeError(MU(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(MU(t)+`expected integer >= 0, got `+e);return e}function FU(e,t,n=``){if(jU(e)&&(t===void 0||e.length===t))return e;t!==void 0&&PU(t,`length`);let r=jU(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=MU(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const IU=(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 LU(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function RU(e,t){FU(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function zU(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function BU(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function VU(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const HU=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function UU(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function WU(e){for(let t=0;t<e.length;t++)e[t]=UU(e[t]);return e}const GU=HU?e=>e:WU,KU=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,qU=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function JU(e){if(FU(e),KU)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=qU[e[n]];return t}function YU(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function XU(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(KU)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=YU(e.charCodeAt(i)),a=YU(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 ZU(e){if(typeof e!=`string`)throw TypeError(`string expected`);return new Uint8Array(new TextEncoder().encode(e))}function QU(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 $U(e,t){if(QU(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function eW(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];FU(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 tW(e,t){return IU(e,`defaults`),IU(t,`opts`),Object.assign(e,t)}function nW(e,t){if(e=FU(e),t=FU(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 rW(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 iW=(e,t)=>{function n(n,...r){if(FU(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];FU(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(jU(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&FU(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`);FU(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,FU(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(FU(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 aW(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(FU(t,e,`output`),n&&!sW(t))throw Error(`invalid output, must be aligned`);return t}function oW(e,t,n){PU(e),PU(t),NU(n);let r=/* @__PURE__ */ new Uint8Array(16),i=VU(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function sW(e){return e.byteOffset%4==0}function cW(e){return Uint8Array.from(FU(e))}function lW(e=32){PU(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 uW(e,t=lW){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;PU(n,`fn.nonceLength`);let r=(e,t,n)=>{let r=eW(e,t);return QU(n,t)||t.fill(0),r},i=((i,...a)=>({encrypt(o){FU(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){FU(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 dW=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),fW=/* @__PURE__ */ GU(zU(dW(`expand 16-byte k`))),pW=/* @__PURE__ */ GU(zU(dW(`expand 32-byte k`)));function mW(e,t){return e<<t|e>>>32-t}const hW=2**32-1,gW=/* @__PURE__ */ Uint32Array.of();function _W(e,t,n,r,i,a,o,s){let c=i.length,l=/* @__PURE__ */ new Uint8Array(64),u=zU(l),d=HU&&sW(i)&&sW(a),f=d?zU(i):gW,p=d?zU(a):gW;if(HU)for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=hW)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),GU(u),o>=hW)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 vW(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=tW({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return PU(i),PU(o),NU(a),NU(n),(t,s,c,l,u=0)=>{FU(t,void 0,`key`),FU(s,void 0,`nonce`),FU(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=aW(d,l,!1),f&&$U(c,l),PU(u),u<0||u>=hW)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=cW(t)),g=pW;else if(m===16&&n)h=/* @__PURE__ */ new Uint8Array(32),h.set(t),h.set(t,16),g=fW,p.push(h);else throw FU(t,32,`arx key`),Error(`invalid key size`);(!HU||!sW(s))&&p.push(s=cW(s));let _=zU(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(HU)r(g,_,zU(e),_);else{let t=GU(Uint32Array.from(g));r(t,_,zU(e),_),BU(t),GU(_)}s=s.subarray(16)}else HU||GU(_);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=GU(zU(s));try{return _W(e,g,_,y,c,l,u,o),l}finally{BU(...p)}}}function yW(e,t){return e[t++]&255|(e[t++]&255)<<8}var bW=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=cW(FU(e,32,`key`));let t=yW(e,0),n=yW(e,2),r=yW(e,4),i=yW(e,6),a=yW(e,8),o=yW(e,10),s=yW(e,12),c=yW(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]=yW(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=yW(e,t+0),_=yW(e,t+2),v=yW(e,t+4),y=yW(e,t+6),b=yW(e,t+8),x=yW(e,t+10),S=yW(e,t+12),ee=yW(e,t+14),C=i[0]+(g&8191),te=i[1]+((g>>>13|_<<3)&8191),w=i[2]+((_>>>10|v<<6)&8191),ne=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*w+5*p*ne+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*w+5*m*ne+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+w*o+5*h*ne+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+w*s+ne*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+w*c+ne*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+w*l+ne*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+w*u+ne*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+w*d+ne*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+w*f+ne*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+w*p+ne*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;BU(n)}update(e){LU(this),FU(e),e=cW(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,BU(this.h,this.r,this.buffer,this.pad)}digestInto(e){LU(this),RU(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 xW=/* @__PURE__ */ rW(32,e=>new bW(e));function SW(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,w=u,ne=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+w|0,ce=mW(ce^S,16),ie=ie+ce|0,w=mW(w^ie,12),S=S+w|0,ce=mW(ce^S,8),ie=ie+ce|0,w=mW(w^ie,7),ee=ee+ne|0,le=mW(le^ee,16),ae=ae+le|0,ne=mW(ne^ae,12),ee=ee+ne|0,le=mW(le^ee,8),ae=ae+le|0,ne=mW(ne^ae,7),C=C+T|0,ue=mW(ue^C,16),oe=oe+ue|0,T=mW(T^oe,12),C=C+T|0,ue=mW(ue^C,8),oe=oe+ue|0,T=mW(T^oe,7),te=te+re|0,de=mW(de^te,16),se=se+de|0,re=mW(re^se,12),te=te+re|0,de=mW(de^te,8),se=se+de|0,re=mW(re^se,7),S=S+ne|0,de=mW(de^S,16),oe=oe+de|0,ne=mW(ne^oe,12),S=S+ne|0,de=mW(de^S,8),oe=oe+de|0,ne=mW(ne^oe,7),ee=ee+T|0,ce=mW(ce^ee,16),se=se+ce|0,T=mW(T^se,12),ee=ee+T|0,ce=mW(ce^ee,8),se=se+ce|0,T=mW(T^se,7),C=C+re|0,le=mW(le^C,16),ie=ie+le|0,re=mW(re^ie,12),C=C+re|0,le=mW(le^C,8),ie=ie+le|0,re=mW(re^ie,7),te=te+w|0,ue=mW(ue^te,16),ae=ae+ue|0,w=mW(w^ae,12),te=te+w|0,ue=mW(ue^te,8),ae=ae+ue|0,w=mW(w^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+w|0,r[fe++]=d+ne|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 CW(e,t,n,r){let i=HU?e:GU(e.slice(0,4)),a=HU?t:GU(t.slice(0,8)),o=HU?n:GU(n.slice(0,4)),s=/* @__PURE__ */ new Uint32Array(16);SW(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,GU(r),HU||BU(i,a,o),BU(s)}const wW=/* @__PURE__ */ vW(SW,{counterRight:!1,counterLength:8,extendNonceFn:CW,allowShortKeys:!1}),TW=/* @__PURE__ */ new Uint8Array(16),EW=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(TW.subarray(n))},DW=/* @__PURE__ */ new Uint8Array(32);function OW(e,t,n,r,i){i!==void 0&&FU(i,void 0,`AAD`);let a=e(t,n,DW),o=oW(r.length,i?i.length:0,!0),s=xW.create(a);i&&EW(s,i),EW(s,r),s.update(o);let c=s.digest();return BU(a,o),c}const kW=/* @__PURE__ */ iW({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},/* @__PURE__ */ (e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=aW(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=OW(e,t,n,s,r);return a.set(c,o),BU(c),a},decrypt(i,a){a=aW(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=OW(e,t,n,o,r);if(!nW(s,c))throw BU(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),BU(c),a}}))(wW)),AW={name:`HMAC`,hash:`SHA-256`},jW=`$ba$`;function MW(e){if(!e.startsWith(jW))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 NW(e,t){return`${jW}${e}$${t}`}async function PW(e,t){let n=await AU(`SHA-256`).digest(e),r=ZU(t);return JU(uW(kW)(new Uint8Array(n)).encrypt(r))}async function FW(e,t){let n=await AU(`SHA-256`).digest(e),r=XU(t),i=uW(kW)(new Uint8Array(n));return new TextDecoder().decode(i.decrypt(r))}const IW=async({key:e,data:t})=>{if(typeof e==`string`)return PW(e,t);let n=e.keys.get(e.currentVersion);if(!n)throw Error(`Secret version ${e.currentVersion} not found in keys`);let r=await PW(n,t);return NW(e.currentVersion,r)},LW=async({key:e,data:t})=>{if(typeof e==`string`)return FW(e,t);let n=MW(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 FW(t,n.ciphertext)}if(e.legacySecret)return FW(e.legacySecret,t);throw Error(`Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.`)},RW=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await kU().importKey(`raw`,t,AW,!1,[`sign`,`verify`])},zW=async(e,t)=>{let n=await RW(t),r=await kU().sign(AW.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))};function BW(e){return!!e.database||!!e.secondaryStorage}function VW(e){return!!e.database}function HW(e){return VW(e)}function UW(e){return Ie(Re,e)}function WW(e){return je(Xe,e)}function GW(e){return Me(tt,e)}const KW=A({id:k(),createdAt:nt().default(()=>/* @__PURE__ */ new Date),updatedAt:nt().default(()=>/* @__PURE__ */ new Date)}),qW=KW.extend({userId:UW(),expiresAt:nt(),token:k(),ipAddress:k().nullish(),userAgent:k().nullish()}),JW=KW.extend({email:k().transform(e=>e.toLowerCase()),emailVerified:Je().default(!1),name:k(),image:k().nullish()});function YW(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 XW=/* @__PURE__ */ new WeakMap;function ZW(e,t,n){let r=`${t}:${n}`;XW.has(e)||XW.set(e,/* @__PURE__ */ new Map);let i=XW.get(e);if(i.has(r))return i.get(r);let a=n===`output`?ie(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 QW(e,t){return YW(t,ZW(e,`user`,`output`))}function $W(e,t){let n=ZW(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 eG(e,t){return YW(t,ZW(e,`session`,`output`))}function tG(e,t){let{accessToken:n,refreshToken:r,idToken:i,accessTokenExpiresAt:a,refreshTokenExpiresAt:o,password:s,...c}=YW(t,ZW(e,`account`,`output`));return c}function nG(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 rG(e,t={},n){return nG(t,{fields:ZW(e,`user`,`input`),action:n})}function iG(e,t={},n){let r=ZW(e,`user`,`input`),i=Object.create(null);for(let e of Object.keys(t))r[e]?.input!==!1&&(i[e]=t[e]);return nG(i,{fields:r,action:n})}function aG(e,t,n){return nG(t,{fields:ZW(e,`session`,`input`),action:n})}function oG(e){let t=ZW(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 sG(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 cG=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function lG(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}const uG=/^(\+|\-)? ?(\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 dG(e){let t=uG.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 fG(e){return Math.round(dG(e)/1e3)}const pG=We({session:qW.loose(),user:JW.loose(),updatedAt:Le(),version:k().optional()}),mG=A({session:ze(k(),rt()),expiresAt:Le(),signature:k()});function hG(e){let t=ye(e);if(t===null)return null;let n=pG.safeParse(t);return n.success?n.data:(C.warn(`Cookie cache payload failed schema validation`,{issues:n.error.issues.map(({code:e,path:t})=>({code:e,path:t}))}),null)}function gG(e){let t=mG.safeParse(e);return t.success?t.data:null}function _G(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function vG(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 yG(e){let t=/* @__PURE__ */ new Map;return vG(e).forEach(e=>{let[n,...r]=e.split(`;`).map(e=>e.trim()),[i,...a]=(n||``).split(`=`),o=SG(a.join(`=`));if(!i)return;let s={value:_G(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 bG=/^[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E\x5F\x60\x61-\x7A\x7C\x7E]+$/,xG=/^[\x20\x21\x23-\x3A\x3C-\x5B\x5D-\x7E]*$/;function SG(e){return e.length<2||!e.startsWith(`"`)||!e.endsWith(`"`)?e:e.slice(1,-1)}function CG(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 wG(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=CG(n.slice(0,e)),i=SG(CG(n.slice(e+1)));bG.test(r)&&xG.test(i)&&t.set(r,_G(i))}return t}function TG(e){let t={clockTolerance:15,audience:e?.audience??`better-auth:session-cache`};return e?.issuer&&(t.issuer=e.issuer),t}function EG(e){let t=hG(e);return!t||typeof e.iss!=`string`||!e.iss||e.sub!==t.user.id||e.sid!==t.session.token?null:{...e,...t}}const DG={name:`HMAC`,hash:`SHA-256`},OG=async e=>{let t=typeof e==`string`?new TextEncoder().encode(e):e;return await kU().importKey(`raw`,t,DG,!1,[`sign`,`verify`])},kG=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 kU().verify(DG,n,i,new TextEncoder().encode(t))}catch{return!1}},AG=async(e,t)=>{let n=await OG(t),r=await kU().sign(DG.name,n,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(r)))},jG=async(e,t)=>{let n=await AG(e,t);return e=`${e}.${n}`,e=encodeURIComponent(e),e},MG=/^application\/([a-z0-9.+-]*\+)?json/i;async function NG(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(MG.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 PG(e){return e instanceof O||e?.name===`APIError`}function FG(e){try{return e.includes(`%`)?decodeURIComponent(e):e}catch{return e}}async function IG(e){try{return{data:await e,error:null}}catch(e){return{data:null,error:e}}}function LG(e){return e instanceof Request||Object.prototype.toString.call(e)===`[object Request]`}const RG={secure:`__Secure-`,host:`__Host-`},zG=(e,t)=>{if(!t)return e;if(t===`secure`||t===`host`)return RG[t]+e};function BG(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,FG(n))}n=i+1}return t}function VG(e,t,n={}){let r=zG(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 HG({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 UG=(e,t,n)=>(t=encodeURIComponent(t),HG(VG(e,t,n))),WG=async(e,t,n,r)=>(t=await jG(t,n),HG(VG(e,t,r)));async function GG(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:KG(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:KG(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 KG(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 qG=async(e,{options:t,path:n})=>{let r=new Headers,i,{data:a,error:o}=await GG(t,e);if(o)throw new Pe(o.message,o.issues);let s=e.headers===void 0?`request`in e&&LG(e.request)?e.request.headers:null:e.headers instanceof Headers?e.headers:new Headers(e.headers),c=s?.get(`cookie`),l=c?BG(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=zG(e,t);return n&&l?.get(n)||null},getSignedCookie:async(e,t,n)=>{let r=zG(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 kG(s,o,await OG(t))?o:!1},setCookie:(e,t,n)=>{let i=UG(e,t,n);return r.append(`set-cookie`,i),i},setSignedCookie:async(e,t,n,i)=>{let a=await WG(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 JG(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 YG(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 XG(e){return!e||typeof e!=`object`?!1:`_flag`in e&&e._flag===`json`}const ZG=/* @__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 QG(e){for(let t of ZG)e.delete(t)}function $G(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 eK(e,t){if(e instanceof Response){if(t?.headers){let n=new Headers(t.headers);QG(n),$G(e.headers,n)}return e}if(XG(e)){let n=e.body,r=e.routerResponse;if(r instanceof Response)return r;let i=new Headers;if($G(i,r?.headers),$G(i,e.headers),t?.headers){let e=new Headers(t.headers);QG(e),$G(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(PG(e))return eK(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 QG(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`)):JG(e)&&(n=YG(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 tK(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 Ne(`Body is not allowed with GET or HEAD methods`);if(r&&/\/{2,}/.test(r))throw new Ne(`Path cannot contain consecutive slashes`);let o=async(...e)=>{let t=e[0]||{},{data:n,error:o}=await IG(qG(t,{options:i,path:r}));if(o)throw o instanceof Pe?(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(PG(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?eK(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 nK(e,t){return[...e??[],...t??[]]}tK.create=e=>{function t(...t){if(t.length===3){let[n,r,i]=t;return tK(n,{...r,use:nK(r.use,e?.use)},i)}let[n,r]=t;return tK({...n,use:nK(n.use,e?.use)},r)}return t};function rK(e,t){let n=async n=>{let r=n,i=typeof e==`function`?e:t,a=await qG(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 PG(e)&&Object.defineProperty(e,Fe,{enumerable:!1,configurable:!0,get(){return a.responseHeaders}}),e}};return n.options=typeof e==`function`?{}:e,n}rK.create=e=>{function t(t,n){if(typeof t==`function`)return rK({use:e?.use},t);if(!n)throw Error(`Middleware handler is required`);return rK({...t,method:`*`,use:[...e?.use||[],...t.use||[]]},n)}return t};const iK={};function aK(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 oK(e){let t=[];return e.metadata?.openapi?.parameters?(t.push(...e.metadata.openapi.parameters),t):(e.query instanceof $e&&Object.entries(e.query.shape).forEach(([e,n])=>{n instanceof $e&&t.push({name:e,in:`query`,schema:{type:aK(n),...`minLength`in n&&n.minLength?{minLength:n.minLength}:{},description:n.description}})}),t)}function sK(e){if(e.metadata?.openapi?.requestBody)return e.metadata.openapi.requestBody;if(e.body&&(e.body instanceof $e||e.body instanceof Ge)){let t=e.body.shape;if(!t)return;let n={},r=[];return Object.entries(t).forEach(([e,t])=>{t instanceof $e&&(n[e]={type:aK(t),description:t.description},t instanceof Ge||r.push(e))}),{required:e.body instanceof Ge?!1:!!e.body,content:{"application/json":{schema:{type:`object`,properties:n,required:r}}}}}}function cK(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 lK(e,t){return Object.entries(e).forEach(([e,t])=>{let n=t.options;if(t.path&&!n.metadata?.SERVER_ONLY&&(n.method===`GET`&&(iK[t.path]={get:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:oK(n),responses:cK(n.metadata?.openapi?.responses)}}),n.method===`POST`)){let e=sK(n);iK[t.path]={post:{tags:[`Default`,...n.metadata?.openapi?.tags||[]],description:n.metadata?.openapi?.description,operationId:n.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:oK(n),...e?{requestBody:e}:{requestBody:{content:{"application/json":{schema:{type:`object`,properties:{}}}}}},responses:cK(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:iK}}const uK=(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>`,dK=/* @__PURE__ */ (()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function fK(){return{root:{key:``},static:new dK}}function pK(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 mK(e){if(!e.includes(`{`))return;let t=pK(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 hK(e){return`__rou3_unnamed_${e}`}function gK(e){return/^(?!__rou3_|_\d)[A-Za-z_]\w*$/.test(e)?e:`__rou3_esc_`+e.replace(/[_-]/g,e=>e===`_`?`__`:`_h`)}function _K(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 vK(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 yK(e,t,n=hK){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 bK(e){return e.includes(`\\`)?e.replace(/\\([:(){}])/g,(e,t)=>`�`+`ABCDE`[`:(){}`.indexOf(t)]):e}function xK(e){return e.startsWith(`**`)?2:e===`*`||e.includes(`:`)||e.includes(`(`)||vK(e)?1:e===`\\*`?`*`:e===`\\*\\*`?`**`:e.includes(`�`)?e.replace(/\uFFFD([A-E])/g,(e,t)=>t===`A`?`:`:t===`B`?`(`:t===`C`?`)`:t===`D`?`{`:`}`):e}function SK(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 CK(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 wK(e){let t=e.split(`/`);return t.shift(),t[t.length-1]===``&&t.pop(),t}function TK(e){let t=wK(e);for(;t[t.length-1]===``;)t.pop();return t}function EK(e,t){let n=new dK;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[_K(t)]=e.groups[t]}}return n}function DK(e,t=``,n,r){t=t.toUpperCase(),n.charCodeAt(0)!==47&&(n=`/${n}`);let i=mK(n);if(i){for(let n of i)DK(e,t,n,r);return}n=bK(n);let a=TK(n),o=SK(a);if(o){for(let n of o)DK(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=xK(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]=OK(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 dK),s.static[t]=e,s=e}}let d=l.length>0,f=s.methods??=new dK;(f[t]??=[]).push({data:r||null,paramsRegexp:u,paramsMap:d?l:void 0}),d||(e.static[`/`+a.join(`/`)]=s)}function OK(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]=yK(r,n);let a=r.replace(/:([\w-]+)(?:\(([^)]*)\))?/g,(e,t,n)=>`(?<${gK(t)}>${n||`[^/]+`})`).replace(/\((?![?<])/g,()=>`(?<${hK(n++)}>`).replace(/\uFFFE(.)/g,(e,t)=>/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t);return[RegExp(`^${a}$`),n]}function kK(e,t=``,n,r){r?.normalize&&(n=CK(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=wK(n),o=AK(e.root,t,a,0);if(o!==void 0)return r?.params===!1?o:{data:o.data,params:o.paramsMap?EK(a,o.paramsMap):void 0}}function AK(e,t,n,r){if(r===n.length){if(e.methods){let r=jK(e.methods,t,n,e.key===`*`,!1);if(r)return r}return e.param?.methods&&jK(e.param.methods,t,n,!0,!0)||e.wildcard?.methods&&jK(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=AK(a,t,n,r+1);if(e)return e}}if(e.param){let i=AK(e.param,t,n,r+1);if(i)return i}if(e.wildcard&&e.wildcard.methods)return jK(e.wildcard.methods,t,n,!0,!1)}function jK(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 MK(e,t=``,n,r){r?.normalize&&(n=CK(n)),n.charCodeAt(n.length-1)===47&&(n=n.slice(0,-1));let i=wK(n),a=NK(e.root,t,i,0);return r?.params===!1?a:a.map(e=>({data:e.data,params:e.paramsMap?EK(i,e.paramsMap):void 0}))}function NK(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)PK(i,a,!0);else{let e=[];for(let t of a){let n=t.paramsMap;n?.[n.length-1]?.[2]&&e.push(t)}PK(i,e,!0)}}}if(e.param){if(r<n.length){let o=i.length;if(NK(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)}PK(i,e,!0)}}}if(r<n.length){let o=e.static?.[a];o&&NK(o,t,n,r+1,i)}if(r===n.length&&e.methods){let n=e.methods[t]||e.methods[``];n&&PK(i,n,e.key===`*`)}return i}function PK(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 FK=(e,t)=>{if(!t?.openapi?.disabled){let n={path:`/api/reference`,...t?.openapi};e.openapi=tK(n.path,{method:`GET`},async t=>{let r=await lK(e);return new Response(uK(r,n.scalar),{headers:{"Content-Type":`text/html`}})})}let n=fK(),r=fK();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)DK(n,r,t.path,t)}if(t?.routerMiddleware?.length)for(let{path:e,middleware:n}of t.routerMiddleware)DK(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=kK(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 NG(u.options.cloneRequest?e.clone():e,n),query:l,_flag:`router`,asResponse:!0,context:t?.routerContext},a=MK(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 eK(r)}catch(e){if(PG(e))return eK(e);throw e}if(t?.throwError)throw n;return PG(n)?eK(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=LG(n)?n:e,i=await a(r),o=await t?.onResponse?.(i,r);return o instanceof Response?o:i},endpoints:e}},IK=4050;function LK(e,t){return IK-UG(e,``,{...t}).length}function RK(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 zK(e,t){let n={},r=wG(t.headers?.get(`cookie`)||``);for(let[t,i]of r)(t===e||RK(e,t)!==null)&&(n[t]=i);return n}function BK(e,t,n,r){let i=LK(`${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 ${IK} byte limit and was split into ${a} chunks.`,valueSize:t.value.length,chunkCount:a,chunkSizes:o.map(e=>e.value.length)}),o}function VK(e,t){let n={};for(let r in e)n[r]={name:r,value:``,attributes:{...t,maxAge:0}};return n}const HK=e=>(t,n,r)=>{let i=zK(t,r),a=r.context.logger,o=()=>{let e=VK(i,n);for(let e in i)delete i[e];return e};return{chunk(r,s){let c=o(),l=BK(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)}}},UK=HK(`Session`),WK=HK(`Account`);function GK(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 wG(i)){let i=RK(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 KK(e,t){let n=e.context.authCookies.accountData,r={maxAge:300,...n.attributes},i=await yU(t,e.context.secretConfig,`better-auth-account`,r.maxAge),a=WK(n.name,r,e);a.setCookies(a.chunk(i,r))}async function qK(e){let t=GK(e,e.context.authCookies.accountData.name);if(t){let n=ye(await xU(t,e.context.secretConfig,`better-auth-account`));if(n)return n}return null}const JK=at(A({disableCookieCache:GW().meta({description:`Disable cookie cache and fetch session from database`}).optional(),disableRefresh:GW().meta({description:`Disable session refresh. Useful for checking session status, without updating the session`}).optional()})),YK=/* @__PURE__ */ new Map,XK=new TextEncoder,ZK={decode:(e,t=`utf-8`)=>(YK.has(t)||YK.set(t,new TextDecoder(t)),YK.get(t).decode(e)),encode:e=>XK.encode(e)},QK=(e=`SHA-256`,t=`none`)=>{let n={importKey:async(t,n)=>kU().importKey(`raw`,le(t),{name:`HMAC`,hash:{name:e}},!1,[n]),sign:async(e,r)=>{typeof e==`string`&&(e=await n.importKey(e,`sign`));let i=await kU().sign(`HMAC`,e,le(r));return t===`hex`?xe.encode(i):t===`base64`?he.encode(i):t===`base64url`||t===`base64urlnopad`?me.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`?xe.toBytes(i):i),(t===`base64`||t===`base64url`||t===`base64urlnopad`)&&(i=await he.decode(i)),kU().verify(`HMAC`,e,le(i),le(r)))};return n};function $K(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://`):ae):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&&!zH(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 eq(e){let t=$K(e),n=t(`session_token`,{maxAge:e.session?.expiresIn||fG(`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 tq(e,t,n){if(!e.context.options.session?.cookieCache?.enabled)return;let r=YW(t.session,e.context.options.session?.additionalFields),i=QW(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=lG(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=cG(c.maxAge||60,`sec`).getTime(),u=e.context.options.session?.cookieCache?.strategy||`compact`,d;if(u===`jwe`)d=await yU(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 dU(s,e.context.secret,c.maxAge||300)}else d=me.encode(JSON.stringify({session:s,expiresAt:l,signature:await QK(`SHA-256`,`base64urlnopad`).sign(e.context.secret,JSON.stringify({...s,expiresAt:l}))}),{padding:!1});let f=UK(e.context.authCookies.sessionData.name,c,e);if(f.setCookies(f.chunk(d,c)),e.context.options.account?.storeAccountCookie&&!aq(e,e.context.authCookies.accountData.name)){let n=await qK(e);if(n){if(!HW(e.context.options)||n.userId===t.user.id)await KK(e,n);else{oq(e,e.context.authCookies.accountData);let t=WK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e);t.setCookies(t.clean())}}}}async function nq(e,t){let n=e.context.options.session?.cookieCache?.strategy||`compact`;if(n===`jwe`){let n=await xU(t,e.context.secretConfig,`better-auth-session`),r=hG(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 fU(t,e.context.secret),i=hG(r);return i?{session:i,expiresAt:r?.exp?r.exp*1e3:Date.now()}:null}let r=gG(ye(ZK.decode(me.decode(t))));if(!r||!await QK(`SHA-256`,`base64urlnopad`).verify(e.context.secret,JSON.stringify({...r.session,expiresAt:r.expiresAt}),r.signature))return null;let i=hG(r.session);return i?{session:i,expiresAt:r.expiresAt}:null}async function rq(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 tq(e,t,n),e.context.setNewSession(t)}function iq(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():vG(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 aq(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():vG(e.get(`set-cookie`)||``)).some(e=>e.startsWith(i)||e.startsWith(a)))return!0;return!1}function oq(e,t){iq(e,t.name),e.setCookie(t.name,``,{...t.attributes,maxAge:0})}function sq(e,t){if(oq(e,e.context.authCookies.sessionToken),oq(e,e.context.authCookies.sessionData),e.context.options.account?.storeAccountCookie){oq(e,e.context.authCookies.accountData);let t=WK(e.context.authCookies.accountData.name,e.context.authCookies.accountData.attributes,e),n=t.clean();t.setCookies(n)}e.context.oauthConfig.storeStateStrategy===`cookie`&&oq(e,e.context.createAuthCookie(`oauth_state`));let n=UK(e.context.authCookies.sessionData.name,e.context.authCookies.sessionData.attributes,e),r=n.clean();n.setCookies(r),t||oq(e,e.context.authCookies.dontRememberToken)}const cq=_e(`better-auth:oauth-encryption:v1`);function lq(e,t){return m(QH(uU,_e(e),cq,_e(`better-auth:${t}:v1`),32))}function uq(e,t){return typeof e==`string`?lq(e,t):{keys:new Map(Array.from(e.keys,([e,n])=>[e,lq(n,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:lq(e.legacySecret,t)}}}const dq=We({callbackURL:k(),codeVerifier:k(),errorURL:k().optional(),newUserURL:k().optional(),expiresAt:Le(),oauthState:k().optional(),link:A({email:k(),userId:UW()}).optional(),requestSignUp:Je().optional(),idTokenNonce:k().optional(),serverContext:ze(k(),rt()).optional()}),fq=e=>`auth-state:${e}`;new Set(Object.keys(dq.shape));var pq=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 mq(e,t,n){let r=KH(32);if(e.context.oauthConfig.storeStateStrategy===`cookie`){let i={...t,oauthState:r},a=await IW({key:uq(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:fq(r),expiresAt:a}))throw new pq(`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 hq(e,t,n){if(!t)throw new pq(`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 pq(`State mismatch: auth state cookie not found`,{code:`state_mismatch`,details:{state:t}});try{let t=await LW({key:uq(e.context.secretConfig,`oauth-state-cookie`),data:a});i=dq.parse(JSON.parse(t))}catch(e){throw new pq(`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 pq(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});oq(e,r)}else{let r=await e.context.internalAdapter.findVerificationValue(fq(t));if(!r)throw new pq(`State mismatch: verification not found`,{code:`state_mismatch`,details:{state:t}});if(i=dq.parse(JSON.parse(r.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new pq(`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 pq(`State mismatch: State not persisted correctly`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});oq(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(fq(t))}if(i.expiresAt<Date.now())throw new pq(`Invalid state: request expired`,{code:`state_mismatch`,details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function gq(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 _q=`https://better-auth.invalid`;function vq(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,_q):new URL(e);if(n&&r.origin!==_q)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 yq=[`javascript:`,`data:`,`vbscript:`],bq={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 xq(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=vq(t,i);throw e.redirect(a)}function Sq(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:Cq,set:wq}=_H(()=>null),Tq=async()=>await Cq(),{get:Eq,set:Dq}=_H(()=>null),Oq=async e=>{await Dq({...await Eq()??{},...e})};function kq(e){return e.requiresIdTokenNonce?KH(32):void 0}async function Aq(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??KH(128),i=await Eq(),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 wq(o);try{return mq(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 jq(e){let t=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,r;try{r=await hq(e,t)}catch(t){e.context.logger.error(`Failed to parse state`,t);let r=`internal_server_error`,i=n;t instanceof pq&&(r=t.code===`state_security_mismatch`?`state_mismatch`:t.code,i=t.errorURL||n),xq(e,i,r)}return r.errorURL||(r.errorURL=n),r&&await wq(r),r}const Mq={scope:`server`};function Nq(e){return e instanceof O||e instanceof E||e?.name===`APIError`}const Pq={"Cache-Control":`no-store`,Pragma:`no-cache`};function Fq(e,t){Nq(t)&&e&&Object.defineProperty(t,Fe,{enumerable:!1,configurable:!0,value:e,writable:!1})}const Iq=rK(async()=>({})),Lq=rK.create({use:[Iq,rK(async()=>({}))]}),Rq=tK.create({use:[Iq]});function zq(e,t){let n=t.metadata?.noStore===!0;return async t=>{if(n)for(let[e,n]of Object.entries(Pq))t.setHeader(e,n);try{return await fH(t,()=>e(t))}catch(e){throw Fq(t.responseHeaders,e),e}}}function X(...e){if(e.length===3){let[t,n,r]=e;return Rq(t,n,zq(r,n))}let[t,n]=e;return Rq(t,zq(n,t))}function Bq(e){return{...e,metadata:{...e.metadata,SERVER_ONLY:!0}}}X.serverOnly=(e,t)=>X(Bq(e),t);const Vq=/[\u0000-\u001f\u007f-\u009f]/,Hq=`https://better-auth.invalid`,Uq=/%2[fF]|%5[cC]/,Wq=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(`/`)}`:``},Gq=e=>{if(Vq.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=Wq(a===-1?r:r.slice(0,a));return{scheme:n,authority:i.toLowerCase(),path:o}},Kq=e=>{if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||Vq.test(e))return!1;let t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t);if(Uq.test(n))return!1;try{return new URL(e,Hq).origin===Hq}catch{return!1}},qq=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths===!0&&Kq(e);if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return OH(t)(IH(e)||e);let n=RH(e);return n?OH(t)(n):!1}let r=LH(e);if(r===`http:`||r===`https:`||!r)return t===IH(e);let i=Gq(e),a=Gq(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 Jq(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function Yq(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function Xq(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=gq(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}const Zq=Jq(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.`),Qq=Lq(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await eJ(e),Xq(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`)}),$q=e=>Lq(async t=>{if(!t.request||Xq(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 eJ(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(Yq(e)){e.context.options.advanced?.disableOriginCheck===!0&&Zq();return}if(Xq(e)||!(t||a))return;let o=r===`null`&&n.get(`sec-fetch-site`)===`same-origin`?FH(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(o?IH(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=>qq(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 tJ=Lq(async e=>{e.request&&await nJ(e)});async function nJ(e){let t=e.request;if(!t||e.context.skipCSRFCheck||Yq(e))return;let n=t.headers;if(n.has(`cookie`))return await eJ(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 eJ(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await eJ(e,!0)}const rJ=He(),iJ=Qe();function aJ(e){return oJ(e)||sJ(e)}function oJ(e){return qe(rJ,e)}function sJ(e){return qe(iJ,e)}function cJ(e){let t=e.toLowerCase();if(t.startsWith(`::ffff:`)){let e=t.substring(7);if(oJ(e))return e}let n=e.split(`:`);if(n.length===7&&n[5]?.toLowerCase()===`ffff`){let e=n[6];if(e&&oJ(e))return e}if(t.includes(`::ffff:`)||t.includes(`:ffff:`)){let t=lJ(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 lJ(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 uJ(e,t){let n=lJ(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 dJ(e,t={}){if(oJ(e)||!sJ(e))return e.toLowerCase();let n=cJ(e);return n?n.toLowerCase():uJ(e,t.ipv6Subnet??64)}function fJ(e){if(oJ(e))return Uint8Array.from(e.split(`.`).map(e=>Number(e)));if(!sJ(e))return null;let t=cJ(e);if(t)return Uint8Array.from(t.split(`.`).map(e=>Number(e)));let n=lJ(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 pJ=/^\d+$/;function mJ(e){let t=e.lastIndexOf(`/`),n=fJ(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(!pJ.test(i))return null;let a=Number(i);return a<=r?{bytes:n,prefix:a}:null}function hJ(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 gJ(e){return e.filter(e=>mJ(e)===null)}function _J(e,t={}){let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);if(n.length===0)return null;let r=(t.trustedProxies??[]).map(mJ).filter(e=>e!==null);if(r.length>0){for(let e=n.length-1;e>=0;e--){let i=n[e],a=i?fJ(i):null;if(!i||!a)return null;if(!r.some(e=>hJ(a,e)))return dJ(i,{ipv6Subnet:t.ipv6Subnet})}return null}if(n.length!==1)return null;let i=n[0];return!i||!aJ(i)?null:dJ(i,{ipv6Subnet:t.ipv6Subnet})}const vJ=[`x-forwarded-for`];function yJ(e,t){if(t.advanced?.ipAddress?.disableIpTracking)return null;let n=`headers`in e?e.headers:e,r=t.advanced?.ipAddress?.ipAddressHeaders||vJ;for(let e of r){let r=`get`in n?n.get(e):n[e];if(typeof r==`string`){let e=_J(r,{ipv6Subnet:t.advanced?.ipAddress?.ipv6Subnet,trustedProxies:t.advanced?.ipAddress?.trustedProxies});if(e)return e}}return v()||p()?`127.0.0.1`:null}function bJ(e,t){return`${e}|${t}`}const xJ=/* @__PURE__ */ new Map,SJ=1e5;function CJ(){let e=Date.now();for(let[t,n]of xJ)e>=n.expiresAt&&xJ.delete(t);if(xJ.size<=SJ)return;let t=xJ.size-SJ,n=0;for(let e of xJ.keys())if(xJ.delete(e),++n>=t)break}function wJ(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:EJ(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 TJ(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 EJ(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function DJ(e){let t=`rateLimit`,n=e.adapter,r=Math.max(...OJ(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return r&&(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:EJ(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 OJ(e){let t=[e.rateLimit.window,...NJ().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 kJ(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){CJ();let r=Date.now(),i=xJ.get(e),a=wJ(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&xJ.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return DJ(e)}let AJ=!1;async function jJ(e,t){let n=new URL(t.baseURL).pathname,r=gq(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=yJ(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!AJ&&(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."),AJ=!0);let s=bJ(o??`no-trusted-ip`,r),c=NJ().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(`*`)?OH(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 MJ(e,t){if(!t.rateLimit.enabled)return;let n=await jJ(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=kJ(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return TJ(l??i)}function NJ(){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:PJ,set:yfe}=_H(()=>!1),FJ=()=>X(`/get-session`,{method:[`GET`,`POST`],operationId:`getSession`,query:JK,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=GK(e,e.context.authCookies.sessionData.name);if(a&&!r){let t=UK(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 nq(e,a):null;o&&a&&!s&&oq(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)oq(e,e.context.authCookies.sessionData);else{let n=e.context.sessionConfig.cookieRefreshCache;if(n===!1){e.context.session=t;let n=eG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),r=QW(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 PJ();if(r<i&&!a){let n={session:{...t.session},user:t.user,updatedAt:Date.now()};await tq(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=eG(e.context.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),o=QW(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=eG(e.context.options,{...t.session,expiresAt:new Date(t.session.expiresAt),createdAt:new Date(t.session.createdAt),updatedAt:new Date(t.session.updatedAt)}),l=QW(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 sq(e),l&&(!t||n)&&await e.context.internalAdapter.deleteSession(l.session.token),e.json(null);if(c||e.query?.disableRefresh){let t=eG(e.context.options,l.session),n=QW(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 PJ(),h=f&&!p&&!m;if(t&&!n){await tq(e,l,!!c);let t=eG(e.context.options,l.session),n=QW(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:cG(e.context.sessionConfig.expiresIn,`sec`),updatedAt:/* @__PURE__ */ new Date});if(!t)throw sq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let n=e.context.sessionConfig.expiresIn;await rq(e,{session:t,user:l.user},!1,{maxAge:n});let r=eG(e.context.options,t),i=QW(e.context.options,l.user);return e.json({session:r,user:i})}await tq(e,l,!!c);let g=eG(e.context.options,l.session),_=QW(e.context.options,l.user);return e.json({session:g,user:_})}catch(t){throw Nq(t)?t:(e.context.logger.error(`INTERNAL_SERVER_ERROR`,t),E.from(`INTERNAL_SERVER_ERROR`,Y.FAILED_TO_GET_SESSION,{cause:t}))}}),IJ=e=>BW(e.context.options),LJ=async(e,t)=>{if(e.context.session)return e.context.session;let n=await FJ()({...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)},RJ=async e=>IJ(e)?(e.context.session=null,LJ(e,{disableCookieCache:!0})):LJ(e),zJ=Lq(async e=>{let t=await LJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}}),BJ=Lq(async e=>{let t=await RJ(e);if(!t?.session)throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});Lq(async e=>{let t=await LJ(e);if(!t?.session&&(e.request||e.headers))throw E.from(`UNAUTHORIZED`,{message:`Unauthorized`,code:`UNAUTHORIZED`});return{session:t}});const VJ=Lq(async e=>{let t=await LJ(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}}),HJ=()=>X(`/list-sessions`,{method:`GET`,operationId:`listUserSessions`,use:[VJ],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=>eG(e.context.options,t)))}catch(t){throw e.context.logger.error(t),e.error(`INTERNAL_SERVER_ERROR`)}}),UJ=X(`/revoke-session`,{method:`POST`,body:A({token:k().meta({description:`The token to revoke`})}),use:[BJ],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})}),WJ=X(`/revoke-sessions`,{method:`POST`,use:[BJ],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})}),GJ=X(`/revoke-other-sessions`,{method:`POST`,requireHeaders:!0,use:[BJ],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 KJ(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 qJ(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;KJ(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 JJ=async e=>{let t=await AU(`SHA-256`).digest(new TextEncoder().encode(e));return me.encode(new Uint8Array(t),{padding:!1})};async function YJ(e,t){return!t||t===`plain`?e:t===`hashed`?JJ(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function XJ(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}}function ZJ(e,t){let n=ue(t.options),r=t.hooks;async function i(t,i,a){let o=uH(),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}`,{[ve]:`create.before`,[Ce]:i,[be]: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 bH(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 CH(async()=>{await n(`db create.after ${i}`,{[ve]:`create.after`,[Ce]:i,[be]:e},()=>r(c,o))})}return c}async function a(t,i,a,o){let s=uH(),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}`,{[ve]:`update.before`,[Ce]:a,[be]: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 bH(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 CH(async()=>{await n(`db update.after ${a}`,{[ve]:`update.after`,[Ce]:a,[be]:e},()=>r(u,s))})}return u}async function o(t,i,a,o){let s=uH(),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}`,{[ve]:`updateMany.before`,[Ce]:a,[be]: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 bH(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 CH(async()=>{await n(`db updateMany.after ${a}`,{[ve]:`updateMany.after`,[Ce]:a,[be]:e},()=>r(u,s))})}return u}async function s(t,i,a){let o=uH(),s=null;try{s=(await(await bH(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 bH(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 CH(async()=>{await n(`db delete.after ${i}`,{[ve]:`delete.after`,[Ce]:i,[be]:e},()=>r(s,o))})}return l}async function c(t,i,a){let o=uH(),s=[];try{s=await(await bH(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 bH(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 CH(async()=>{await n(`db delete.after ${i}`,{[ve]:`delete.after`,[Ce]:i,[be]:t},()=>r(e,o))})}return l}async function l(t,i,a,o){let s=uH(),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 bH(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 CH(async()=>{await n(`db delete.after ${t}`,{[ve]:`delete.after`,[Ce]:t,[be]:e},()=>r(u,s))})}return u}return{createWithHooks:i,updateWithHooks:a,updateManyWithHooks:o,deleteWithHooks:s,deleteManyWithHooks:c,consumeOneWithHooks:l}}function QJ(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}const $J=(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}=ZJ(e,t),m=t=>{let n=[...t,{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}];return f(n,`session`,{fn:async()=>{await(await bH(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=(ye(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=ye(r);if(!a)return;let o=QJ(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&&ye(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),QJ(c,o)):await i.delete(r)}async function v(e,t){if(!i)return;let r=t??await g(e);await CH(()=>_(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)=>SH(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`};KJ(e);let r;try{r=dH()}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 qJ(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 bH(e)).findMany({model:`session`,where:[{field:`userId`,value:n},{field:`expiresAt`,value:/* @__PURE__ */ new Date,operator:`gt`}]})).map(e=>eG(t.options,e));if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=ye(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(eG(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await bH(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 bH(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await bH(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=uH();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?ge():e}let y=oG(r),b={...v?{id:v}:{},ipAddress:p&&yJ(p,r)||``,userAgent:p?.get(`user-agent`)||``,..._,expiresAt:cG(l?86400:o,`sec`),userId:a,token:ge(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=ye(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=QJ(s.at(-1)?.expiresAt??b.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await bH(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=QJ(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 CH(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=ye(e);return n?{session:eG(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:QW(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await bH(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:eG(t.options,s),user:QW(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 bH(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=ye(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=eG(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=QJ(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&&ye(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),QJ(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}=ye(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=ye(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),QJ(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 bH(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 bH(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 bH(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 CH(()=>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 CH(()=>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 bH(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await bH(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 bH(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 bH(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=XJ(e.identifier,r.verification?.storeIdentifier),n=await YJ(e.identifier,t);return await c({createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=QJ(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=XJ(t,r.verification?.storeIdentifier),a=await YJ(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=ye(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=ye(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await bH(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 YJ(e,XJ(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=XJ(t,r.verification?.storeIdentifier),a=await YJ(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?ye(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}`,()=>SH(e,async()=>{let n=await bH(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=we(new Uint8Array(await AU(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),r),a=XJ(t.identifier,r.verification?.storeIdentifier),o=await YJ(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=QJ(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 YJ(e,XJ(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=ye(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=QJ(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 eY(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 tY(e,t,n=`.`,r){if(!eY(t))return tY(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]]:eY(a)&&eY(i[t])?tY(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function nY(e){return(...t)=>t.reduce((t,n)=>tY(t,n,``,e),{})}const rY=nY(),iY=/* @__PURE__ */ new Set([`metadata.google.internal`,`metadata.goog`,`metadata`,`instance-data`,`instance-data.ec2.internal`]);function aY(e){return e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function oY(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 sY(e){let t=e.indexOf(`%`);return t===-1?e:e.slice(0,t)}function cY(e){return e.replace(/\.+$/,``)}function lY(e){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function uY(e){let t=e.split(`.`);return(Number(t[0])<<24|Number(t[1])<<16|Number(t[2])<<8|Number(t[3]))>>>0}function dY(e,t,n){if(n===0)return!0;let r=n===32?4294967295:-1<<32-n>>>0;return(e&r)===(t&r)}function fY(e){if(e===`0.0.0.0`)return`unspecified`;if(e===`255.255.255.255`)return`broadcast`;let t=uY(e);return dY(t,uY(`127.0.0.0`),8)?`loopback`:dY(t,uY(`10.0.0.0`),8)||dY(t,uY(`172.16.0.0`),12)||dY(t,uY(`192.168.0.0`),16)?`private`:dY(t,uY(`169.254.0.0`),16)?`linkLocal`:dY(t,uY(`100.64.0.0`),10)?`sharedAddressSpace`:dY(t,uY(`192.0.2.0`),24)||dY(t,uY(`198.51.100.0`),24)||dY(t,uY(`203.0.113.0`),24)?`documentation`:dY(t,uY(`198.18.0.0`),15)?`benchmarking`:dY(t,uY(`224.0.0.0`),4)?`multicast`:dY(t,uY(`0.0.0.0`),8)||dY(t,uY(`192.0.0.0`),24)||dY(t,uY(`192.88.99.0`),24)||dY(t,uY(`240.0.0.0`),4)?`reserved`:`public`}function pY(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 mY(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=pY(e,1);return t&&fY(t)!==`public`?`reserved`:`public`}if(e.startsWith(`0064:ff9b:0000:0000:0000:0000:`)){let t=pY(e,6);return t&&fY(t),`reserved`}if(e.startsWith(`0064:ff9b:0001:`))return`reserved`;if(e.startsWith(`2001:0000:`)){let t=pY(e,6,{xor:!0});return t&&fY(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 hY(e){let t=cY(sY(aY(oY(e.trim())))).toLowerCase();if(t===``)return{kind:`reserved`,literal:`fqdn`,canonical:``};if(!aJ(t))return t===`localhost`||t.endsWith(`.localhost`)?{kind:`localhost`,literal:`fqdn`,canonical:t}:iY.has(t)?{kind:`cloudMetadata`,literal:`fqdn`,canonical:t}:{kind:`public`,literal:`fqdn`,canonical:t};if(lY(t))return{kind:fY(t),literal:`ipv4`,canonical:t};let n=dJ(t,{ipv6Subnet:128});return lY(n)?{kind:fY(n),literal:`ipv4`,canonical:n}:{kind:mY(n),literal:`ipv6`,canonical:n}}function gY(e){return hY(e).kind===`loopback`}function _Y(e){let t=hY(e).kind;return t===`loopback`||t===`localhost`}function vY(e){return hY(e).kind===`public`}async function yY(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=lG(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=rY(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=$J(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function bY(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function xY(e,t){let n=[];if(zH(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`||_Y(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=FH(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=S.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function SY(e){if(BH(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 CY(e){return e.advanced?.trustedProxyHeaders??!1}async function wY(e,t,n){let r=e.options.baseURL,i=GH(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:IH(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?BH(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await xY(o,c),a.trustedProviders=await EY(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=eq(a.options),a.createAuthCookie=$K(a.options)),a}async function TY(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 EY(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function DY(e){return e}async function OY(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 kY(e,t,n){try{return await OY(e,t,n)}catch{throw E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_USER_INFO)}}function AY(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function jY(e,t){return e&&(t.options.account?.encryptOAuthTokens&&AY(e)?LW({key:t.secretConfig,data:e}):e)}function MY(e,t){return t.options.account?.encryptOAuthTokens&&e?IW({key:t.secretConfig,data:e}):e}function NY(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function PY(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 FY(e,t,n,r=3600,i){return await dU({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function IY(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 FY(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 LY=X(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:A({email:Ve().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 LJ(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await FY(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await IY(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 IY(e,n.user),e.json({status:!0})}),RY=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:[$q(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=vq(e.query.callbackURL,n);throw e.redirect(r)}throw E.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await tI(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof nP?t(Y.TOKEN_EXPIRED):t(Y.INVALID_TOKEN)}let i=A({email:Ve(),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 LJ(e);if(n&&n.user.email!==i.email)return t(Y.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await FY(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},PY(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 rq(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:QW(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 FY(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},PY(e.request))),await rq(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:QW(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 LJ(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 rq(e,{session:t,user:{...a.user,emailVerified:!0}})}else await rq(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 zY(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 BY(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:zY(e.scope),idToken:e.id_token,raw:e}}function VY(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 HY(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`&&t.length>0?t:void 0}async function UY(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return me.encode(new Uint8Array(n),{padding:!1})}const WY=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],GY=new Set(WY);async function KY({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=HY(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 UY(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(_))GY.has(e)||y.searchParams.set(e,t);return y}const qY=ze(k(),k()).refine(e=>!Object.keys(e).some(e=>GY.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${WY.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional(),JY=/^Basic +(.*)$/i;function YY(e){return new URLSearchParams({v:e}).toString().slice(2)}function XY(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 ZY(e,t){let n=`${YY(e)}:${YY(t)}`;return`Basic ${he.encode(n)}`}function QY(e){let t=e.match(JY);if(!t)throw Error(`Authorization header is not a Basic credential`);let n=t[1]??``,r=new TextDecoder().decode(he.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:XY(a),clientSecret:XY(o)}}const $Y=[`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`,`ES256`,`ES384`,`ES512`,`EdDSA`];async function eX({getClientAssertion:e,context:t}){return{client_assertion:await e(t),client_assertion_type:`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`}}var tX=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 nX=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 rX=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}},iX=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 aX(e){if(typeof e==`number`)return new rX({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new rX(e);case`exponential`:return new iX(e);default:throw Error(`Invalid retry strategy`)}}const oX=[`get`,`post`,`put`,`patch`,`delete`];function sX(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return oX.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}const cX=e=>e===`.`||e===`..`,lX=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function uX(e,t){let n=t.get(e);if(n===void 0)return lX(e);if(cX(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function dX(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}=sX(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=>uX(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 fX=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},pX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function mX(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 pX.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function hX(e){try{return JSON.parse(e),!0}catch{return!1}}function gX(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 _X(e){try{return JSON.parse(e)}catch{return e}}function vX(e){return typeof e==`function`}function yX(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&vX(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&vX(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function bX(...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 xX(e){let t=new Headers(bX(e?.headers,await fX(e)));if(!t.has(`content-type`)){let n=SX(e?.body);n&&t.set(`content-type`,n)}return t}function SX(e){return gX(e)?`application/json`:null}function CX(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function wX(e,t){let{body:n}=e;return n?!gX(n)||typeof n==`string`?n:CX(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function TX(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=sX(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function EX(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var DX=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function OX(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new DX(n.issues);return n.value}function kX(e){"@babel/helpers - typeof";return kX=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},kX(e)}function AX(e,t){if(kX(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(kX(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function jX(e){var t=AX(e,`string`);return kX(t)==`symbol`?t:t+``}function MX(e,t,n){return(t=jX(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function NX(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 PX(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?NX(Object(n),!0).forEach(function(t){MX(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):NX(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const FX=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await nX(e,t),o=yX(a),s=new AbortController,c=a.signal??s.signal,l=dX(i,a),u=await xX(a),d=wX(a,u),f=TX(i,a),p=PX(PX({},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}=EX(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(PX(PX({},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=mX(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??_X)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await OX(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(PX(PX({},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??_X,b=await h.text(),x=hX(b),S=x?await y(b):null,ee={response:h,responseText:b,request:p,error:PX(PX({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var C;await e(PX(PX({},ee),{},{response:t!=null&&(C=t.hookOptions)!=null&&C.cloneResponse?h.clone():h}))}if(t?.retry){let n=aX(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 FX(e,PX(PX({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new tX(h.status,h.statusText,x?S:b);return{data:null,error:PX(PX({},S),{},{status:h.status,statusText:h.statusText})}},IX=/* @__PURE__ */ new Set([301,302,303,307,308]);function LX(e){return e.type===`opaqueredirect`||IX.has(e.status)}function RX(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.`)}async function zX(e,t){let n=!1,r=t?.onError,i=await FX(e,{...t,redirect:`manual`,async onError(e){LX(e.response)&&(n=!0),await r?.(e)}}).catch(t=>{throw n?RX(e):t});if(n)throw RX(e);return i}function BX(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function VX(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function HX(e,t){t&&e.set(`client_id`,t)}function UX(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function WX(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function GX({body:e,options:t,clientId:n,requireClientSecret:r}){r&&UX(`client_secret_post`,t),t.clientSecret&&(WX(`client_secret_post`,n),HX(e,n),e.set(`client_secret`,t.clientSecret))}function KX({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`);UX(`client_secret_basic`,t),WX(`client_secret_basic`,n),e.authorization=ZY(n,t.clientSecret)}function qX(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 JX({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){qX(e);let s=HY(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);VX(`private_key_jwt`,n,e),HX(e,s);return}let c=a??BX(n,o);if(c.method===`custom`)await c.customizeRequest({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i}),qX(e);else if(c.method===`private_key_jwt`){if(VX(c.method,n,e),WX(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await eX({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});HX(e,s);for(let[n,r]of Object.entries(t))e.set(n,r)}else if(c.method===`none`){if(VX(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);WX(c.method,s),HX(e,s)}else c.method===`client_secret_basic`?KX({headers:t,options:n,clientId:s,body:e}):GX({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}const YX=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],XX=/* @__PURE__ */ new Set([`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`,`k`]);function ZX(e){return{reserve:({key:t,expiresAt:n})=>e.reserveVerificationValue({identifier:`dpop-proof:${t}`,value:t,expiresAt:n})}}function QX(e,t){return Object.assign(Error(t),{code:e})}function $X(e){return e instanceof Error&&`code`in e&&e.code===`invalid_dpop_proof`}function eZ(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 tZ(e){return eZ(e)?.token??e}function nZ(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 rZ(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return gP(new Uint8Array(t))}async function iZ(e){return cI(e,`sha256`)}function aZ(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 oZ(e){return aZ(e.cnf)}function sZ(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function cZ(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function lZ(e,t){if(!e||e===`none`||e.startsWith(`HS`))throw QX(`invalid_dpop_proof`,`DPoP proof must use an asymmetric JWS algorithm`);if(!t.includes(e))throw QX(`invalid_dpop_proof`,`DPoP proof uses an unsupported JWS algorithm`)}function uZ(e){if(!e||typeof e!=`object`||Array.isArray(e))throw QX(`invalid_dpop_proof`,`DPoP proof header must include a public jwk`);if(e.kty===`oct`)throw QX(`invalid_dpop_proof`,`DPoP proof jwk must be asymmetric`);for(let t of XX)if(t in e)throw QX(`invalid_dpop_proof`,`DPoP proof jwk must not contain private key material`)}async function dZ(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 gP(new Uint8Array(n))}async function fZ(e,t){if(e&&!await e.reserve(t))throw QX(`invalid_dpop_proof`,`DPoP proof jti has already been used`)}async function pZ({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=YX,replayStore:l}){if(!e||e.split(`.`).length!==3)throw QX(`invalid_dpop_proof`,`DPoP proof must be a compact JWT`);let u;try{u=hI(e)}catch(e){throw QX(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof header is invalid`)}if(u.typ!==`dpop+jwt`)throw QX(`invalid_dpop_proof`,`DPoP proof typ must be "dpop+jwt"`);lZ(u.alg,c),uZ(u.jwk);let d;try{d=(await tI(e,await mI(u.jwk,u.alg),{typ:`dpop+jwt`})).payload}catch(e){throw QX(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof signature is invalid`)}let f=sZ(d,`htm`),p=sZ(d,`htu`),m=sZ(d,`jti`),h=cZ(d,`iat`);if(!f||!p||!m||h===void 0)throw QX(`invalid_dpop_proof`,`DPoP proof must include htm, htu, jti, and iat claims`);if(m.length>512)throw QX(`invalid_dpop_proof`,`DPoP proof jti is too large`);if(f.toUpperCase()!==t.toUpperCase())throw QX(`invalid_dpop_proof`,`DPoP proof htm does not match the request method`);let g,_;try{g=nZ(n),_=nZ(p)}catch(e){throw QX(`invalid_dpop_proof`,e instanceof Error?e.message:`DPoP proof htu is invalid`)}if(_!==g)throw QX(`invalid_dpop_proof`,`DPoP proof htu does not match the request URL`);if(h>o+5||o-h>s)throw QX(`invalid_dpop_proof`,`DPoP proof iat is outside the accepted window`);let v=sZ(d,`ath`);if(a&&!v)throw QX(`invalid_dpop_proof`,`DPoP proof must include an ath claim`);if(r!==void 0&&v!==await rZ(r))throw QX(`invalid_dpop_proof`,`DPoP proof ath does not match the access token`);let y=await iZ(u.jwk);if(i!==void 0&&y!==i)throw QX(`invalid_dpop_proof`,`DPoP proof key does not match the bound token`);let b=await dZ({jkt:y,htm:f.toUpperCase(),htu:g,jti:m}),x=/* @__PURE__ */ new Date((h+s)*1e3);return await fZ(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 mZ(e,t){return Object.assign(Error(t),{code:e})}function hZ(e){return e instanceof Error&&`code`in e&&(e.code===`invalid_token`||e.code===`invalid_dpop_proof`)}async function gZ({payload:e,authorization:t,proofJwt:n,method:r,url:i,replayStore:a,proofMaxAgeSeconds:o,signingAlgorithms:s}){let c=oZ(e);if(c){if(t.scheme!==`DPoP`)throw mZ(`invalid_token`,`DPoP-bound access token requires the DPoP authorization scheme`);if(!n)throw mZ(`invalid_dpop_proof`,`DPoP proof header is required`);try{await pZ({proofJwt:n,method:r,url:i,accessToken:t.token,expectedJkt:c,requireAth:!0,proofMaxAgeSeconds:o,signingAlgorithms:s,replayStore:a})}catch(e){throw $X(e)?mZ(`invalid_dpop_proof`,e.message):e}}else if(t.scheme===`DPoP`)throw mZ(`invalid_token`,`DPoP authorization requires a DPoP-bound access token`)}const _Z=/* @__PURE__ */ new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function vZ({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=bZ({refreshToken:e,options:t,extraParams:a,resource:o});return await JX({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function yZ(e,t){if(t)for(let[n,r]of Object.entries(t))_Z.has(n)||e.set(n,r)}function bZ({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&&yZ(i,n),{body:i,headers:a}}async function xZ({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await vZ({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await zX(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:zY(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}pP.code,uP.code,fP.code;const SZ=/* @__PURE__ */ new Map,CZ=/* @__PURE__ */ new WeakMap,wZ=5e3;function TZ(e,t){let n=e.get(t);return n||(n={fetchedAt:0,refetchedAt:0},e.set(t,n)),n}function EZ(e,t){return e.pending!==void 0&&t-e.pending.startedAt<wZ}async function DZ(e,t){let n=Date.now();if(!e.pending||!EZ(e,n)){let r={startedAt:n,promise:kZ(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 pP),i+wZ-n)})])}finally{clearTimeout(a)}}async function OZ(e,t,n){if(e.jwks!==t)return e.jwks;let r=Date.now();if(!EZ(e,r)){if(r-e.refetchedAt<3e4)return;e.refetchedAt=r}return DZ(e,n)}async function kZ(e){try{let t=typeof e==`string`?await zX(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{C.error(`JWKS fetch failed:`,e)}catch{}throw Error(`JWKS fetch failed`)}throw e}}async function AZ(e,t){return(await jZ(e,t)).jwks}async function jZ(e,t){let n;try{n=hI(e)}catch(e){throw e instanceof Error?e:Error(e)}let r=n.kid,i=typeof t.jwksFetch==`string`?TZ(SZ,t.jwksFetch):t.jwksCacheKey?TZ(CZ,t.jwksCacheKey):{fetchedAt:0,refetchedAt:0},a=Date.now()-i.fetchedAt<3e5?i.jwks:void 0;if(!a)return{jwks:await DZ(i,t.jwksFetch),kid:r};let o=e=>OZ(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 MZ({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=NZ({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await JX({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function NZ({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 PZ({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 MZ({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 zX(i,{method:`POST`,body:d,headers:f});if(m)throw m;return BY(p)}const FZ=[`iss`,`sub`,`aud`,`exp`,`iat`];function IZ(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:FZ,clockTolerance:30}}async function LZ(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 RZ(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await LZ(t):!1}async function bfe(e,t,n){if(![t.audience].flat().some(Boolean))throw Error(`ID token audience is not configured`);let r=await tI(e,t.jwks,IZ(t));if(n&&!await RZ(r.payload.nonce,n,t.nonceComparison))throw Error(`ID token nonce does not match`);if(t.verifyClaims&&!t.verifyClaims(r.payload))throw Error(`ID token claims were rejected`);return r}function zZ(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function BZ(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;return a?`verify`in a?await a.verify(t,n,r):t.split(`.`).length===3?(await bfe(t,a,n),!0):a.allowOpaqueToken===!0:!1}catch{return!1}}function VZ(e,t){return{linked:!1,error:{code:e,message:t}}}async function xfe(e,{link:t,userInfo:n,account:r,profile:i,scopes:a}){try{await qJ(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(!Nq(e)||!e.body?.code)throw e;return VZ(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`),VZ(bq.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return VZ(bq.EMAIL_DOES_NOT_MATCH);let o=await e.context.internalAdapter.findAccountByKey(r);if(o){if(o.userId.toString()!==t.userId.toString())return VZ(bq.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=VY(o.scope,a),i=Object.fromEntries(Object.entries({providerId:r.providerId,accessToken:await MY(r.accessToken,e.context),refreshToken:await MY(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 MY(r.accessToken,e.context),refreshToken:await MY(r.refreshToken,e.context),scope:a?.join(`,`)??r.scope}))return VZ(bq.UNABLE_TO_LINK_ACCOUNT);return await WZ(e,t.userId,n),{linked:!0}}async function HZ(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),xq(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(Nq(t))throw t;e.context.logger.error(`Better auth was unable to query your database.
|
|
61
|
+
Error: `,t),xq(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)}),f=d?.user,m=!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 qJ(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 MY(r.accessToken,e.context),refreshToken:await MY(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 KK(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 p()&&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 qJ(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 MY(r.accessToken,e.context),refreshToken:await MY(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 KK(e,o))}catch(t){if(Nq(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 WZ(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=iG(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=iG(e.context.options,p,`create`),h={accessToken:await MY(r.accessToken,e.context),refreshToken:await MY(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 SH(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 KK(e,_))}catch(t){if(Nq(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 h=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(m&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??h)&&await UZ(e,f,i,t.deferNonDatabaseWrites),h&&!f.emailVerified)return!m&&e.context.options.emailVerification?.sendOnSignIn&&await UZ(e,f,i,t.deferNonDatabaseWrites),{error:bq.EMAIL_NOT_VERIFIED,data:null,isRegister:m};let g=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:t.deferNonDatabaseWrites===!0});if(!g)return{error:`unable to create session`,data:null,isRegister:!1};if(c&&g.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:g,user:f},error:null,isRegister:m,accountCookie:l}}async function UZ(e,t,n,r){let i=e.context.options.emailVerification?.sendVerificationEmail;if(!i)return;let a=async()=>{try{let r=await FY(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 CH(a):await a()}async function WZ(e,t,n){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:r,emailVerified:i,name:a,image:o,...s}=n,c=iG(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 Sfe=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(!HY(e.clientId)||!e.clientSecret)throw C.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 KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),idToken:{jwks:e=>Cfe(e.kid),issuer:`https://appleid.apple.com`,algorithms:[`RS256`],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=>xZ({refreshToken:n,options:e,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gI(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}},Cfe=async e=>{let{data:t}=await FX(`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 mI(n,n.alg)},wfe=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 C.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),KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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 C.error(`Failed to fetch user info from Atlassian:`,e),null}},options:e}},GZ=`https://dash.cloudflare.com/oauth2/token`,KZ=e=>{let t=e.clientSecret?`client_secret_basic`:`none`;return{method:e.tokenEndpointAuthMethod??t}},Tfe=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),KY({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})=>PZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:GZ,tokenEndpointAuth:KZ(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:GZ,tokenEndpointAuth:KZ(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await FX(`https://api.cloudflare.com/client/v4/user`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n?.success||!n.result)return C.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}),Efe=e=>{if(!e.domain||!e.region||!e.userPoolId)throw C.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(!HY(e.clientId))throw C.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 C.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 KY({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})=>PZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),idToken:{jwks:t=>Dfe(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:[`RS256`],maxTokenAge:`1h`},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let n=gI(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){C.error(`Failed to decode ID token:`,e)}if(t.accessToken)try{let{data:n}=await FX(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){C.error(`Failed to fetch user info from Cognito:`,e)}return null},options:e}},Dfe=async(e,t,n)=>{let r=`https://cognito-idp.${t}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:t}=await FX(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 mI(n,n.alg)}catch(e){throw C.error(`Failed to fetch Cognito public key:`,e),e}},Ofe=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 KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},kfe=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 KY({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 PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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 qZ(e,t){let n=HY(t.clientId);if(!n||!t.clientSecret)return null;let r=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await FX(`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 Afe=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(!HY(e.clientId)||!e.clientSecret)throw C.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 KY({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})=>PZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),idToken:{jwks:Bde(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=>xZ({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){let n=!!t.idToken&&t.idToken.split(`.`).length!==3,r=t.accessToken||(n?t.idToken:void 0);return r&&!await qZ(r,e)?null:e.getUserInfo(t)}if(t.idToken&&t.idToken.split(`.`).length===3){let n=gI(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 qZ(n,e);if(!r)return null;let{data:i,error:a}=await FX(`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}),jfe=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 C.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 KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`https://api.figma.com/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return C.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 C.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},Mfe=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),KY({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 MZ({code:n,codeVerifier:r,redirectURI:i,options:e}),{data:s,error:c}=await FX(t,{method:`POST`,body:a,headers:o});return c?(C.error(`GitHub OAuth token exchange failed:`,c),null):`error`in s?(C.error(`GitHub OAuth token exchange failed:`,s),null):BY(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`https://api.github.com/user`,{headers:{"User-Agent":`better-auth`,authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i}=await FX(`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}},JZ=(e=``)=>e.split(`://`).map(e=>e.replace(/\/{2,}/g,`/`)).join(`://`),Nfe=e=>{let t=e||`https://gitlab.com`;return{authorizationEndpoint:JZ(`${t}/oauth/authorize`),tokenEndpoint:JZ(`${t}/oauth/token`),userinfoEndpoint:JZ(`${t}/api/v4/user`)}},Pfe=e=>{let{authorizationEndpoint:t,tokenEndpoint:n,userinfoEndpoint:r}=Nfe(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 KY({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})=>PZ({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({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 FX(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}},YZ=`RS256`,Ffe=[YZ],XZ=(e,t)=>e?typeof t!=`string`||!t?!1:e===`*`||t===e:!0,Ife=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(!HY(e.clientId)||!e.clientSecret)throw C.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 KY({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})=>PZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://oauth2.googleapis.com/token`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://oauth2.googleapis.com/token`}),idToken:{jwks:e=>Lfe(e.kid),issuer:[`https://accounts.google.com`,`accounts.google.com`],audience:e.clientId,algorithms:Ffe,maxTokenAge:`1h`,verifyClaims:e.hd?t=>XZ(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gI(t.idToken);if(!XZ(e.hd,n.hd))return C.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}),Lfe=async e=>{let[t]=await Rfe(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},Rfe=async e=>{let{data:t}=await FX(`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=>mI(e,YZ)))},zfe=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),KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},Bfe=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),KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},Vfe=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),KY({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 PZ({code:t,redirectURI:n,options:e,tokenEndpoint:`https://id.kick.com/oauth/token`,codeVerifier:r})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({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 FX(`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}),Hfe=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 KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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=gI(t.idToken)}catch{}if(!n){let{data:e}=await FX(`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}},Ufe=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),KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},Wfe=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 KY({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 PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},ZZ=`9188040d-6c67-4c5b-b112-36a304b66dad`,Gfe=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(!HY(e.clientId))throw C.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),KY({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 PZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:i,tokenEndpointAuth:a})},idToken:{jwks:e=>Kfe(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===ZZ||t===`consumers`&&r!==ZZ)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=gI(t.idToken);if(typeof n.oid!=`string`||n.oid.trim().length===0)return C.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 FX(`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, ${he.encode(t)}`}catch(e){C.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),xZ({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},extraParams:{scope:n.join(` `)},tokenEndpoint:i,tokenEndpointAuth:a})},options:e}},Kfe=async(e,t,n)=>{let{data:r}=await FX(`${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 mI(i,i.alg??`RS256`)},qfe=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),KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},Jfe=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),KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},Yfe=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 C.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 KY({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})=>PZ({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({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=gI(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}},Xfe=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 C.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 KY({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 PZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw C.error(`PayPal token exchange failed:`,e),new D(`FAILED_TO_GET_ACCESS_TOKEN`)}},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>{try{return await xZ({refreshToken:e,options:a,tokenEndpoint:r,tokenEndpointAuth:o})}catch(e){throw C.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 C.error(`Access token is required to fetch PayPal user info`),null;try{let n=await FX(`${i}?schema=paypalv1.1`,{headers:{Authorization:`Bearer ${t.accessToken}`,Accept:`application/json`}});if(!n.data)return C.error(`Failed to fetch user info from PayPal`),null;let r=n.data;if(t.idToken){let e;try{e=gI(t.idToken).sub}catch(e){return C.error(`Failed to decode PayPal ID token:`,e),null}let n=r.sub??r.user_id;if(!e||n!==e)return C.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 C.error(`Failed to fetch user info from PayPal:`,e),null}},options:e}},Zfe=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),KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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}},QZ=`https://backboard.railway.com/oauth/token`,Qfe=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),KY({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})=>PZ({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:QZ,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:QZ,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await FX(`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 $Z({identifier:e,namespace:t}){let n=Ve().safeParse(`${e}@${t}.placeholder.invalid`);if(!n.success)throw TypeError(`Invalid placeholder email`);return n.data}const eQ={apple:Sfe,atlassian:wfe,cloudflare:Tfe,cognito:Efe,discord:Ofe,facebook:Afe,figma:jfe,github:Mfe,microsoft:Gfe,google:Ife,huggingface:zfe,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),KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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),KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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),KY({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})=>PZ({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 C.error(`No idToken found in token`),null;let r=gI(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),KY({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})=>PZ({code:n,codeVerifier:r,authentication:`basic`,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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 FX(`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||$Z({identifier:n.data.id,namespace:`twitter`}),image:n.data.profile_image_url,emailVerified:o,...s},data:n}},options:e}},dropbox:kfe,kick:Vfe,linear:Ufe,linkedin:Wfe,gitlab:Pfe,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))GY.has(e)||e!==`client_key`&&o.searchParams.set(e,t);return o},validateAuthorizationCode:async({code:r,codeVerifier:i,redirectURI:a})=>PZ({code:r,codeVerifier:i,redirectURI:e.redirectURI||a,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async e=>xZ({refreshToken:e,options:{},tokenEndpoint:t,tokenEndpointAuth:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await FX(`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||$Z({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),KY({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})=>PZ({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=>xZ({refreshToken:e,options:n,tokenEndpoint:t,tokenEndpointAuth:r}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await FX(`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||$Z({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),KY({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})=>PZ({code:n,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:t,authentication:`post`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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:$Z({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 C.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),KY({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})=>PZ({code:t,codeVerifier:n,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>xZ({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 FX(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return C.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 C.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),KY({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})=>PZ({code:n,codeVerifier:r,redirectURI:e.redirectURI||i,options:e,deviceId:a,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>xZ({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 FX(`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})=>KY({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})=>PZ({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=>xZ({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 FX(`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:Jfe,kakao:Bfe,naver:qfe,line:Hfe,paybin:Yfe,paypal:Xfe,polar:Zfe,railway:Qfe,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)),KY({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})=>PZ({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 FX(`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))GY.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 FX(`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 FX(`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 FX(`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||$Z({identifier:o,namespace:`wechat`}),image:r.headimgurl,emailVerified:!1,...a},data:r}},options:e})},$fe=Object.keys(eQ),tQ=Ze($fe).or(k());function nQ(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const epe=X(`/list-accounts`,{method:`GET`,use:[zJ],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}=tG(e.context.options,t);return{...r,scopes:nQ(n)}}))}),tpe=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:tQ,idToken:A({token:k(),nonce:k().optional(),accessToken:k().optional(),refreshToken:k().optional()}).optional(),requestSignUp:Je().optional(),scopes:Be(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:Je().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:ze(k(),et()).optional()}),use:[zJ],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 TY(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(!zZ(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 BZ(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(Sq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await kY(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 MY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await MY(e.body.idToken.refreshToken,e.context)}).filter(([e,t])=>t!==void 0));return await e.context.internalAdapter.updateAccount(s.id,i),await WZ(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 MY(e.body.idToken.accessToken,e.context),idToken:r,refreshToken:await MY(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 WZ(e,t.user.id,a.user),e.json({url:``,status:!0,redirect:!1})}let r=kq(n),i=await Aq(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}${NY(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})}),npe=X(`/unlink-account`,{method:`POST`,body:A({accountId:k().meta({description:`The Better Auth account ID to unlink`})}),use:[VJ],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 rQ(e,t){let n=await LJ(e,{disableCookieCache:IJ(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 iQ=Ae([it({accountId:k().meta({description:`The Better Auth account ID`}),userId:k().meta({description:`The user ID associated with the account`}).optional()}),it({useAccountCookie:Ye(!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 aQ(e,t,{resolvedUserId:n,selection:r}){return(!HW(e.context.options)||t.userId===n)&&(`accountId`in r?t.id===r.accountId:!0)}async function oQ(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 qK(e);if(r&&aQ(e,r,{resolvedUserId:t,selection:n}))return{account:r,accountCookie:r}}throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND)}async function sQ(e,{resolvedUserId:t,selection:n,account:r}){let i=r??(await oQ(e,{resolvedUserId:t,selection:n})).account;if(!aQ(e,i,{resolvedUserId:t,selection:n}))throw E.from(`BAD_REQUEST`,Y.ACCOUNT_NOT_FOUND);let a=await TY(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 jY(i.refreshToken,e.context);t=await a.refreshAccessToken(n,e);let r={accessToken:await MY(t?.accessToken,e.context),accessTokenExpiresAt:t?.accessTokenExpiresAt,refreshToken:t?.refreshToken?await MY(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 KK(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 jY(i.accessToken??``,e.context),accessTokenExpiresAt:r,scopes:nQ(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 rpe=X(`/get-access-token`,{method:`POST`,body:iQ,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 sQ(e,{resolvedUserId:await rQ(e,t),selection:e.body});return e.json(n)}),ipe=X(`/refresh-token`,{method:`POST`,body:iQ,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 oQ(e,{resolvedUserId:await rQ(e,t),selection:e.body}),i=await TY(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 jY(a,e.context),o=await i.refreshAccessToken(t,e),s=o.refreshToken?await MY(o.refreshToken,e.context):a,c=o.refreshTokenExpiresAt??n.refreshTokenExpiresAt,l={accessToken:await MY(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 KK(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`})}}),ape=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:iQ},async e=>{let{userId:t}=e.query,n=await rQ(e,t),{account:r}=await oQ(e,{resolvedUserId:n,selection:e.query}),i=await TY(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 sQ(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}})});async function ope(e,t,n){if(n.iss&&t.issuer&&n.iss!==t.issuer)return e.context.logger.error(`OAuth issuer mismatch`,{expected:t.issuer,received:n.iss}),{error:bq.ISSUER_MISMATCH};if(t.requiresIdTokenNonce&&!n.idTokenNonce)return e.context.logger.error(`OAuth id_token nonce binding required but no expected nonce was found in state`,{providerId:t.id}),{error:bq.NONCE_BINDING_MISSING};let r;try{r=await t.validateAuthorizationCode({code:n.code,codeVerifier:n.codeVerifier,deviceId:n.deviceId,redirectURI:`${e.context.baseURL}${NY(t)}`})}catch(t){return e.context.logger.error(`Failed to validate authorization code`,t),{error:bq.INVALID_CODE}}if(!r)return{error:bq.INVALID_CODE};let i=await t.getUserInfo({...r,expectedIdTokenNonce:n.idTokenNonce,user:ye(n.user)??void 0});if(!i?.user)return e.context.logger.error(`Unable to get user info`),{error:bq.UNABLE_TO_GET_USER_INFO};let a=await OY(t,r,i.data).catch(n=>(e.context.logger.error(`Unable to derive provider account identity`,{providerId:t.id,error:n}),null));return a?{tokens:r,userInfo:i.user,providerProfile:DY(i.data),accountKey:a}:{error:bq.UNABLE_TO_GET_USER_INFO}}const cQ=A({code:k().optional(),error:k().optional(),device_id:k().optional(),error_description:k().optional(),state:k().optional(),user:k().optional(),iss:k().optional()}),spe=X(`/callback/:id`,{method:[`GET`,`POST`],operationId:`handleOAuthCallback`,body:cQ.optional(),query:cQ.optional(),metadata:{...Mq,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?cQ.parse(e.body):{},n=e.query?cQ.parse(e.query):{},r=cQ.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=cQ.parse(e.query);else if(e.method===`POST`)t=cQ.parse(e.body);else throw Error(`Unsupported method`)}catch(t){e.context.logger.error(`INVALID_CALLBACK_REQUEST`,t);let r=vq(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 TY(e.context.socialProviders,{value:e.params.id});if(t?.allowIdpInitiated){let n=kq(t),{state:r,codeVerifier:i}=await Aq(e,{idTokenNonce:n}),a=await t.createAuthorizationURL({state:r,codeVerifier:i,idTokenNonce:n,redirectURI:`${e.context.baseURL}${NY(t)}`});throw e.redirect(a.toString())}}if(!a){e.context.logger.error(`State not found`,i);let t=vq(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 jq(e);function _(t,r){let i=p??n,a=new URLSearchParams({error:t});r&&a.set(`error_description`,r);let o=vq(i,a);throw e.redirect(o)}if(i&&_(i,o),!r)throw e.context.logger.warn(`Code not found`),_(bq.NO_CODE);let v=await TY(e.context.socialProviders,{value:e.params.id});if(!v)throw e.context.logger.warn(`OAuth provider not found`,{providerId:e.params.id}),_(bq.PROVIDER_NOT_FOUND);let y=await ope(e,v,{code:r,codeVerifier:u,iss:l,deviceId:s,user:c,idTokenNonce:g});if(y.error)throw _(y.error);let{tokens:b,userInfo:x,providerProfile:S,accountKey:ee}=y,{accountId:C}=ee;if(!d)throw e.context.logger.error(`No callback URL found`),_(bq.NO_CALLBACK_URL);let te={...ee,...b,scope:b.scopes?.join(`,`)};if(f){let t=await xfe(e,{link:f,userInfo:x,account:te,profile:S,scopes:b.scopes});if(!t.linked)return _(t.error.code,t.error.message);throw e.redirect(d)}if(!x.email)return e.context.logger.error(Sq(v.id)),_(bq.EMAIL_NOT_FOUND);let w;try{w=await HZ(e,{userInfo:{...x,id:C,email:x.email,name:x.name||``},account:te,callbackURL:d,disableSignUp:v.disableImplicitSignUp&&!h||v.options?.disableSignUp,overrideUserInfo:v.options?.overrideUserInfoOnSignIn,source:{method:`oauth`,oauth:{providerId:v.id,profile:S}}})}catch(e){throw Nq(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:ne,user:T}=w.data;await rq(e,{session:ne,user:T});let re;try{re=(w.isRegister&&m||d).toString()}catch{re=w.isRegister&&m||d}throw e.redirect(re)});function lQ(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/&(?!amp;|lt;|gt;|quot;|#39;|#x[0-9a-fA-F]+;|#[0-9]+;)/g,`&`)}const cpe=(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
|
+
${lQ(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>`},lpe=X(`/error`,{method:`GET`,metadata:{...Mq,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?lQ(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=vq(c,o);return new Response(null,{status:302,headers:{Location:e}})}return ae&&!s.onAPIError?.customizeDefaultErrorPage?new Response(null,{status:302,headers:{Location:`/?${o.toString()}`}}):new Response(cpe(e.context.options,i,a),{headers:{"Content-Type":`text/html`}})}),upe=X(`/ok`,{method:`GET`,metadata:{...Mq,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 uQ(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 dQ(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 dpe(e,t,n,r){await SH(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 fpe(e,t){dQ(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 ppe(e,t){let n=t.body.password;typeof n==`string`&&dQ(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 fQ(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 mpe(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 hpe=X(`/request-password-reset`,{method:`POST`,body:A({email:Ve().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:[$q(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 ge(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=cG(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||3600,`sec`),a=ge(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`})}),gpe=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:[$q(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(fQ(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(fQ(e.context,n,{error:`INVALID_TOKEN`})):e.redirect(mpe(e.context,n,{token:t}))}),_pe=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;uQ(e,n),dQ(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 dpe(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})}),vpe=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:[BJ]},async e=>{let{password:t}=e.body,n=e.context.session;if(!await fpe(e,{password:t,userId:n.user.id}))throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);return e.json({status:!0})}),ype=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:tQ,disableRedirect:Je().meta({description:`Disable automatic redirection to the provider. Useful for handling the redirection yourself`}).optional(),idToken:at(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:Le().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:Be(k()).meta({description:`Array of scopes to request from the provider. This will override the default scopes passed.`}).optional(),requestSignUp:Je().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:ze(k(),et()).optional().meta({description:`Additional data to be passed through the OAuth flow`})}),bpe=()=>X(`/sign-in/social`,{method:`POST`,operationId:`socialSignIn`,body:ype,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 TY(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(!zZ(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 BZ(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(Sq(e.body.provider,{source:`id_token`}),{provider:e.body.provider}),E.from(`UNAUTHORIZED`,Y.USER_EMAIL_NOT_FOUND);let o=await kY(t,i,a.data),s=DY(a.data),c=await HZ(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===bq.EMAIL_NOT_VERIFIED?E.from(`FORBIDDEN`,Y.EMAIL_NOT_VERIFIED):E.from(`UNAUTHORIZED`,{message:c.error,code:`OAUTH_LINK_ERROR`});return await rq(e,c.data),e.json({redirect:!1,token:c.data.session.token,url:void 0,user:QW(e.context.options,c.data.user)})}let n=kq(t),{codeVerifier:r,state:i}=await Aq(e,{additionalData:e.body.additionalData,idTokenNonce:n}),a=await t.createAuthorizationURL({state:i,codeVerifier:r,idTokenNonce:n,redirectURI:`${e.context.baseURL}${NY(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})}),xpe=()=>X(`/sign-in/email`,{method:`POST`,operationId:`signInEmail`,use:[tJ],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:Je().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(!Ve().safeParse(t).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);dQ(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 FY(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},PY(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 rq(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:QW(e.context.options,a)})}),Spe=A({callbackURL:k().meta({description:`The URL to redirect to after provider logout`}).optional(),disableRedirect:Je().meta({description:`Return the provider logout URL without redirecting`}).optional(),state:k().meta({description:`State to pass to the provider logout endpoint`}).optional()}).optional(),pQ=e=>({success:!0,url:e?.url,redirect:e?.redirect}),Cpe=X(`/sign-out`,{method:`POST`,body:Spe,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)}sq(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(pQ({url:r,redirect:t}))}return e.json(pQ())}),wpe=A({name:k(),email:Ve(),password:k().nonempty(),image:k().optional(),callbackURL:k().optional(),rememberMe:Je().optional()}).and(ze(k(),et())),Tpe=()=>X(`/sign-up/email`,{method:`POST`,operationId:`signUpWithEmailAndPassword`,use:[tJ],body:wpe,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=>SH(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(!Ve().safeParse(r).success)throw E.from(`BAD_REQUEST`,Y.INVALID_EMAIL);if(!i||typeof i!=`string`)throw E.from(`BAD_REQUEST`,Y.INVALID_PASSWORD);uQ(e,i),dQ(e,i);let l=e.context.options.emailAndPassword.requireEmailVerification||e.context.options.emailAndPassword.autoSignIn===!1,u=e.context.options.emailAndPassword.autoSignIn===!1||l,d=rG(e.context.options,c,`create`),f=r.toLowerCase(),m=()=>{let t=/* @__PURE__ */ new Date,r=e.context.generateId({model:`user`})||ge(),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=$W(e.context.options,a)}else s=$W(e.context.options,{...i,...d,id:r});return e.json({token:null,user:QW(e.context.options,s)})},h=await e.context.internalAdapter.findUserByEmail(f);if(h?.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:h.user},PY(e.request))),m();throw E.from(`UNPROCESSABLE_ENTITY`,Y.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)}let g=await e.context.password.hash(i),_;try{if(_=await e.context.internalAdapter.createUser({email:f,name:n,image:a,...d,emailVerified:!1},{method:`email-password`}),!_)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_USER)}catch(t){if(Nq(t)){if(t.statusCode===403&&l)return m();throw t}throw p()&&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(!_)throw E.from(`UNPROCESSABLE_ENTITY`,Y.FAILED_TO_CREATE_USER);if(await e.context.internalAdapter.linkAccount({userId:_.id,providerId:`credential`,accountId:_.id,password:g}),e.context.options.emailVerification?.sendOnSignUp??e.context.options.emailAndPassword.requireEmailVerification){let n=await FY(e.context.secret,_.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:_,url:i,token:n},PY(e.request)))}if(u)return e.json({token:null,user:QW(e.context.options,_)});let v=await e.context.internalAdapter.createSession(_.id,s===!1,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!v)throw E.from(`BAD_REQUEST`,Y.FAILED_TO_CREATE_SESSION);return await rq(e,{session:v,user:_},s===!1),e.json({token:v.token,user:QW(e.context.options,_)})})),Epe=ze(k().meta({description:`Field name must be a string`}),et()),Dpe=()=>X(`/update-session`,{method:`POST`,operationId:`updateSession`,body:Epe,use:[zJ],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=aG(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&&IJ(e))throw sq(e),E.from(`UNAUTHORIZED`,Y.FAILED_TO_GET_SESSION);let a=i??{...n.session,...r,updatedAt:/* @__PURE__ */ new Date};return await rq(e,{session:a,user:n.user}),e.json({session:eG(e.context.options,a)})}),Ope=ze(k().meta({description:`Field name must be a string`}),et()),kpe=()=>X(`/update-user`,{method:`POST`,operationId:`updateUser`,body:Ope,use:[zJ],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=rG(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 rq(e,{session:a.session,user:s}),e.json({status:!0})}),Ape=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:Je().meta({description:`Must be a boolean value`}).optional()}),use:[BJ],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;uQ(e,t),dQ(e,t),dQ(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 SH(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 rq(e,{session:s,user:i.user}),c=s.token),e.json({token:c,user:QW(e.context.options,i.user)})}),jpe=X.serverOnly({method:`POST`,body:A({newPassword:k().meta({description:`The new password to set is required`})}),use:[BJ]},async e=>{let{newPassword:t}=e.body,n=e.context.session;uQ(e,t),dQ(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)}),Mpe=X(`/delete-user`,{method:`POST`,use:[BJ],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){dQ(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 mQ({...e,query:{token:e.body.token}}),e.json({success:!0,message:`User deleted`});if(e.context.options.user.deleteUser?.sendDeleteAccountVerification){let n=KH(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),sq(e);let r=e.context.options.user.deleteUser?.afterDelete;return r&&await r(t.user,e.request),e.json({success:!0,message:`User deleted`})}),mQ=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:[$q(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 LJ(e,{disableCookieCache:IJ(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),sq(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`})}),Npe=X(`/change-email`,{method:`POST`,body:A({newEmail:Ve().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:[BJ],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 FY(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 rq(e,{session:e.context.session.session,user:{...e.context.session.user,email:t}}),r){let n=await FY(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 FY(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 FY(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})}),hQ=nY((e,t,n)=>{if(Array.isArray(e[t])&&Array.isArray(n))return e[t]=n,!0}),gQ=/* @__PURE__ */ new WeakMap;function _Q(e,t){let n=e.options;return n?.operationId??n?.metadata?.openapi?.operationId??t??e.path??`/:virtual`}function vQ(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 yQ(e){let t=e[Fe],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 Ppe(e,t,n,r){let i=ue(e.context.options),a={};for(let o of t){let t=!1;try{t=o.matcher(e)}catch(t){let n=gQ.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=gQ.get(o.handler)??`unknown`,c=n.path??`/:virtual`,l=await i(`hook before ${c} ${s}`,{[ve]:`before`,[fe]:c,[be]:s,[pe]:r},()=>o.handler({...e,returnHeaders:!0})).catch(t=>{throw Nq(t)&&w(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),t});vQ(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=hQ(t,a);continue}return u}}return{context:a}}async function Fpe(e,t,n,r){let i=ue(e.context.options);for(let a of t){if(!a.matcher(e))continue;let t=gQ.get(a.handler)??`unknown`,o=n.path??`/:virtual`,s=await i(`hook after ${o} ${t}`,{[ve]:`after`,[fe]:o,[be]:t,[pe]:r},()=>a.handler(e)).catch(t=>{if(Nq(t))return w(e.context.logger.level,`debug`)&&(t.stack=t.errorStack),{response:t,headers:yQ(t)};throw t});vQ(e.context,s.headers),s.response!==void 0&&(e.context.returned=s.response)}return{response:e.context.returned,headers:e.context.responseHeaders}}function Ipe(e){let t=e.options.plugins||[],n=[],r=[],i=e.options.hooks?.before;i&&(gQ.set(i,`user`),n.push({matcher:()=>!0,handler:i}));let a=e.options.hooks?.after;a&&(gQ.set(a,`user`),r.push({matcher:()=>!0,handler:a}));let o=t.flatMap(e=>(e.hooks?.before??[]).map(t=>(gQ.set(t.handler,`plugin:${e.id}`),t))),s=t.flatMap(e=>(e.hooks?.after??[]).map(t=>(gQ.set(t.handler,`plugin:${e.id}`),t)));return o.length&&n.push(...o),s.length&&r.push(...s),{beforeHooks:n,afterHooks:r}}async function bQ(e,t){let n=ue(t.context.options),r=t.operationId??_Q(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??BH(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}`,{[fe]:i,[pe]:r},async()=>fH(l,async()=>{let{beforeHooks:a,afterHooks:o}=Ipe(l.context),s=await Ppe(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=hQ(t,l)}else if(s){let e=l.context.responseHeaders;return c?eK(s,{headers:e}):t.returnHeaders?{headers:e,response:s}:s}l.asResponse=!1,l.returnHeaders=!0,l.returnStatus=!0;let u=await fH(l,()=>n(`handler ${i}`,{[fe]:i,[pe]:r},()=>e(l))).catch(e=>{if(Nq(e))return{response:e,status:e.statusCode,headers:yQ(e)};throw e});if(u instanceof Response)return u;l.context.returned=u.response,l.context.responseHeaders=u.headers??void 0;let d=await Fpe(l,o,e,r);if(d.response!==void 0&&(u.response=d.response),u.headers=d.headers??u.headers,Nq(u.response)&&w(l.context.logger.level,`debug`)&&(u.response.stack=u.response.errorStack),Nq(u.response)&&!c)throw u.headers&&Object.defineProperty(u.response,Fe,{enumerable:!1,configurable:!0,writable:!1,value:u.headers}),u.response;return c?eK(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 Lpe(e,t){if(e.baseURL)return e;let n=SY(t),r=e.options.baseURL,i=zH(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 wY(e,n,CY(e.options))}catch(e){throw e instanceof D?new E(`INTERNAL_SERVER_ERROR`,{message:e.message}):e}}function Rpe(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=async e=>{let n=_Q(i,r),a=async()=>{let r=await t,a=r.checkSchema?.();a&&await a;let o=zH(r.options.baseURL)?await Lpe(r,e):r;return bQ(i,{...e,context:o,operationId:n,asResponse:e?.asResponse??BH(e?.request)})};return await mH()?a():gH(/* @__PURE__ */ new WeakMap,a)},n[r].path=i.path,n[r].options=i.options;return n}function zpe(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 xQ(e,t){let n=ue(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:Rpe({signInSocial:bpe(),callbackOAuth:spe,getSession:FJ(),signOut:Cpe,signUpEmail:Tpe(),signInEmail:xpe(),resetPassword:_pe,verifyPassword:vpe,verifyEmail:RY,sendVerificationEmail:LY,changeEmail:Npe,changePassword:Ape,setPassword:jpe,updateSession:Dpe(),updateUser:kpe(),deleteUser:Mpe,requestPasswordReset:hpe,requestPasswordResetCallback:gpe,listSessions:HJ(),revokeSession:UJ,revokeSessions:WJ,revokeOtherSessions:GJ,linkSocialAccount:tpe,listUserAccounts:epe,deleteUserCallback:mQ,unlinkAccount:npe,refreshToken:ipe,getAccessToken:rpe,accountInfo:ape,...r,ok:upe,error:lpe},e),middlewares:i}}const Bpe=(e,t)=>{let n=ue(t),{api:r,middlewares:i}=xQ(e,t),a=new URL(e.baseURL).pathname;return FK(r,{routerContext:e,openapi:{disabled:!0},basePath:a,routerMiddleware:[{path:`/**`,middleware:Qq},...i],allowedMediaTypes:[`application/json`],skipTrailingSlashes:t.advanced?.skipTrailingSlashes??!1,async onRequest(t){let r=e.options.disabledPaths||[],i=gq(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 MJ(s,e);if(c)return c;for(let t of e.options.plugins||[])if(t.onRequest){let r=await n(`onRequest ${t.id}`,{[ve]:`onRequest`,[be]:`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}`,{[ve]:`onResponse`,[be]:`plugin:${r.id}`,[eee]:t.status},()=>r.onResponse(t,e));if(i)return i.response}return t},async onError(n){if(Nq(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`?C: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}Nq(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 Vpe(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=ie(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./dist-BwJIqVtn.mjs`);n=i(r)(e)}return n.transaction||(C.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 Hpe(e){return Vpe(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./kysely-adapter-CAYiOhH_.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 Upe(e){let{indexesByTable:t,tables:n}=oe(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 Wpe={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`int8`,`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 SQ(e,t){return`${Se(e)}\u0000${Se(t)}`}function CQ(e,t){return`${e}\u0000${t}`}function wQ(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 TQ(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function EQ(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[SQ(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 Gpe(e,n,r,i){if(i)return EQ(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=SQ(t,n),a=e.nonUnique??e.non_unique??e.NON_UNIQUE,s=a===void 0?TQ(e.isUnique??e.is_unique):!TQ(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=TQ(e.isPartial),d=!TQ(e.isDisabled)&&!TQ(e.isHypothetical)&&(e.isValid===void 0||TQ(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 EQ([...o.values()])}async function Kpe(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(CQ(t,n),{maxIndexBytes:r<0?null:r})}return i}function qpe({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=x({columnName:s,dialect:t,fields:r,indexes:i});c+=(e??0)*(t===`mysql`?4:1);continue}let l=e.get(CQ(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 Jpe=class extends D{};function Ype(e,t){return e.type===`date`&&typeof e.defaultValue==`function`&&(t===`postgres`||t===`mysql`||t===`mssql`)}function Xpe(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 Zpe(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 Qpe(e,t,n){function r(e){return e.toLowerCase().split(`(`)[0].trim()}if(t===`string[]`||t===`number[]`)return e.toLowerCase().includes(`json`);let i=Wpe[n];return(Array.isArray(t)?i.string.map(e=>e.toLowerCase()):i[t].map(e=>e.toLowerCase())).includes(r(e))}async function DQ(e,{throwOnUnsafe:n=!0}={}){let{schema:r,tables:i,referenceKeys:o}=Upe(e),d=ee(e.logger),f=[],p=e=>{if(n)throw new Jpe(e);f.push(e)},{kysely:m,databaseType:h,introspectIndexes:g,schemaName:v}=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 y=await m.introspection.getTables(),b,S=y;switch(h){case`postgres`:{let e=v??await a(m);b={type:`postgres`,schema:e},d.debug(`PostgreSQL migration: Using schema '${e}' (${v?`from database.schemaName`:`from search_path`})`);try{(await m.introspection.getSchemas()).some(({name:t})=>t===e)||(v?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)}`)}S=y.filter(t=>t.schema===e&&!t.isView&&!(`isForeign`in t&&t.isForeign)),d.debug(`Found ${S.length} table(s) in schema '${e}': ${S.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)`),S=y.filter(t=>t.schema===e);break}case`mysql`:b={type:`mysql`};break;case`sqlite`:b={type:`sqlite`}}let C=await Gpe(m,b,y.map(e=>e.name),g),te=await Kpe(m,b),w=ree(l(m,r),s(S)).filter(e=>e.kind===`unexpected-required-column`).map(e=>iee(e,`database`)),ne=[],T=[],re=[],ie=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(r)){if(t.disableMigrations)continue;let n=S.find(t=>t.name===e);for(let r of t.indexes??[]){let i=r.name,a=SQ(e,i),o=C.get(a);if(o){if(!wQ(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=[...C.values()].find(t=>Se(t.name)===Se(i)&&Se(t.table)!==Se(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=ie.get(a);if(s){if(!wQ({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`)&&qpe({columnBounds:te,dbType:h,existingColumns:new Set(n.columns.map(e=>e.name)),fields:t.fields,index:r,indexes:t.indexes??[],table:e}),ie.set(a,r),re.push({table:e,index:r,name:i})}if(!n){let n=ne.findIndex(t=>t.table===e),r={table:e,fields:t.fields,order:t.order||1/0},i=ne.findIndex(e=>(e.order||1/0)>r.order);i===-1?n===-1?ne.push(r):ne[n].fields={...ne[n].fields,...t.fields}:ne.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.`),!Qpe(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&&T.push({table:e,fields:r,order:t.order||1/0})}let ae=[];v&&ne.length>0&&ae.push(m.schema.createSchema(v).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=cee({schema:i,usePlural:!1}),ue=lee({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 x({columnName:t,dialect:h,fields:n.fields,indexes:n.indexes??[]})};if(T.length){let e=/* @__PURE__ */ new Map;for(let n of T)for(let[r,i]of Object.entries(n.fields)){let a=Ype(i,h),o=Xpe(i);if(i.required!==!1&&!a&&!o){let t=e.get(n.table);if(t===void 0&&(t=await Zpe(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=_(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(ne.length)for(let e of ne){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(_(e.table,n,!1)).on(e.table).columns([n]);fe.push(t)}}ae.push(r)}for(let{table:e,index:t,name:n}of re){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&&oee(e.database)}}async function he(){return ae.map(e=>e.compile().sql).join(`;
|
|
506
|
+
|
|
507
|
+
`)+`;`}return{toBeCreated:ne,toBeAdded:T,toBeAddedIndexes:re,unsafeChanges:f,schemaProblems:w,runMigrations:me,compileMigrations:he}}function $pe(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function eme(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 tme(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.`),$pe(r.value)<120&&t.warn(`[better-auth] Warning: the current secret appears low-entropy. Use a randomly generated secret for production.`)}function nme(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 rme(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 ime(){let e=S.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 ame(){return S.CI!==`false`&&(`BUILD_ID`in S||`BUILD_NUMBER`in S||`CI`in S||`CI_APP_ID`in S||`CI_BUILD_ID`in S||`CI_BUILD_NUMBER`in S||`CI_NAME`in S||`CONTINUOUS_INTEGRATION`in S||`RUN_ID`in S)}function ome(){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 sme(){return tee(`NODE_ENV`)===`production`?`production`:ame()?`ci`:v()?`test`:`development`}async function OQ(e){let t=await AU(`SHA-256`).digest(e);return he.encode(t)}const cme=e=>f(`a-z`,`A-Z`,`0-9`)(e||32);let kQ;async function AQ(){if(kQ)return kQ;try{let e=process.cwd();if(!e)return;let t=await At.readFile(dt.join(e,`package.json`),`utf-8`);return kQ=JSON.parse(t),kQ}catch{}}async function jQ(e){if(kQ)return kQ.dependencies?.[e]||kQ.devDependencies?.[e]||kQ.peerDependencies?.[e];try{let t=process.cwd();if(!t)throw Error(`no-cwd`);let n=dt.join(t,`node_modules`,e,`package.json`),r=await At.readFile(n,`utf-8`);return JSON.parse(r).version||await MQ(e)||void 0}catch{}return MQ(e)}async function MQ(e){let t=await AQ();if(t)return{...t.dependencies,...t.devDependencies,...t.peerDependencies}[e]}async function lme(){return(await AQ())?.name}async function ume(){try{let e=_t.cpus();return{deploymentVendor:dme(),systemPlatform:_t.platform(),systemRelease:_t.release(),systemArchitecture:_t.arch(),cpuCount:e.length,cpuModel:e.length?e[0].model:null,cpuSpeed:e.length?e[0].speed:null,memory:_t.totalmem(),isWSL:await gme(),isDocker:await PQ(),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 dme(){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 NQ;async function fme(){try{return Dt.statSync(`/.dockerenv`),!0}catch{return!1}}async function pme(){try{return Dt.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}async function PQ(){return NQ===void 0&&(NQ=await fme()||await pme()),NQ}let FQ;const mme=async()=>{try{return Dt.statSync(`/run/.containerenv`),!0}catch{return!1}};async function hme(){return FQ===void 0&&(FQ=await mme()||await PQ()),FQ}async function gme(){try{return process.platform===`linux`&&(_t.release().toLowerCase().includes(`microsoft`)||Dt.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`))?!await hme():!1}catch{return!1}}let IQ=null;async function LQ(e){if(IQ)return IQ;let t=await lme();return t?(IQ=await OQ(e?e+t:t),IQ):e?(IQ=await OQ(e),IQ):(IQ=cme(32),IQ)}async function _me(){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 jQ(e);if(n)return{name:t,version:n}}}async function vme(){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 jQ(e);if(n)return{name:t,version:n}}}const yme=async function(){};async function bme(e,t){let n=e.telemetry?.debug||ne(`BETTER_AUTH_TELEMETRY_DEBUG`,!1),r=y.BETTER_AUTH_TELEMETRY_ENDPOINT;if(!r&&!t?.customTrack)return{publish:yme};let i=async e=>{t?.customTrack?await t.customTrack(e).catch(C.error):r&&(n?C.info(`telemetry event`,JSON.stringify(e,null,2)):await FX(r,{method:`POST`,body:e}).catch(C.error))},a=await(async()=>{let n=e.telemetry?.enabled!==void 0&&e.telemetry.enabled;return(ne(`BETTER_AUTH_TELEMETRY`,!1)||n)&&(t?.skipTestCheck||!v())})(),o;return a&&(o=await LQ(typeof e.baseURL==`string`?e.baseURL:void 0),i({type:`init`,payload:{config:await rme(e,t),runtime:ome(),database:await _me(),framework:await vme(),environment:sme(),systemInfo:await ume(),packageManager:ime()},anonymousId:o})),{publish:async t=>{a&&(o||=await LQ(typeof e.baseURL==`string`?e.baseURL:void 0),await i({type:t.type,payload:t.payload,anonymousId:o}))}}}function xme(e){let t=new Set(e).size;return t===0?0:Math.log2(t**+e.length)}function Sme(e,t){let n=e===`better-auth-secret-12345678901234567890`;if(!v()){if(n&&ae)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`."),xme(e)<120&&t.warn(`[better-auth] Warning: your BETTER_AUTH_SECRET appears low-entropy. Use a randomly generated secret for production.`)}}async function Cme(e,t,n){let r=BW(t);r||(t=rY(t,{session:{cookieCache:{enabled:!0,strategy:`jwe`,refreshCache:!0,maxAge:t.session?.expiresIn||604800}}})),t.database||(t=rY(t,{account:{storeAccountCookie:!0}}));let i=t.plugins||[],a=bY(t),o=ee(t.logger),s=zH(t.baseURL);if(zH(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:FH(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??eme(S.BETTER_AUTH_SECRETS),u=t.secret||S.BETTER_AUTH_SECRET||S.AUTH_SECRET||``,d,f;l?(tme(l,o),d=l[0].value,f=nme(l,u)):(d=u||`better-auth-secret-12345678901234567890`,Sme(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)},zpe(t,o);let p=t.advanced?.ipAddress?.trustedProxies;if(p&&p.length>0){let e=gJ(p);e.length>0&&o.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(`, `)}. Each entry must be an IP address or CIDR range.`)}let m=eq(t),h=ie(t),g=(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=eQ[e](n);return r.disableImplicitSignUp=n.disableImplicitSignUp,r}))).filter(e=>e!==null),_=({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:ge(n)},{publish:y}=await bme(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,C=e=>b.has(e),te=await xY(t),w=await EY(t),ne={appName:t.appName||`Better Auth`,baseURL:c||``,version:se(),socialProviders:g,options:t,oauthConfig:{storeStateStrategy:t.account?.storeStateStrategy||(r?`database`:`cookie`),skipStateCookieCheck:!!t.account?.skipStateCookieCheck},tables:h,trustedOrigins:te,trustedProviders:w,isTrustedOrigin(e,t){return this.trustedOrigins.some(n=>qq(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??ae,window:t.rateLimit?.window||10,max:t.rateLimit?.max||100,storage:t.rateLimit?.storage||(t.secondaryStorage?`secondary-storage`:`memory`)},authCookies:m,logger:o,generateId:_,session:null,secondaryStorage:t.secondaryStorage,password:{hash:t.emailAndPassword?.password?.hash||DU,verify:t.emailAndPassword?.password?.verify||OU,config:{minPasswordLength:t.emailAndPassword?.minPasswordLength||8,maxPasswordLength:t.emailAndPassword?.maxPasswordLength||128},checkPassword:ppe},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:$J(e,{options:t,logger:o,hooks:t.databaseHooks?[{source:`user`,hooks:t.databaseHooks}]:[],generateId:_}),createAuthCookie:$K(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?!!v():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:C},T=yY(ne);return lG(T)&&await T,ne.checkSchema=ot(ne.adapter),ne.explicitSchemaCheck=aee(ne.adapter),ne}const wme=async e=>{let t=await Cme(await Hpe(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 DQ(e);await t()},t},Tme=(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 see?t.message:`Could not validate the database schema. Check your database connection.`)}),e}),{api:r}=xQ(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(zH(e.baseURL))a=await wY(r,t,CY(r.options));else{a=Object.create(Object.getPrototypeOf(r),Object.getOwnPropertyDescriptors(r));let e=r.options;if(!r.options.baseURL){let n=FH(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:IH(n)||void 0},e=a.options}a.trustedOrigins=await xY(e,t),a.trustedProviders=await EY(e,t)}let{handler:o}=Bpe(a,e);return xH(a.adapter,()=>o(t))};return{handler:a,fetch:a,api:r,options:e,$context:n,$ERROR_CODES:{...i,...Y}}},Eme=e=>Tme(e,wme),RQ=vH({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 zQ(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 Dme={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*:/},Ome=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,BQ={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},kme=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Ame(e){return e instanceof Date&&!isNaN(e.getTime())}function jme(e){let t=kme.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 Ame(f)?f:null}function Mme(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 BQ)return BQ[s];if(!Ome.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(Dme).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=jme(t);if(e)return e}return i?i(e,t):t}})}catch(t){if(n)throw t;return e}}function Nme(e,t={strict:!0}){return Mme(e,t)}function VQ(e){return e==null?null:typeof e==`object`?e:ye(e)}function HQ(e){return e!=null&&typeof e==`string`}async function Pme(e,t,n){if(n.storage!==`database`&&!n.fallbackToDatabase)return;let r=t.filter(e=>HQ(e.metadata));if(r.length===0)return;let i=r.map(async t=>{let n=VQ(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 UQ(e,t,n){let r=VQ(t.metadata);if(HQ(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 WQ(e){return`api-key:${e}`}function GQ(e){return`api-key:by-id:${e}`}function KQ(e){return`api-key:by-ref:${e}`}function Fme(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 qQ(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 JQ(e,t){return t.customStorage?t.customStorage:e.context.secondaryStorage||null}function YQ(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 XQ(e,t,n){let r=WQ(t);return qQ(await n.get(r))}async function ZQ(e,t,n){let r=GQ(t);return qQ(await n.get(r))}const QQ=/* @__PURE__ */ new Map;function Ime(e,t){let n=(QQ.get(e)??Promise.resolve()).then(t,t).finally(()=>{QQ.get(e)===n&&QQ.delete(e)});return QQ.set(e,n),n}async function $Q(e,t,n){await Ime(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 e$(e,t,n,r,i){let a=Fme(t),o=KQ(t.referenceId);i.fallbackToDatabase?await Promise.all([n.set(WQ(t.key),a,r),n.set(GQ(t.id),a,r),n.delete(o)]):(await Promise.all([n.set(WQ(t.key),a,r),n.set(GQ(t.id),a,r)]),await $Q(n,o,e=>e.includes(t.id)?e:[...e,t.id]))}async function Lme(e,t,n,r){let i=KQ(t.referenceId);r.fallbackToDatabase?await Promise.all([n.delete(WQ(t.key)),n.delete(GQ(t.id)),n.delete(i)]):await Promise.all([n.delete(WQ(t.key)),n.delete(GQ(t.id)),$Q(n,i,e=>e.filter(e=>e!==t.id))])}async function t$(e,t,n){let r=JQ(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 XQ(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 e$(e,i,r,YQ(i),n),i}return n.storage===`secondary-storage`?r?await XQ(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`key`,value:t}]})}async function n$(e,t,n){let r=JQ(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 ZQ(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 e$(e,i,r,YQ(i),n),i}return n.storage===`secondary-storage`?r?await ZQ(e,t,r):null:await e.context.adapter.findOne({model:`apikey`,where:[{field:`id`,value:t}]})}async function r$(e,t,n){let r=JQ(e,n),i=YQ(t);if(n.storage!==`database`&&n.storage===`secondary-storage`){if(!r)throw Error(`Secondary storage is required when storage mode is 'secondary-storage'`);await e$(e,t,r,i,n)}}async function i$(e,t,n){let r=JQ(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 Lme(e,t,r,n)}}function a$(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 o$(e,t,n,r){let i=JQ(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=KQ(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 zQ(n,t=>ZQ(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:a$(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 zQ(l,t=>e$(e,t,i,YQ(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=KQ(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 zQ(l,t=>ZQ(e,t,i),{concurrency:10})).filter(e=>e!=null);return{apiKeys:a$(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 Rme(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 s$(e,t,n,r){let i=Rme(e);if(!i){let e=RQ.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=RQ.USER_NOT_MEMBER_OF_ORGANIZATION;throw E.from(`FORBIDDEN`,e)}if(!await zme(e,a.role,n,r,i)){let e=RQ.INSUFFICIENT_API_KEY_PERMISSIONS;throw E.from(`FORBIDDEN`,e)}return a}async function zme(e,t,n,r,i){let{hasPermission:a}=await import(`./organization-B_0UJJOj.mjs`);try{return await a({role:t,options:i,permissions:{apiKey:[r]},organizationId:n,allowCreatorAllPermissions:!0},e)}catch{return!1}}const c$=(e,t=`ms`)=>new Date(Date.now()+(t===`sec`?e*1e3:e));function Bme(e){return e instanceof E||e instanceof E||e?.name===`APIError`}const Vme=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:Le().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:Le().meta({description:`Remaining number of requests. Server side only`}).min(0).optional().nullable().default(null),metadata:et().optional(),refillAmount:Le().meta({description:`Amount to refill the remaining count of the Api Key. server-only. Eg: 100`}).min(1).optional(),refillInterval:Le().meta({description:`Interval to refill the Api Key in milliseconds. server-only. Eg: 1000`}).optional(),rateLimitTimeWindow:Le().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:Le().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:Je().meta({description:`Whether the key has rate limiting enabled. server-only. Eg: true`}).optional(),permissions:ze(k(),Be(k())).meta({description:`Permissions of the Api Key.`}).optional(),userId:UW().meta({description:`User Id of the user that the Api Key belongs to. server-only. Eg: "user-id"`}).optional(),organizationId:UW().meta({description:`Organization Id of the organization that the Api Key belongs to. Eg: 'org-id'`}).optional()});function Hme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:r}){return X(`/api-key/create`,{method:`POST`,body:Vme,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=f$(n.context,t,i),_=g.customKeyGenerator||e,v=await LJ(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`,RQ.SERVER_ONLY_PROPERTY);if(n.request&&n.body.userId!==void 0)throw E.from(`UNAUTHORIZED`,RQ.UNAUTHORIZED_SESSION);let b=g.references??`user`,x;if(b===`organization`){let e=n.body.organizationId;if(!e){let e=RQ.ORGANIZATION_ID_REQUIRED;throw E.from(`BAD_REQUEST`,e)}let t=v?.user.id||n.body.userId;if(!t)throw E.from(`UNAUTHORIZED`,RQ.UNAUTHORIZED_SESSION);await s$(n,t,e,`create`),x=e}else if(y){if(!v?.user.id){let e=RQ.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=RQ.UNAUTHORIZED_SESSION;throw E.from(`UNAUTHORIZED`,e)}x=t||e}if(l){if(g.enableMetadata===!1)throw E.from(`BAD_REQUEST`,RQ.METADATA_DISABLED);if(typeof l!=`object`)throw E.from(`BAD_REQUEST`,RQ.INVALID_METADATA_TYPE)}if(u&&!d){let e=RQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(d&&!u){let e=RQ.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw E.from(`BAD_REQUEST`,e)}if(o){if(g.keyExpiration.disableCustomExpiresTime===!0){let e=RQ.KEY_DISABLED_EXPIRATION;throw E.from(`BAD_REQUEST`,e)}let e=o/86400;if(g.keyExpiration.minExpiresIn>e){let e=RQ.EXPIRES_IN_IS_TOO_SMALL;throw E.from(`BAD_REQUEST`,e)}if(g.keyExpiration.maxExpiresIn<e){let e=RQ.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`,RQ.INVALID_PREFIX_LENGTH);if(a){if(a.length<g.minimumNameLength||a.length>g.maximumNameLength)throw E.from(`BAD_REQUEST`,RQ.INVALID_NAME_LENGTH)}else if(g.requireName)throw E.from(`BAD_REQUEST`,RQ.NAME_REQUIRED);r(n.context);let S=await _({length:g.defaultKeyLength,prefix:s||g.defaultPrefix}),ee=g.disableKeyHashing?S:await _$(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,w=f?JSON.stringify(f):te?JSON.stringify(te):void 0,ne={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?c$(o,`sec`):g.keyExpiration.defaultExpiresIn?c$(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:w};l&&(ne.metadata=l);let T;if(g.storage===`secondary-storage`&&g.fallbackToDatabase)T=await n.context.adapter.create({model:v$,data:ne}),await r$(n,T,g);else if(g.storage===`secondary-storage`){let e=n.context.generateId({model:`apikey`})||ge();T={...ne,id:e},await r$(n,T,g)}else T=await n.context.adapter.create({model:v$,data:ne});return n.json({...T,key:S,metadata:l??null,permissions:T.permissions?ye(T.permissions):null})})}function Ume({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 Wme=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 Gme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/delete`,{method:`POST`,body:Wme,use:[zJ],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`,RQ.USER_BANNED);let o=f$(t.context,e,r),s=null;if(s=await n$(t,i,o),!s||!m$(s.configId,o.configId))throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let c=f$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await s$(t,a.user.id,s.referenceId,`delete`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);try{c.storage===`secondary-storage`&&c.fallbackToDatabase?(await i$(t,s,c),await t.context.adapter.delete({model:v$,where:[{field:`id`,value:s.id}]})):c.storage===`database`?await t.context.adapter.delete({model:v$,where:[{field:`id`,value:s.id}]}):await i$(t,s,c)}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}return n(t.context),t.json({success:!0})})}const Kme=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 qme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/get`,{method:`GET`,query:Kme,use:[zJ],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=f$(t.context,e,r),s=null;if(s=await n$(t,i,o),!s||!m$(s.configId,o.configId))throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let c=f$(t.context,e,s.configId);if((c.references??`user`)===`organization`)await s$(t,a.user.id,s.referenceId,`read`);else if(s.referenceId!==a.user.id)throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);n(t.context);let l=await UQ(t,s,c),{key:u,...d}=s;return t.json({...d,metadata:l,permissions:d.permissions?ye(d.permissions):null})})}function Jme(e){return e.storage===`database`?`database`:e.customStorage?`custom:${e.configId??`default`}`:e.fallbackToDatabase?`secondary-storage-with-fallback`:`secondary-storage`}const Yme=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:WW().int().nonnegative().meta({description:`The number of API keys to return`}).optional(),offset:WW().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:Ze([`asc`,`desc`]).meta({description:`The direction to sort by`}).optional()}).optional();function Xme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/list`,{method:`GET`,use:[zJ],query:Yme,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 s$(t,r.user.id,a,`read`);let c=a??r.user.id,l=a?`organization`:`user`,u=[];if(i){let{apiKeys:n}=await o$(t,c,f$(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=Jme(t);n.has(e)||n.set(e,t)}let r=await Promise.all([...n.values()].map(e=>o$(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=>p$(t.configId)?p$(e.configId):e.configId===t.configId)?.references??`user`)===l&&t.referenceId===c);i&&(d=d.filter(e=>m$(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:VQ(e.metadata),permissions:n.permissions?ye(n.permissions):null}}),h=e.find(e=>e.storage===`database`||e.fallbackToDatabase);return h&&await t.context.runInBackgroundOrAwait(Pme(t,p,h)),t.json({apiKeys:m,total:f,limit:o,offset:s})})}const Zme=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:UW().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:Je().meta({description:`Whether the Api Key is enabled or not`}).optional(),remaining:Le().meta({description:`The number of remaining requests`}).min(1).optional(),refillAmount:Le().meta({description:`The refill amount`}).optional(),refillInterval:Le().meta({description:`The refill interval`}).optional(),metadata:et().optional(),expiresIn:Le().meta({description:`Expiration time of the Api Key in seconds`}).min(1).optional().nullable(),rateLimitEnabled:Je().meta({description:`Whether the key has rate limiting enabled.`}).optional(),rateLimitTimeWindow:Le().meta({description:`The duration in milliseconds where each request is counted. server-only. Eg: 1000`}).optional(),rateLimitMax:Le().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:ze(k(),Be(k())).meta({description:`Update the permissions on the API Key. server-only.`}).optional().nullable()});function Qme({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X(`/api-key/update`,{method:`POST`,body:Zme,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 LJ(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`,RQ.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`,RQ.SERVER_ONLY_PROPERTY);let y=f$(t.context,e,r),b=null;if(b=await n$(t,i,y),!b||!m$(b.configId,y.configId))throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let x=f$(t.context,e,b.configId);if((x.references??`user`)===`organization`)await s$(t,v.id,b.referenceId,`update`);else if(b.referenceId!==v.id)throw E.from(`NOT_FOUND`,RQ.KEY_NOT_FOUND);let S={};if(d!==void 0){if(d.length<x.minimumNameLength||d.length>x.maximumNameLength)throw E.from(`BAD_REQUEST`,RQ.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`,RQ.KEY_DISABLED_EXPIRATION);if(a!==null){let e=a/86400;if(e<x.keyExpiration.minExpiresIn)throw E.from(`BAD_REQUEST`,RQ.EXPIRES_IN_IS_TOO_SMALL);if(e>x.keyExpiration.maxExpiresIn)throw E.from(`BAD_REQUEST`,RQ.EXPIRES_IN_IS_TOO_LARGE)}S.expiresAt=a?c$(a,`sec`):null}if(s!==void 0&&x.enableMetadata===!0){if(typeof s!=`object`)throw E.from(`BAD_REQUEST`,RQ.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`,RQ.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(l!==void 0&&c===void 0)throw E.from(`BAD_REQUEST`,RQ.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`,RQ.NO_VALUES_TO_UPDATE);let ee=b;try{if(x.storage===`secondary-storage`&&x.fallbackToDatabase){let e=await t.context.adapter.update({model:v$,where:[{field:`id`,value:b.id}],update:S});e&&(await r$(t,e,x),ee=e)}else if(x.storage===`database`){let e=await t.context.adapter.update({model:v$,where:[{field:`id`,value:b.id}],update:S});e&&(ee=e)}else{let e={...b,...S,updatedAt:/* @__PURE__ */ new Date};await r$(t,e,x),ee=e}}catch(e){throw E.fromStatus(`INTERNAL_SERVER_ERROR`,{message:e?.message})}n(t.context);let C=await UQ(t,ee,x),{key:te,...w}=ee;return t.json({...w,metadata:C,permissions:w.permissions?ye(w.permissions):null})})}function l$(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:RQ.RATE_LIMIT_EXCEEDED.message,tryAgainIn:Math.ceil(i-o)}:{type:`increment`,now:n,max:a,windowStart:new Date(n.getTime()-i)}}async function u$({key:e,ctx:t,lookupOpts:n,configurations:r,schema:i,permissions:a,expectedConfigId:o,runCustomValidator:s}){let c=n.disableKeyHashing?e:await _$(e),l=await t$(t,c,n);if(!l||o!==void 0&&!m$(l.configId,o))throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);let u=f$(t.context,r,l.configId);if(s&&u.customAPIKeyValidator&&!await u.customAPIKeyValidator({ctx:t,key:e}))throw E.from(`UNAUTHORIZED`,RQ.KEY_NOT_FOUND);if(l.enabled===!1)throw E.from(`UNAUTHORIZED`,RQ.KEY_DISABLED);if(l.expiresAt&&Date.now()>new Date(l.expiresAt).getTime()){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await i$(t,l,u),await t.context.adapter.delete({model:v$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await i$(t,l,u):await t.context.adapter.delete({model:v$,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`,RQ.KEY_EXPIRED)}if(a){let e=l.permissions?ye(l.permissions):null;if(!e||!uee(e).authorize(a).success)throw E.from(`UNAUTHORIZED`,RQ.KEY_NOT_FOUND)}if(l.remaining===0&&l.refillAmount===null){let e=async()=>{u.storage===`secondary-storage`&&u.fallbackToDatabase?(await i$(t,l,u),await t.context.adapter.delete({model:v$,where:[{field:`id`,value:l.id}]})):u.storage===`secondary-storage`?await i$(t,l,u):await t.context.adapter.delete({model:v$,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`,RQ.USAGE_EXCEEDED)}return{apiKey:u.storage===`database`||u.storage===`secondary-storage`&&u.fallbackToDatabase?await $me({ctx:t,apiKey:l,opts:u,hashedKey:c}):await the({ctx:t,apiKey:l,opts:u,hashedKey:c}),opts:u}}async function $me({ctx:e,apiKey:t,opts:n,hashedKey:r}){let i=t;t.remaining!==null&&(i=await ehe(e,t)),i=await d$(e,i,n);let a=await e.context.adapter.update({model:v$,where:[{field:`id`,value:i.id}],update:{updatedAt:/* @__PURE__ */ new Date}});if(!a)throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);return n.storage===`secondary-storage`&&n.fallbackToDatabase&&await r$(e,a,n),a}async function ehe(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:v$,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:v$,where:[{field:`id`,value:t.id},{field:`remaining`,operator:`gt`,value:0}],increment:{remaining:-1}});if(!a)throw E.from(`TOO_MANY_REQUESTS`,RQ.USAGE_EXCEEDED);return a}async function d$(e,t,n){let r=l$(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:v$,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:v$,where:[{field:`id`,value:t.id}]});if(!a)throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);return d$(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:v$,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:v$,where:[{field:`id`,value:t.id}]});if(!o)throw E.from(`UNAUTHORIZED`,RQ.INVALID_API_KEY);return d$(e,o,n)}async function the({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`,RQ.USAGE_EXCEEDED);i--}let o={...nhe(t,n),remaining:i,lastRefillAt:a,updatedAt:/* @__PURE__ */ new Date},s=async()=>{let t=await t$(e,r,n);if(!t)return null;let i={...t,...o};return await r$(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`,RQ.FAILED_TO_UPDATE_API_KEY);return c}function nhe(e,t){let n=l$(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 rhe=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:ze(k(),Be(k())).meta({description:`The permissions to verify.`}).optional()});function ihe({configurations:e,schema:t,deleteAllExpiredApiKeys:n}){return X.serverOnly({method:`POST`,body:rhe},async r=>{let{configId:i,key:a}=r.body,o=f$(r.context,e,i);if(i!==void 0&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:RQ.INVALID_API_KEY,code:`KEY_NOT_FOUND`},key:null});let s=null,c;try{let l=await u$({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),Bme(e)?r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null}):r.json({valid:!1,error:{message:RQ.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 UQ(r,s,c)),u.permissions=u.permissions?ye(u.permissions):null,r.json({valid:!0,error:null,key:s===null?null:{...u,metadata:d}})})}function f$(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=RQ.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 p$(e){return!e||e==="default"}function m$(e,t){return p$(e)&&p$(t)?!0:e===t}let h$=null;async function g$(e,t=!1){h$&&!t&&(/* @__PURE__ */ new Date()).getTime()-h$.getTime()<1e4||(h$=/* @__PURE__ */ new Date,await e.adapter.deleteMany({model:v$,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 ahe({defaultKeyGenerator:e,configurations:t,schema:n}){return{createApiKey:Hme({defaultKeyGenerator:e,configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),verifyApiKey:ihe({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),getApiKey:qme({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),updateApiKey:Qme({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),deleteApiKey:Gme({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),listApiKeys:Xme({configurations:t,schema:n,deleteAllExpiredApiKeys:g$}),deleteAllExpiredApiKeys:Ume({deleteAllExpiredApiKeys:g$})}}const ohe=({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?Nme(e):null}}}}}}),_$=async e=>{let t=await AU(`SHA-256`).digest(new TextEncoder().encode(e));return me.encode(new Uint8Array(t),{padding:!1})},v$=`apikey`;function she(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=sG(ohe({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=KH(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=ahe({defaultKeyGenerator:a,configurations:r,schema:i});return{id:`api-key`,version:`1.7.12`,$ERROR_CODES:RQ,hooks:{before:[{matcher:e=>!!s(e),handler:Lq(async e=>{let{key:t,config:n}=s(e);if(typeof t!=`string`)throw E.from(`BAD_REQUEST`,RQ.INVALID_API_KEY_GETTER_RETURN_TYPE);if(t.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:t}))throw E.from(`FORBIDDEN`,RQ.INVALID_API_KEY);let{apiKey:a}=await u$({key:t,ctx:e,lookupOpts:n,configurations:r,schema:i,expectedConfigId:n.configId}),o=g$(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=RQ.INVALID_REFERENCE_ID_FROM_API_KEY;throw E.from(`UNAUTHORIZED`,e)}let c=await e.context.internalAdapter.findUserById(a.referenceId);if(!c){let e=RQ.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?yJ(e.request,e.context.options):null,createdAt:/* @__PURE__ */ new Date,updatedAt:/* @__PURE__ */ new Date,expiresAt:a.expiresAt||c$(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}}function y$(e){return e?.jwks?.keyPairConfig?.alg??`EdDSA`}const b$=(e,t)=>({getAllKeys:async n=>t?.adapter?.getJwks?await t.adapter.getJwks(n):await(await bH(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 bH(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 bH(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 bH(e)).findMany({model:`jwks`});if(!i)return;let a=y$(t),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 bH(e)).create({model:`jwks`,data:{...r,createdAt:/* @__PURE__ */ new Date}})});function x$(e,t){return typeof e==`number`?e:e instanceof Date?Math.floor(e.getTime()/1e3):t+fG(e)}async function che(e){let{alg:t,...n}=e?.jwks?.keyPairConfig??{alg:`EdDSA`,crv:`Ed25519`},{publicKey:r,privateKey:i}=await Hde(t,{...n,extractable:!0});return{publicWebKey:await oI(r),privateWebKey:await oI(i),alg:t,cfg:n}}async function S$(e,t){let{publicWebKey:n,privateWebKey:r,alg:i,cfg:a}=await che(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 IW({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 b$(e.context.adapter,t).createJwk(e,d)}async function C$(e,t,n){if(t?.jwt?.sign)return null;let r=b$(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=y$(t);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=y$(t),a=t?.jwks?.keyPairConfigs?.find(e=>e.alg===n.signingAlgorithm),o=r===n.signingAlgorithm;if(a||o)i=await S$(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=y$(t);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 S$(e,t)}let a=t?.jwks?.disablePrivateKeyEncryption?i.privateKey:await LW({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??y$(t),s=await mI(JSON.parse(a),o);return{alg:o,kid:i.id,privateKey:s}}async function w$(e,t){let{options:n}=t,r=t.payload,i=Math.floor(Date.now()/1e3),a=r.iat,o=r.exp,s=x$(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((!(u??d)||!(f??p))&&e.context.logger.warn("[better-auth] The JWT plugin signed a JWT without an issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options."),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 C$(e,n,{signingKeyId:t.signingKeyId,signingAlgorithm:t.signingAlgorithm}),_=new rI(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 T$(e,t){let n=t?.jwt?.definePayload?await t.jwt.definePayload(e.context.session):e.context.session.user;return await w$(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 E$(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 lhe(e,t,n){let r=hI(t).kid;if(!r)return e.context.logger.debug(`Cookie-cache JWT missing kid in header`),null;let i=await b$(e.context.adapter,n).getAllKeys(e);if(!i?.length)return e.context.logger.debug(`No JWKS keys available for cookie-cache JWT`),null;let a=i.find(e=>e.id===r);if(!a)return e.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${r}`),null;let o=a.alg??y$(n);return{alg:o,publicKey:await mI(JSON.parse(a.publicKey),o)}}async function uhe(e,t,n,r){let i=await C$(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 rI({...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(E$(e)).setAudience(`better-auth:session-cache`).setSubject(t.user.id).sign(i.privateKey)}async function dhe(e,t,n){try{if(hI(t).typ!==`better-auth.session-cache+jwt`)return null;let r=await lhe(e,t,n);if(!r)return null;let{payload:i}=await tI(t,r.publicKey,{...TG({issuer:E$(e)}),algorithms:[r.alg]}),a=EG(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 fhe(e){return{sign:(t,n,r)=>uhe(t,n,r,e),verify:(t,n)=>dhe(t,n,e)}}const phe={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 mhe(e,t){let n=dH();try{let r=e.split(`.`);if(r.length!==3)return null;let i=new TextDecoder().decode(he.decode(r[0])),a=JSON.parse(i).kid;if(!a)return n.context.logger.debug(`JWT missing kid in header`),null;let o=await b$(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=JSON.parse(s.publicKey),l=s.alg??y$(t),u=await mI(c,l),d=typeof n.context.options.baseURL==`string`?n.context.options.baseURL:void 0,f=t?.jwt?.issuer??d,p=t?.jwt?.audience??d;(!f||!p)&&n.context.logger.warn("[better-auth] The JWT plugin is verifying a JWT without checking its issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");let{payload:m}=await tI(e,u,{issuer:f,audience:p,algorithms:[l]});return!m.sub||!m.aud?null:m}catch(e){return n.context.logger.debug(`JWT verification failed`,e),null}}const hhe=A({payload:ze(k(),et()),overrideOptions:ze(k(),et()).optional()}),ghe=A({token:k(),issuer:k().optional()}),_he=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.12`,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:fhe(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=b$(t.context.adapter,e),r=await n.getAllKeys(t);if((!r||r?.length===0)&&(await S$(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??y$(e),crv:t.crv??c,...JSON.parse(t.publicKey),kid:t.id}))})}),getToken:X(`/token`,{method:`GET`,requireHeaders:!0,use:[zJ],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 T$(t,e);return t.json({token:n})}),signJWT:X.serverOnly({method:`POST`,metadata:{$Infer:{body:{}}},body:hhe},async t=>{let n=await w$(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:ghe},async t=>{let n=t.body.issuer?{...e,jwt:{...e?.jwt,issuer:t.body.issuer}}:e,r=await mhe(t.body.token,n);return t.json({payload:r})})},hooks:{after:[{matcher(e){return e.path===`/get-session`},handler:Lq(async t=>{if(e?.disableSettingJwtHeader)return;let n=t.context.session||t.context.newSession;if(n&&n.session){let n=await T$(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:sG(phe,e?.schema)}};var D$=Object.defineProperty,O$=(e,t)=>{let n={};for(var r in e)D$(n,r,{get:e[r],enumerable:!0});return t||D$(n,Symbol.toStringTag,{value:`Module`}),n};const k$=`ba_iat`,A$=`ba_pl`,j$=`ba_param`;function M$(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 vhe(e){e.delete(j$);let t=[.../* @__PURE__ */ new Set([...e.keys(),j$])].sort();for(let n of t)e.append(j$,n)}function yhe(e){let t=new URLSearchParams(e).get(k$);if(!t)return null;let n=Number(t);return!Number.isFinite(n)||n<=0?null:new Date(n)}const bhe=[`authorization_code`,`client_credentials`,`refresh_token`],N$=[`client_secret_basic`,`client_secret_post`,`private_key_jwt`],xhe=[`none`,...N$],She=new Set(xhe);function P$(e,t){if(!(t.trim().length>0))throw new D(`OAuth Provider extension ${e} cannot be empty`)}function F$(e,t){P$(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 Che(e){F$(`grant type`,e)}function whe(e){if(P$(`token_endpoint_auth_method`,e),She.has(e))throw new D(`OAuth Provider extension token_endpoint_auth_method is reserved: ${e}`)}function The(e){if(F$(`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 Ehe(e){let t=Object.keys(e.grants??{});for(let e of t)Che(e);let n=[],r=[];for(let[t,i]of Object.entries(e.clientAuthentication??{})){whe(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)The(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)P$(`client discovery id`,e);return{grantTypes:t,authMethods:n,assertionTypes:r,clientDiscoveryIds:i}}function I$(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 L$(e){let t=(e??[]).map(Ehe);I$(`grant type`,t.flatMap(e=>e.grantTypes)),I$(`token_endpoint_auth_method`,t.flatMap(e=>e.authMethods)),I$(`client_assertion_type`,t.flatMap(e=>e.assertionTypes)),I$(`client discovery id`,t.flatMap(e=>e.clientDiscoveryIds))}function R$(e){return e.extensions??[]}function z$(e){return R$(e).flatMap(e=>{let t=e.clientDiscovery;return t?Array.isArray(t)?t:[t]:[]})}function Dhe(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];L$(i),n.options.extensions=i}function Ohe(e){return R$(e).flatMap(e=>Object.keys(e.grants??{}))}function B$(e){return Array.from(/* @__PURE__ */ new Set([...e.grantTypes??bhe,...Ohe(e)]))}function khe(e,t){for(let n of R$(e)){let e=n.grants?.[t];if(e)return e}}function V$(e){return R$(e).flatMap(e=>Object.keys(e.clientAuthentication??{}))}function H$(e,t){return Array.from(/* @__PURE__ */ new Set([...t?.includeNone?[`none`]:[],...N$,...V$(e)]))}function U$(e,t){return t?V$(e).includes(t):!1}function Ahe(e,t){if(t!==`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`)for(let n of R$(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 W$(e,t,n,r){let i={...r};for(let a of R$(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 G$(e,t){let n={};for(let r of R$(e)){let e=await t(r)??{};for(let[t,r]of Object.entries(e))t in n?C.warn(`oauth-provider: two extensions contributed the claim "${t}"; keeping the first-registered value.`):n[t]=r}return n}function jhe(e,t){return G$(e,e=>e.claims?.accessToken?.(t))}function Mhe(e,t){return G$(e,e=>e.claims?.idToken?.(t))}function Nhe(e,t){return G$(e,e=>e.claims?.userInfo?.(t))}function Phe(e){return R$(e).some(e=>e.claims?.userInfo)}function Fhe(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 Ihe(){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 K$=e=>{let t=e.getPlugin(`jwt`);if(!t)throw new D(`jwt_config`);return t},Lhe=/* @__PURE__ */ new Set([pP.code,uP.code,fP.code]);function q$(e){return e instanceof eP&&!Lhe.has(e.code)}function J$(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 Rhe(e){if(e instanceof Date||!e||typeof e!=`object`)return J$(e);let t=J$(e.createdAt)??J$(e.created_at);if(t)return t;let n=e.session;if(n&&typeof n==`object`)return J$(n.createdAt)??J$(n.created_at)}function Y$(e){if(typeof e==`string`)return[e];if(e?.length)return e}function X$(e){if(typeof e==`string`)return e;if(e?.length)return e.length===1?e.at(0):e}const Z$=/* @__PURE__ */ new WeakMap;function zhe(e){let t=Z$.get(e);if(t)return t;let n=Ihe();return Z$.set(e,n),n}async function Q$(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 zW(M$(n).toString(),t);return i.length===1&&!!r&&SU(r,o)&&/* @__PURE__ */ new Date(a*1e3)>=/* @__PURE__ */ new Date}function $$(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 e1(e,t,n){let r=zhe(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=z$(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 t1(e){return e.reduce((e,t)=>({...e,...t.discoveryMetadata??{}}),{})}const n1=async e=>{let t=await AU(`SHA-256`).digest(new TextEncoder().encode(e));return me.encode(new Uint8Array(t),{padding:!1})};async function r1(e,t,n){if(t===`encrypted`)return await LW({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 Bhe(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 n1(r):void 0;return!!e&&SU(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&&SU(e,n)}}if(i===`encrypted`)try{let t=await r1(e,i,n);return!!r&&SU(t,r)}catch{return!1}if(typeof i==`object`&&`decrypt`in i){let t=await r1(e,i,n);return!!r&&SU(t,r)}throw new D(`Unsupported verify storageMethod type '${i}'`)}async function i1(e,t,n){let r=t.storeClientSecret??(t.disableJwtPlugin?`encrypted`:`hashed`);if(r===`encrypted`)return await IW({key:e.context.secretConfig,data:n});if(r===`hashed`)return await n1(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 a1(e=`hashed`,t,n){if(e===`hashed`)return await n1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`storeToken: unsupported storageMethod type '${e}'`)}async function o1(e=`hashed`,t,n){if(e===`hashed`)return await n1(t);if(typeof e==`object`&&`hash`in e)return await e.hash(t,n);throw new D(`getStoredToken: unsupported storageMethod type '${e}'`)}const s1=/^Basic +/i,Vhe=/^([!#$%&'*+\-.^_`|~0-9A-Za-z]+)(?=\s|$)/;function Hhe(e){return e.match(Vhe)?.[1]}const c1=[`client_secret`,`client_assertion`,`client_assertion_type`];function l1(e){throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:e})}async function Uhe(e,t={}){let n;t.client_id!==void 0&&t.client_id!==``&&(typeof t.client_id!=`string`&&l1(`client_id must be a string`),n=t.client_id);let r={},i=(e,t)=>{t!==void 0&&t!==``&&(typeof t!=`string`&&l1(`${e} must be a string`),r[e]=t)};for(let e of c1)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&&l1(`client_id must not be repeated`),n=r[0];for(let e of c1){let n=t.getAll(e).filter(e=>e.length>0);n.length>1&&l1(`${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)&&l1(`A request must use only one client authentication method`),t.client_id=n;for(let e of c1)t[e]=r[e];return{detected:a||Object.keys(r).length>0}}function Whe(e){if(s1.test(e))try{let{clientId:t,clientSecret:n}=QY(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 u1(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 d1(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 f1(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 p1(e,t,n,r,i,a,o,s){let c=await e1(e,t,n);c||f1(`client not found`,{method:s}),c.disabled&&f1(`client is disabled`,{method:s});let l=c.tokenEndpointAuthMethod??`client_secret_basic`;if(s&&l!==s&&f1(`client registered for ${l} cannot use ${s}`,{method:s}),(c.tokenEndpointAuthMethod===`private_key_jwt`||U$(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&&f1(`client secret must be provided`,{method:s}),r&&!c.clientSecret&&f1(`public client, client secret should not be received`,{method:s}),r&&!await Bhe(e,t,c.clientSecret,r)&&f1(`invalid client_secret`,{method:s})),d1(c,i),o&&!u1(c,o))throw new O(`BAD_REQUEST`,{error_description:`client is not authorized to use grant type ${o}`,error:`unauthorized_client`});return c}function m1(e){if(e)return typeof e==`string`?JSON.parse(e):e}function h1(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 g1(e,t,n){let r={...e.body??{}};await Uhe(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=Ahe(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(()=>p_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&&!s1.test(i)){let e=Hhe(i);if(!e)throw new O(`BAD_REQUEST`,{error:`invalid_request`,error_description:`Invalid authorization header format`});f1(`unsupported authorization scheme`,{scheme:e})}if(i&&s1.test(i)){let e=Whe(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 _1(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 Ghe(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 Khe(e,t,n){return zW(`${Ghe(t)}.${e}`,n)}async function v1(e,t,n){return t.subjectType===`pairwise`&&n.pairwiseSecret?Khe(e,t,n.pairwiseSecret):e}async function y1(e,t){return await e.postLogin?.consentReferenceId?.(t)||void 0}async function b1(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 x1(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 S1(e,t){if(!t)return!1;let n=J$(e);return n?n.getTime()>=t.getTime():!1}function C1(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 w1(e){let t=new URLSearchParams(e);return t.delete(`max_age`),t}function T1(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 qhe=/^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/i,Jhe=/* @__PURE__ */ new Set([`http:`,`https:`,`ws:`,`wss:`,`file:`,`ftp:`,`mailto:`,`javascript:`,`data:`,`vbscript:`,`blob:`,`about:`,`view-source:`]);function E1(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(`//`)&&qhe.test(t)}function Yhe(e){return Jhe.has(e.protocol)||e.host.length===0?!1:e.pathname.startsWith(`/`)}function D1(e){return E1(e)||Yhe(e)}const O1=nee().superRefine((e,t)=>{let n;try{n=new URL(e)}catch{return t.addIssue({code:`custom`,message:`URL must be parseable`,fatal:!0}),Ke}yq.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:`&&!_Y(n.host)&&t.addIssue({code:`custom`,message:`Redirect URI must use HTTPS (HTTP allowed only for loopback hosts)`}))}),Xhe=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`nbf`,`iat`,`jti`,`auth_time`,`nonce`,`acr`,`amr`,`azp`,`sid`,`at_hash`,`c_hash`,`s_hash`]);function k1(e){if(!e)return{};let t=[],n=Object.create(null);for(let[r,i]of Object.entries(e))Xhe.has(r)?t.push(r):n[r]=i;return t.length>0&&C.warn(`oauth-provider: stripped reserved id-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}const A1=ze(k(),rt()).nullable(),Zhe=We({essential:Je().optional(),value:k().optional(),values:Be(k()).optional()}).nullable(),Qhe=A({acr:Zhe.optional()}).catchall(A1),$he=We({userinfo:ze(k(),A1).optional(),id_token:Qhe.optional()});function ege(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}function j1(e){let t=ege(e),n=$he.safeParse(t);return n.success?n.data:void 0}const M1=Ae([k(),ze(k(),rt())]),tge=M1,N1=M1.refine(e=>j1(e)!==void 0,{error:`claims must be a valid Claims request object`});function nge(e){return e===void 0||j1(e)!==void 0}function P1(e,t){let n=j1(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 rge(e,t){let n=j1(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 ige(e,t){let n=j1(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 F1(e){let t=e.split(` `).filter(e=>e!==``);return t.length<=1?{}:{given:t.slice(0,-1).join(` `),family:t.at(-1)}}const I1={name:{scope:`profile`,resolve:e=>e.name??void 0},picture:{scope:`profile`,resolve:e=>e.image??void 0},given_name:{scope:`profile`,resolve:e=>F1(e.name).given},family_name:{scope:`profile`,resolve:e=>F1(e.name).family},email:{scope:`email`,resolve:e=>e.email??void 0},email_verified:{scope:`email`,resolve:e=>e.emailVerified??!1}},L1=Object.keys(I1);function R1(e){return e.advertisedMetadata?.claims_supported??e.claims??[]}const age=/* @__PURE__ */ new Set([`iss`,`sub`,`aud`,`exp`,`iat`,`jti`,`client_id`,`scope`,`auth_time`,`acr`,`amr`,`cnf`]);function oge(e){if(!e)return{};let t=[],n={};for(let[r,i]of Object.entries(e))age.has(r)?t.push(r):n[r]=i;return t.length>0&&C.warn(`oauth-provider: stripped reserved access-token claim name(s): ${t.join(`, `)}. The AS owns these claim values.`),n}async function z1(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 jhe(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 oge({...p,...d??{},...m,...f})}const sge=[`javascript:`,`data:`,`vbscript:`],B1=k().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:`custom`,message:`resource must be an absolute URI`,fatal:!0}),Ke;e.includes(`#`)?t.addIssue({code:`custom`,message:`resource must not contain a fragment`}):sge.includes(new URL(e).protocol)&&t.addIssue({code:`custom`,message:`resource cannot use javascript:, data:, or vbscript: scheme`})}),cge=Ze([`none`,`consent`,`login`,`create`,`select_account`]),lge=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=cge.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`})}}),V1=A({keys:Be(ze(k(),rt())).min(1)}),uge=Ae([Le(),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`}),Ke):n}),dge=k().regex(/^[A-Za-z0-9_-]{43}$/,`dpop_jkt must be a base64url-encoded SHA-256 JWK thumbprint`),H1=A({response_type:k().pipe(Ze([`code`])).optional(),request:k().optional(),request_uri:k().optional(),redirect_uri:O1.optional(),scope:k().optional(),state:k().optional(),client_id:k().min(1,`client_id is required`),prompt:lge.optional(),display:k().optional(),ui_locales:k().optional(),max_age:uge.optional(),acr_values:k().optional(),login_hint:k().optional(),id_token_hint:k().optional(),code_challenge:k().optional(),code_challenge_method:k().pipe(Ze([`S256`])).optional(),nonce:k().optional(),claims:tge.optional(),dpop_jkt:dge.optional(),resource:Ae([B1,Be(B1).min(1)]).optional()}).passthrough(),fge=H1.extend({redirect_uri:O1.optional(),claims:N1.optional()}),pge=A({type:Ye(`authorization_code`),query:fge,sessionId:k(),userId:k(),referenceId:k().optional(),authTime:Le().optional(),resource:Be(k()).optional()}).passthrough(),U1=A({redirect_uris:Be(O1).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:Be(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:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),token_endpoint_auth_method:k().trim().min(1).optional(),jwks:V1.optional(),jwks_uri:k().optional(),grant_types:Be(k().trim().min(1)).min(1).optional(),response_types:Be(Ze([`code`])).optional(),application_type:Ze([`web`,`native`]).optional(),subject_type:Ze([`public`,`pairwise`]).optional(),dpop_bound_access_tokens:Je().optional(),resources:Be(B1).optional(),skip_consent:Ue({error:`skip_consent cannot be set during dynamic client registration`}).optional()}),mge=U1.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:Le().int().nonnegative().optional(),client_id_issued_at:Le().int().nonnegative().optional()}).loose(),W1=[`EdDSA`,`ES256`,`ES512`,`PS256`,`RS256`],hge=new Set(W1);async function G1(e,t){let n=e.identifierValidator;if(n)return await n(t)?{ok:!0}:{ok:!1,reason:`resource identifier ${t} failed validation`};let r=B1.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 gge(e,t){let n=await G1(e,t);if(!n.ok)throw new E(`BAD_REQUEST`,{error:`invalid_target`,error_description:n.reason})}const _ge=e=>`${e}/oauth2/userinfo`;async function vge(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 yge(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 K1(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=>Z1(e,t,n)))).every(Boolean)}async function q1(e,t,n){let r=yge(n.resource),i=n.requestedScopes.includes(`openid`),a=_ge(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 Z1(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}=J1(t);c&&s.length>0&&await bge(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 bge(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 xge(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 Sge(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 J1(e){return e.enforcePerClientResources===void 0?{value:!0,source:`default`}:{value:e.enforcePerClientResources,source:`explicit`}}const Y1=/* @__PURE__ */ new Map;function X1(e){e===void 0?Y1.clear():Y1.delete(e)}async function Z1(e,t,n){if(await e0(e.context,t),t.cachedResources?.has(n)){let e=Y1.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)&&Y1.set(n,Object.assign({},r)),r}function Cge(e){return e.name??e.identifier}function wge(e){let t=[];if(e.resources?.length)for(let n of e.resources)t.push(typeof n==`string`?{identifier:n}:n);return t}function Q1(e,t){return{identifier:e.identifier,name:Cge(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 Tge(e,t,n){if(t===`overwrite`){let{identifier:t,createdAt:r,...i}=Q1(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 Ege=/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 Dge(e,t){let n=!1,r=t;for(let e=0;r&&!n&&e<5;e++)n=Ege.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 $1=/* @__PURE__ */ new WeakMap;function Oge(e,t){let n=e.adapter,r=$1.get(n);r||(r=/* @__PURE__ */ new WeakMap,$1.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 kge(e,t){let n=wge(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 G1(t,a.identifier);if(!n.ok){C.warn(`oauth-provider: skipping resource seed for ${a.identifier} — ${n.reason}`);continue}let o=a;if(o.signingAlgorithm!=null&&!hge.has(o.signingAlgorithm)){C.warn(`oauth-provider: dropping unsupported signingAlgorithm "${o.signingAlgorithm}" for resource ${o.identifier} — must be one of ${W1.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:Q1(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:Tge(o,r,l)})}}async function e0(e,t){let n=Oge(e,t);if(n.completed!==!0)return n.promise===null&&(n.promise=kge(e,t).then(()=>{n.completed=!0}).catch(e=>{throw n.promise=null,e})),n.promise}function Age(e){let t=J1(e);C.info(`oauth-provider: enforcePerClientResources resolved to ${t.value} (${t.source})`)}function t0(e){return e.headers?.get(`dpop`)??void 0}function n0(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 jge=/* @__PURE__ */ new Set([`openid`,`profile`,`email`,`offline_access`]);function r0(e){return jge.has(e)}function i0(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}function a0(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)||r0(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 Mge(e,t,n=[]){let r=new Set(n),i={sub:e.id??void 0};for(let[n,a]of Object.entries(I1))(t.includes(a.scope)||r.has(n))&&(i[n]=a.resolve(e));return i}function o0(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 Nge(e){let t=e.headers?.get(`authorization`),n=eZ(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 Pge(e,t){let{authorization:n}=Nge(e);if(!n?.token)throw new E(`UNAUTHORIZED`,{error_description:`access token not found`,error:`invalid_request`});let{payload:r,requestedUserInfoClaims:i}=await O0(e,t,n.token);if(oZ(r)&&!e.request)throw new E(`UNAUTHORIZED`,{error_description:`DPoP-bound access token requires an HTTP request context`,error:`invalid_token`});try{await gZ({payload:r,authorization:n,proofJwt:t0(e),method:e.request?.method??`GET`,url:n0(e,`/oauth2/userinfo`),proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ZX(e.context.internalAdapter)})}catch(e){throw hZ(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=Mge(o,a??[],i),c=r.client_id??r.azp,l=c&&(t.pairwiseSecret||Phe(t))?await e1(e,t,c):void 0;t.pairwiseSecret&&l&&(s.sub=await v1(o.id,l,t));let u=a?.length?await Nhe(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,...o0(u,s),...o0(d),sub:s.sub}}const Fge=Object.fromEntries(L1.map(e=>[e,void 0]));function s0(e){return aZ(e)?`DPoP`:`Bearer`}async function Ige(e,t){let n=e.body.grant_type;if(!B$(t).includes(n))throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`});switch(n){case`authorization_code`:return r_e(e,t);case`client_credentials`:return i_e(e,t);case`refresh_token`:return a_e(e,t);default:{let r=khe(t,n);if(r)return r({ctx:e,opts:t,grantType:n,provider:Lge(e,t,n)});throw new E(`BAD_REQUEST`,{error_description:`unsupported grant_type ${n}`,error:`unsupported_grant_type`})}}}function Lge(e,t,n){return{getClient:n=>e1(e,t,n),authenticateClient:async r=>{let{clientId:i,clientSecret:a,preVerified:o,authMethod:s,confirmation:c}=h1(await g1(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 p1(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 b0(e,t,{...r,grantType:n})},hashToken:(e,n)=>a1(t.storeTokens,e,n),validateAccessToken:async(n,r)=>{let{validateAccessToken:i}=await Promise.resolve().then(()=>x0);return i(e,t,n,r)},requireActiveAccessToken:async(n,r)=>{let{requireActiveAccessToken:i}=await Promise.resolve().then(()=>x0);return i(e,t,n,r)}}}async function Rge(e,t,n,r,i,a,o){let s=o?.iat??Math.floor(Date.now()/1e3),c=o?.exp??s+(t.accessTokenExpiresIn??3600),l=K$(e.context).options,u=n?.id??r.clientId;return w$(e,{options:l,header:{typ:`at+jwt`},signingKeyId:o?.signingKeyId??void 0,signingAlgorithm:o?.signingAlgorithm??void 0,payload:{...o?.accessTokenClaims??{},sub:u,aud:X$(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:KH(32),...o?.confirmation?{cnf:o.confirmation}:{}}})}async function zge(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 gP(r.slice(0,r.length/2))}async function Bge(e,t,n,r,i,a,o,s,c,l){let u=Math.floor(Date.now()/1e3),d=u+(t.idTokenExpiresIn??36e3),f=await v1(n.id,r,t),p=s==null?void 0:Math.floor(s.getTime()/1e3),m=k1(t.customIdTokenClaims?await t.customIdTokenClaims({user:n,scopes:i,metadata:m1(r.metadata)}):void 0),h=t.disableJwtPlugin?void 0:K$(e.context).options,g=!t.disableJwtPlugin&&!h?.jwt?.sign?await C$(e,h):void 0,_=t.disableJwtPlugin?`HS256`:g?.alg??h?.jwks?.keyPairConfig?.alg,v=c?await zge(c,_):void 0,y=!!(r.enableEndSession||r.backchannelLogoutUri),b={...Fge,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=k1(l);if(Object.assign(b,o0(x,b)),t.disableJwtPlugin&&!r.clientSecret)return;let S=t.disableJwtPlugin?await new rI(b).setProtectedHeader({alg:`HS256`}).sign(new TextEncoder().encode(await r1(e,t.storeClientSecret,r.clientSecret))):await w$(e,{options:h,payload:b,resolvedKey:g??void 0});if(S&&v&&h?.jwt?.sign){let e=hI(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 c0(e,t,n){return(e.prefix?.refreshToken??``)+(e.formatRefreshToken?.encrypt?e.formatRefreshToken.encrypt(t,n):t)}async function l0(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 Vge(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():KH(32,`A-Z`,`a-z`);return await e.context.adapter.create({model:`oauthAccessToken`,data:{token:await a1(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 u0(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 Hge(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 d0(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():KH(32,`A-Z`,`a-z`),g=s?.sid,_={token:await a1(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 c0(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 c0(t,h,g)}}async function f0(e,t,n){let r=await q1(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 p0(e){throw new E(`BAD_REQUEST`,{error:`invalid_dpop_proof`,error_description:e})}function Uge(e){let t=m1(e.metadata)??{};return e.dpopBoundAccessTokens===!0||t.dpop_bound_access_tokens===!0}async function m0(e,t,n){let r=n.verificationValue?.query.dpop_jkt,i=aZ(n.refreshToken?.confirmation),a=i??r,o=t0(e),s=Uge(n.client)||n.grantIssuance.dpopBoundAccessTokensRequired||!!r||!!i;if(!o)s&&p0(`DPoP proof header is required`);else try{return{jkt:(await pZ({proofJwt:o,method:`POST`,url:n0(e,e.path??`/oauth2/token`),expectedJkt:a,proofMaxAgeSeconds:t.dpop?.proofMaxAgeSeconds,signingAlgorithms:t.dpop?.signingAlgorithms,replayStore:ZX(e.context.internalAdapter)})).jkt}}catch(e){throw $X(e)&&p0(e.message),e}}function h0(e){return e?[...new Set(e)].sort():void 0}function g0(e,t){let n=h0(e),r=h0(t);return n===void 0||r===void 0?n===r:n.length===r.length&&n.every((e,t)=>e===r[t])}function _0(e){if(e)return`jkt`in e?`jkt:${e.jkt}`:`x5t#S256:${e[`x5t#S256`]}`}function Wge(e,t){return _0(e)===_0(t)}function Gge(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 Kge(e){return e===`Bearer`||e===`DPoP`}function qge(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`&&Kge(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 Jge(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||Gge(n.confirmation))&&qge(t.response)}function v0(e){let t=h0(e.requestedResources);return{effectiveScopes:h0(e.effectiveScopes)??[],...t?{requestedResources:t}:{},...e.confirmation?{confirmation:e.confirmation}:{}}}function Yge(e,t){return g0(e.effectiveScopes,t.effectiveScopes)&&g0(e.requestedResources,t.requestedResources)&&Wge(e.confirmation,t.confirmation)}async function Xge(e,t){return IW({key:e.context.secretConfig,data:JSON.stringify(t)})}async function Zge(e,t){let n=await LW({key:e.context.secretConfig,data:t}),r=JSON.parse(n);if(Jge(r))return r}function y0(e){return!!e.rotatedAt&&!!e.rotationReplayExpiresAt&&e.rotationReplayExpiresAt>=/* @__PURE__ */ new Date}async function Qge(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 Xge(e,{request:r,response:i})}})}async function $ge(e,t,n){if(y0(t)&&t.rotationReplayResponse)try{let r=await Zge(e,t.rotationReplayResponse);return!r||!Yge(r.request,n)?void 0:r.response}catch(t){e.context.logger.error(`refresh token rotation replay failed`,t);return}}async function e_e(e,t,n){let r=Math.floor(Date.now()/1e3),i=await f0(e,t,{clientId:n.client.clientId,requestedScopes:n.scopes,resources:n.resources,refreshToken:n.refreshToken,iat:r,scopeExpiresAtSeconds:r+(t.accessTokenExpiresIn??3600)}),a=await m0(e,t,{client:n.client,grantIssuance:i,refreshToken:n.refreshToken});return v0({effectiveScopes:i.effectiveScopes,requestedResources:n.resources,confirmation:a})}function t_e(e,t){let n=Math.floor(Date.now()/1e3);return e.json({...t,expires_in:Math.max(0,t.expires_at-n)})}async function b0(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]?x$(t.scopeExpirations[e],p):m).reduce((e,t)=>e<t?e:t,m):m,g=await f0(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&&u1(r,`refresh_token`)&&(u?.scopes?.includes(`offline_access`)||i.includes(`offline_access`)),S=_&&!t.disableJwtPlugin,ee=a&&v.includes(`openid`),C=m1(r.metadata),te=ee&&a?{...await Mhe(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,w=t.customTokenResponseFields?await t.customTokenResponseFields({grantType:o,user:a,scopes:v,metadata:C,verificationValue:f}):void 0,ne=g.refreshResources,T=n.confirmation??await m0(e,t,{client:r,grantIssuance:g,verificationValue:f,refreshToken:u}),re=n.requestedUserInfoClaims??u?.requestedUserInfoClaims??[],ie=x&&a&&!S?await d0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,ne,T,re):void 0,ae=S?await z1({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?Rge(e,t,a,r,_,v,{iat:p,exp:y,sid:c,signingAlgorithm:g.signingAlgorithm,signingKeyId:g.signingKeyId,accessTokenClaims:ae,confirmation:T}):Vge(e,t,a,r,v,{iat:p,exp:y,sid:c},n?.resources,s,n.authorizationCodeId,ie?.id,T,re),ie||(x&&a?d0(e,t,a,s,n.authorizationCodeId,r,v,{iat:p,exp:b,sid:c},u,d,ne,T,re):void 0)]),ce=ee?await Bge(e,t,a,r,v,l,c,d,oe,te):void 0,le={...w,...n.tokenResponse??{},access_token:oe,expires_in:y-p,expires_at:y,token_type:s0(T),refresh_token:se?.token,scope:v.join(` `),id_token:ce};if(u?.id&&se?.id)try{await Qge(e,t,u,v0({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 n_e(e,t,n,r,i,a){let o=await a1(t.storeTokens,n,`authorization_code`),s=await e.context.internalAdapter.consumeVerificationValue(o);if(!s)throw await Hge(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=pge.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=Y$(u.resource)??Y$(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 r_e(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/token`)),{code:o,code_verifier:s,redirect_uri:c,resource:l}=e.body,u=Y$(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 p1(e,t,n,r,void 0,i,`authorization_code`,a),{verificationValue:m,effectiveResources:h,authorizedResources:g,authorizationCodeId:_}=await n_e(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(d1(p,v),T1(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 UY(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?Rhe(S):J$(m.authTime),C=P1(m.query.claims,R1(t));return b0(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 i_e(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/token`)),{scope:o,resource:s}=e.body,c=Y$(s);if(!n)throw new E(`BAD_REQUEST`,{error_description:`Missing required client_id`,error:`invalid_request`});let l=await p1(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)||r0(t));if(t.length)throw new E(`BAD_REQUEST`,{error_description:`The following scopes are invalid: ${t.join(`, `)}`,error:`invalid_scope`})}return d||=[...u],b0(e,t,{client:l,scopes:d,grantType:`client_credentials`,resources:c})}async function a_e(e,t){let{clientId:n,clientSecret:r,preVerified:i,authMethod:a}=h1(await g1(e,t,`${e.context.baseURL}/oauth2/token`)),{refresh_token:o,scope:s,resource:c}=e.body,l=Y$(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 p1(e,t,n,r,void 0,i,`refresh_token`,a),d=await l0(t,o),f=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await o1(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(d1(u,m??p),f.revoked){if(y0(f)){let n=await $ge(e,f,await e_e(e,t,{client:u,refreshToken:f,scopes:m??p,resources:l??f.resources}));if(n)return t_e(e,n);throw new E(`BAD_REQUEST`,{error_description:`invalid refresh token`,error:`invalid_grant`})}throw await u0(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:J$(f.authTime);return b0(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 x0=/* @__PURE__ */ O$({introspectEndpoint:()=>A0,requireActiveAccessToken:()=>f_e,requireActiveAccessTokenWithClaims:()=>O0,validateAccessToken:()=>D0});const S0=`Invalid access token`,o_e=`Bearer error="invalid_token", error_description="${S0}"`;function C0(){return{payload:{active:!1},requestedUserInfoClaims:[]}}function s_e(e,t){return e==null?[]:(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`&&e!==t)}async function w0(e,t,n){let{introspectingClientId:r,issuerClientId:i,audienceResources:a}=n;return!r||r===i||a.length!==0&&xge(e,t,r,a)}async function c_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=K$(e.context),a=i.options,o=`${e.context.baseURL??``}/oauth2/userinfo`,s=a?.jwt?.issuer??e.context.baseURL,c;try{c=(await tI(n,uI(await AZ(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 nP||e instanceof cP)return{active:!1};throw e instanceof TypeError||q$(e)?new O(`BAD_REQUEST`,{error_description:`invalid JWT signature`,error:`invalid_request`}):e}let l=c.aud;if(!await K1(e,t,l,[o])||!c.azp)return{active:!1};let u=await e1(e,t,c.azp);if(!u||u?.disabled||!await w0(e,t,{introspectingClientId:r,issuerClientId:c.azp,audienceResources:s_e(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=s0(c.cnf),c}async function l_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 o1(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 C0();let o=Array.isArray(a.resources)?a.resources:void 0,s;if(a.clientId&&(s=await e1(e,t,a.clientId),!s||s?.disabled||!await w0(e,t,{introspectingClientId:r,issuerClientId:a.clientId,audienceResources:o??[]})))return C0();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 C0()}let l;a.userId&&(l=await e.context.internalAdapter.findUserById(a?.userId));let u=`${e.context.baseURL}/oauth2/userinfo`;if(o?.length&&!await K1(e,t,o,[u]))return C0();let d=o?[...o]:void 0;d?.length&&a.scopes?.includes(`openid`)&&(d.includes(u)||d.push(u));let f=o?.length?await Sge(e,t,o):{},p=s?await z1({ctx:e,opts:t,user:l,client:s,scopes:a.scopes??[],grantType:void 0,sessionId:void 0,resources:o,referenceId:a.referenceId,metadata:m1(s.metadata),perRequestClaims:void 0,resourcePolicyClaims:f}):{},m=(t.disableJwtPlugin?void 0:K$(e.context))?.options;return{payload:{...p,active:!0,iss:m?.jwt?.issuer??e.context.baseURL,aud:X$(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:s0(a.confirmation),...a.confirmation?{cnf:a.confirmation}:{}},requestedUserInfoClaims:a.requestedUserInfoClaims??[]}}async function u_e(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await o1(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:K$(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:s0(i.confirmation),...i.confirmation?{cnf:i.confirmation}:{}}}function T0(){return new O(`UNAUTHORIZED`,{error_description:S0,error:`invalid_token`},{"WWW-Authenticate":o_e})}function d_e(e){return e.status===`BAD_REQUEST`||e.body?.error===`invalid_token`}async function E0(e,t,n,r){try{return{payload:await c_e(e,t,n,r),requestedUserInfoClaims:[]}}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(e)}try{return await l_e(e,t,n,r)}catch(e){if(!(e instanceof O))throw e instanceof Error?e:Error(`Unknown error validating access token`)}throw T0()}async function D0(e,t,n,r){return(await E0(e,t,n,r)).payload}async function f_e(e,t,n,r){let i=await D0(e,t,n,r);if(i.active)return i;throw T0()}async function O0(e,t,n,r){let{payload:i,requestedUserInfoClaims:a}=await E0(e,t,n,r);if(i.active)return{payload:i,requestedUserInfoClaims:a};throw T0()}async function k0(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 e1(e,t,i);if(!a)return n;let o=await v1(n.sub,a,t);return{...n,sub:o}}async function A0(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}=h1(await g1(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=tZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await p1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return k0(e,t,await D0(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 k0(e,t,await u_e(e,t,(await l0(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(d_e(e))return{active:!1};throw e}throw e instanceof Error?(C.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(C.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}function j0(e){return e?.get(`sec-fetch-mode`)===`cors`}var p_e=/* @__PURE__ */ e({a:()=>z2,c:()=>u2,d:()=>e2,f:()=>Q0,h:()=>$0,i:()=>a4,l:()=>c2,n:()=>$2,o:()=>K_e,r:()=>n4,s:()=>C2,t:()=>d4,u:()=>X0});async function m_e(e,t,n){let r=await t4.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=R1(t),c=P1(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:P1(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:o4(a.get(`redirect_uri`)??``,`access_denied`,`User denied access`,a.get(`state`)??void 0,d4(e,t))};let p=await LJ(e),m=_1(a.get(`prompt`)??``).has(`login`),h=m&&S1(p?.session.createdAt,r?.signedQueryIssuedAt);if(m&&!h)return e?.headers?.set(`accept`,`application/json`),e.query=x1(a),await n(e);let g=await y1(t,{user:p?.user,session:p?.session,scopes:u??o}),_=await b1(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=ige(a.get(`claims`),f);e?a.set(`claims`,JSON.stringify(e)):a.delete(`claims`)}e?.headers?.set(`accept`,`application/json`);let x=C1(a,`consent`);return h&&(x=C1(x,`login`),x=w1(x)),e.query=x1(x),await n(e,{postLogin:r?.postLoginClearedForSession!==void 0&&r.postLoginClearedForSession===p?.session.id})}async function h_e(e,t){if(e.body.selected===!0)return await g_e(e,t);if(e.body.created===!0)return await __e(e,t);if(e.body.postLogin===!0)return await v_e(e,t);throw new E(`BAD_REQUEST`,{error_description:`Missing parameters`,error:`invalid_request`})}async function g_e(e,t){let n=(await t4.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=x1(C1(new URLSearchParams(n),`select_account`)),await t(e)}async function __e(e,t){let n=(await t4.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=x1(C1(r,`create`)),await t(e)}async function v_e(e,t){let n=await t4.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=x1(i);let a=await LJ(e);return await t(e,{postLogin:n?.postLoginClearedForSession!==void 0&&n.postLoginClearedForSession===a?.session.id,isPostLoginContinuation:!0})}async function y_e(e,t,n,r){return w$(e,{options:t,payload:{...r,events:{"http://schemas.openid.net/event/backchannel-logout":{}}},header:{typ:`logout+jwt`},resolvedKey:n??void 0})}async function b_e(e,t,n){let{sessionId:r,userId:i}=n;if(!i)return null;let a=e.context.logger;try{let n=await bH(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 v1(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 x_e(e,t){let n=/* @__PURE__ */ new Date,r=await bH(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 S_e(e,t)}async function S_e(e,t){let n=e.context.logger,r=K$(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 C$(e,r);await Promise.allSettled(t.targets.map(async({client:c,sub:l})=>{try{let u=KH(32,`a-z`,`A-Z`,`0-9`),d=await y_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 M0(e){return e.replace(/[&<>"']/g,e=>{switch(e){case`&`:return`&`;case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;default:return e}})}function N0(e){let t=e.request?.headers??e.headers;if(!t||j0(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 P0(e,t,n=200){return new Response(`<!doctype html><html><head><meta charset="utf-8"><title>${M0(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 F0(e){return`${e.context.baseURL.replace(/\/$/,``)}/oauth2/end-session/confirm`}function C_e(e){try{return new URL(F0(e)).pathname}catch{return`/oauth2/end-session/confirm`}}function I0(e){return P0(`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="${M0(F0(e))}"><button type="submit" name="action" value="confirm">Confirm logout</button></form></main>`)}function L0(e){return P0(`Logged out`,`<main><p data-oidc-logout-state="logged-out">${e?`Logged out. ${M0(e)}`:`Logged out.`}</p></main>`)}function w_e(e,t){return P0(`Logout error`,`<main><h1>Logout error</h1><p data-oidc-logout-state="error">${M0(e)}</p></main>`,t)}function R0(e,t,n,r){if(N0(e))return w_e(r,t===`BAD_REQUEST`?400:t===`UNAUTHORIZED`?401:500);throw new O(t,{error:n,error_description:r})}function z0(e){return`${e.context.authCookies.sessionToken.name}.oauth_logout_confirmation`}function B0(e,t){return{...e.context.authCookies.sessionToken.attributes,httpOnly:!0,maxAge:t,path:C_e(e),sameSite:`lax`}}async function V0(e,t,n={}){let r={...t?{sessionId:t}:{},...n,expiresAt:Date.now()+3e5};await e.setSignedCookie(z0(e),JSON.stringify(r),e.context.secret,B0(e,300))}async function T_e(e){let t=await e.getSignedCookie(z0(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 H0(e){e.setCookie(z0(e),``,B0(e,0))}async function U0(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 E_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 W0(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 G0(e,t,n){try{return await e1(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 K0(e){return(Array.isArray(e)?e:[e]).filter(e=>typeof e==`string`)}function D_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=K0(e.aud);return t.length===1?t[0]:null}async function O_e(e,t,n,r){if(r)return G0(e,t,r);let i;try{i=gI(n)}catch{return null}let a=D_e(i);return a?G0(e,t,a):null}async function k_e(e,t,n,r){try{let i;if(t.disableJwtPlugin){if(!r.clientSecret)return null;let a=await r1(e,t.storeClientSecret,r.clientSecret),{payload:o}=await RF(n,new TextEncoder().encode(a));i=JSON.parse(new TextDecoder().decode(o))}else{let t=K$(e.context).options,{payload:r}=await RF(n,uI(await AZ(n,{jwksFetch:t?.jwks?.remoteUrl??`${e.context.baseURL}${t?.jwks?.jwksPath??`/jwks`}`})));i=JSON.parse(new TextDecoder().decode(r))}return i.iss!==d4(e,t)||!K0(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 q0(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 J0(e,t){return t.post_logout_redirect_uri?q0(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 A_e(e,t,n){if(n.redirectInvalid)return{invalid:!0};if(!n.clientId||!n.postLogoutRedirectUri)return{invalid:!1};let r=await G0(e,t,n.clientId);return!r||r.disabled||!r.enableEndSession?{invalid:!0}:q0(r,n.postLogoutRedirectUri,n.state)}async function Y0(e,t,n={}){return t?N0(e)?(await V0(e,t.session.id,n),I0(e)):R0(e,`BAD_REQUEST`,`invalid_request`,`User confirmation is required to complete logout`):N0(e)?(await V0(e,void 0,n),I0(e)):R0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`)}async function j_e(e,t){let n=await T_e(e),r=await U0(e);if(!n||n.expiresAt<=Date.now())return R0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`);let i=await A_e(e,t,n);return r?n.sessionId&&n.sessionId!==r.session.id?R0(e,`BAD_REQUEST`,`invalid_request`,`The logout confirmation is invalid or expired`):(await W0(e,r.session),sq(e),H0(e),i.uri?c4(e,i.uri):N0(e)?L0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):null):(H0(e),i.uri?c4(e,i.uri):N0(e)?L0(i.invalid?`The requested post-logout redirect was not registered.`:void 0):R0(e,`BAD_REQUEST`,`invalid_request`,`No active session is available for logout`))}async function M_e(e,t){let n=e.query??{},r=e.body??{},i={...n,...r},a=await U0(e);if(i.id_token_hint===void 0){let n={};if(i.client_id){let r=await G0(e,t,i.client_id);if(!r)return R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(r.disabled)return R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!r.enableEndSession)return R0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);n=J0(r,i)}return Y0(e,a,n)}let o=await O_e(e,t,i.id_token_hint,i.client_id);if(!o)return a&&N0(e)?Y0(e,a):R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client does not exist`);if(o.disabled)return R0(e,`BAD_REQUEST`,`invalid_client`,`The logout client is disabled`);if(!o.enableEndSession)return R0(e,`UNAUTHORIZED`,`invalid_client`,`The client is not allowed to initiate logout`);let s=await k_e(e,t,i.id_token_hint,o);if(!s)return a&&N0(e)?Y0(e,a,i.client_id?J0(o,i):{}):R0(e,`UNAUTHORIZED`,`invalid_token`,`The id_token_hint is invalid`);let c=s.sid,l=await E_e(e,c),u=a?.session.id===c;if(a&&!u)return Y0(e,a,J0(o,i));let d=q0(o,i.post_logout_redirect_uri,i.state),f=l??(u?a?.session:null);return f&&await W0(e,f),u&&sq(e),H0(e),d.uri?c4(e,d.uri):N0(e)?L0(d.invalid?`The requested post-logout redirect was not registered.`:void 0):null}async function N_e(e,t){return j_e(e,t)}function X0(e,t,n){let r=e.context.baseURL,i=!n?.jwt_disabled;return{scopes_supported:n?.scopes_supported,issuer:u4(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:[...$Y],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:[...$Y],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:[...$Y],code_challenge_methods_supported:[`S256`],authorization_response_iss_parameter_supported:!0,dpop_signing_alg_values_supported:n?.dpop_signing_alg_values_supported??[...YX],backchannel_logout_supported:i,backchannel_logout_session_supported:i}}function Z0(e,t){let n=t.disableJwtPlugin?void 0:K$(e.context).options,r=z$(t),i=t.allowUnauthenticatedClientRegistration||r.length>0;return{jwtPluginOptions:n,clientDiscoveries:r,authMetadata:X0(e,n,{scopes_supported:t.advertisedMetadata?.scopes_supported??t.scopes,dynamic_client_registration_supported:t.allowDynamicClientRegistration,public_client_supported:i,grant_types_supported:B$(t),token_endpoint_auth_methods_supported:H$(t,{includeNone:i}),endpoint_auth_methods_supported:H$(t),jwt_disabled:t.disableJwtPlugin,dpop_signing_alg_values_supported:t.dpop?.signingAlgorithms})}}function Q0(e,t){let{clientDiscoveries:n,authMetadata:r}=Z0(e,t);return W$(e,t,`oauth-authorization-server`,{...t1(n),...r})}function $0(e,t){let n=e.context.baseURL,{jwtPluginOptions:r,clientDiscoveries:i,authMetadata:a}=Z0(e,t),o={...a,claims_supported:R1(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 W$(e,t,`openid-configuration`,{...t1(i),...o})}function e2(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 t2(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`,{...n2(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({...n2(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 n2(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?ke(r.path):``;return{error:P_e(r,o,n),error_description:I_e(r,s)}}function P_e(e,t,n){return typeof t==`string`?t:F_e(e)?t?.missing??n:e.code===`invalid_value`?t?.invalid??n:n}function F_e(e){return e.code===`invalid_type`&&e.message.endsWith(`received undefined`)}function I_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 L_e=e=>Lq(async t=>{if(!e.allowPublicClientPrelogin)throw new E(`BAD_REQUEST`);let n=t.body.oauth_query;if(!await Q$(n,t.context.secret))throw new E(`UNAUTHORIZED`,{error:`invalid_signature`})}),r2={"P-256":`ES256`,"P-384":`ES384`,"P-521":`ES512`},R_e=[`Ed25519`],z_e=[`d`,`p`,`q`,`dp`,`dq`,`qi`,`oth`];function i2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a2(e,t){return typeof e[t]==`string`&&e[t].length>0}function o2(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call(r2,e)}function s2(e){return R_e.some(t=>t===e)}function B_e(e){switch(e.kty){case`RSA`:return a2(e,`n`)&&a2(e,`e`);case`EC`:return o2(e.crv)&&a2(e,`x`)&&a2(e,`y`);case`OKP`:return s2(e.crv)&&a2(e,`x`);default:return!1}}function V_e(e){if(e.alg===void 0)return!0;if(typeof e.alg!=`string`||!$Y.some(t=>t===e.alg))return!1;switch(e.kty){case`RSA`:return e.alg.startsWith(`RS`)||e.alg.startsWith(`PS`);case`EC`:return o2(e.crv)&&r2[e.crv]===e.alg;case`OKP`:return s2(e.crv)&&e.alg===`EdDSA`;default:return!1}}function c2(e){let t=i2(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(!i2(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(e.kty===`oct`||`k`in e||z_e.some(t=>t in e))return{valid:!1,error:`jwks must contain only public asymmetric keys`};if(!B_e(e))return{valid:!1,error:`jwks keys must be supported public JWKs with required key parameters`};if(!V_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 l2(e){let t=c2(e);if(!t.valid)throw new E(`BAD_REQUEST`,{error:`invalid_client_metadata`,error_description:t.error})}const H_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})),U_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(`.`),W_e=/* @__PURE__ */ new Set([...H_e,...U_e,`public`,`type`,`resources`,`client_credentials_scopes`]),G_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 u2(e){return G_e.has(e)}function d2(e){if(e)return Object.fromEntries(Object.entries(e).filter(([e])=>!W_e.has(e)))}async function f2(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 p2(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 K_e=/* @__PURE__ */ O$({consumeClientAssertion:()=>C2,isPrivateHostname:()=>b2,verifyClientAssertion:()=>w2});const m2=/* @__PURE__ */ new WeakMap,h2=65536,q_e=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i;function g2(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 _2(e){let t=m2.get(e);if(t)return t;let n=/* @__PURE__ */ new Map;return m2.set(e,n),n}function v2(e){return`${e.clientDiscoveryId??`managed`}:${e.jwksUri??``}`}const y2=[...$Y];function b2(e){return!vY(e)}function J_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(b2(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 Y_e(e){try{let t=new URL(e);return t.protocol!==`https:`&&t.protocol!==`http:`?void 0:t.origin}catch{return}}async function X_e(e){let t=e.headers.get(`content-length`);if(t!==null&&Number.isFinite(Number(t))&&Number(t)>h2)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>h2)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 x2(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||!q_e.test(i))throw Error(`JWKS response must use a JSON media type`);let a=await X_e(r),o;try{o=JSON.parse(a)}catch{return{valid:!1}}let s=c2(o);return s.valid?{valid:!0,jwks:s.jwks}:{valid:!1}}finally{clearTimeout(r)}}function S2(){return new O(`BAD_REQUEST`,{error_description:`failed to fetch client JWKS`,error:`invalid_client`})}async function Z_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?z$(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`});J_e(e,n.jwksUri,n.clientDiscoveryId?Y_e(n.clientId):void 0);let i=Date.now(),a=v2(n),o=_2(t),s=o.get(a);if(s&&i-s.fetchedAt<3e5)return s.jwks;let c;try{c=await x2(n.jwksUri,r?.fetchClientMetadataResource)}catch{if(s&&i-s.fetchedAt<6e5)return s.jwks;throw S2()}if(!c.valid)throw S2();return g2(o,a,c.jwks,i),c.jwks}async function Q_e(e,t){if(!t.jwksUri)return null;let n=t.clientDiscoveryId?z$(e).find(e=>e.id===t.clientDiscoveryId):void 0;if(t.clientDiscoveryId&&!n?.fetchClientMetadataResource)return null;try{let r=await x2(t.jwksUri,n?.fetchClientMetadataResource);return r.valid?(g2(_2(e),v2(t),r.jwks,Date.now()),r.jwks):null}catch{return null}}async function C2(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 AU(`SHA-256`).digest(new TextEncoder().encode(`${r}:${i.jti}`)),l=we(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 w2(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=hI(n)}catch{throw new O(`BAD_REQUEST`,{error_description:`malformed client assertion: invalid JWT header`,error:`invalid_client`})}if(!s.alg||!y2.includes(s.alg))throw new O(`BAD_REQUEST`,{error_description:`unsupported assertion signing algorithm: ${s.alg}`,error:`invalid_client`});let c;try{c=gI(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 e1(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 Z_e(e,t,u),f=a??`${e.context.baseURL}/oauth2/token`,p=d4(e,t),m=o?.endpointAudienceOnly?[f]:[.../* @__PURE__ */ new Set([f,p])],h={issuer:l,subject:l,audience:m,algorithms:y2},g;try{({payload:g}=await tI(n,uI(d),h))}catch(e){if(e instanceof Error&&/no matching key|no applicable key/i.test(e.message)){let e=await Q_e(t,u);if(e)try{({payload:g}=await tI(n,uI(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 C2(e,t,{namespace:`private_key_jwt:${l}`,payload:g,expectedAudience:_}),{clientId:l,client:u}}function T2(e,t,n){return new O(e,{error:t,error_description:n},{"WWW-Authenticate":`Bearer error="${t}"`,...Pq})}async function $_e(e,t,n){let r=e.headers,i;try{i=Fhe(r?.get(`authorization`))}catch{throw T2(`BAD_REQUEST`,`invalid_request`,`Malformed initial access token Authorization header`)}if(!i||!r)return;if(!t.validateInitialAccessToken)throw T2(`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 T2(`UNAUTHORIZED`,`invalid_token`,`Invalid initial access token`);return a}const eve=[`authorization_code`];function E2(e){return[.../* @__PURE__ */ new Set([...e.clientRegistrationDefaultScopes??e.scopes??[],...e.clientRegistrationAllowedScopes??[]])]}function D2(e){let t=e.grant_types??[...eve];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 tve(e,t){return e.response_types?e.response_types:t.includes(`authorization_code`)?[`code`]:void 0}function O2(e,t){let n=new Set(B$(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 k2(e,t=`web`){let n=D2(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:tve(e,n)}}function nve(e){let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`&&t.host!==``}function rve(e){try{let t=new URL(e).protocol;return t!==`http:`&&t!==`https:`}catch{return!1}}function A2(e,t){let n=e.clientRegistrationDefaultApplicationType??`web`;return n===`infer`?(t.redirect_uris??[]).some(e=>rve(e)||M2(e))?`native`:`web`:n}function j2(e){throw new E(`BAD_REQUEST`,{error:`invalid_redirect_uri`,error_description:e})}function ive(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 M2(e){let t=ive(e);return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}function ave(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 ove(e,t,n){let r=t.clientRegistrationDefaultResources??[],i=[.../* @__PURE__ */ new Set([...r,...n])];for(let n of i){let r=await Z1(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 sve(e,t){let n;try{n=new URL(e)}catch{j2(`redirect URI must be an absolute URI: ${e}`)}(e.includes(`#`)||n.username.length>0||n.password.length>0)&&j2(`redirect URI must not include credentials or a fragment: ${e}`);let r=n.protocol===`http:`,i=n.protocol===`https:`;/^localhost\.+$/i.test(n.hostname)&&j2(`redirect URI localhost must not include trailing dots: ${e}`);let a=gY(n.hostname)||n.hostname===`localhost`;t===`web`?(!i||a)&&j2(`web clients require https redirect URIs on non-loopback hosts: ${e}`):i?a&&j2(`native clients must not use https loopback redirect URIs: ${e}`):r?M2(e)||j2(`native clients may use http only on the exact loopback hosts localhost, 127.0.0.1, or [::1]: ${e}`):D1(n)||j2(`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 cve(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 LJ(e),i=r?void 0:await $_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`,...Pq});let o=n.grant_types?.length?O2(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 f2(e,r,t,`create`);let u=i?.referenceId??(r&&t.clientReference?await t.clientReference({user:r.user,session:r.session}):void 0),d=await R2(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 N2(e,t,n){let r=n?.registrationSource===`clientMetadataDocument`,i=k2(e,r?null:n?.registrationSource===`dynamic`?A2(t,e):`web`),a=i.token_endpoint_auth_method??`client_secret_basic`;if(!new Set(H$(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??[])sve(e,c??(r?`native`:`web`));if(r)O2(t,o);else{let e=new Set(B$(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(nve))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?E2(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(b2(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&&l2(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(b2(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 P2=Symbol(`client-registration-collision`);function F2(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[P2]===!0&&(t.kind===`oauth-client-row-unique`||t.kind===`oauth-client-resource-link-unique`)&&`cause`in t}async function I2(e,t,n){let r=n.registrationSource===`dynamic`&&!n.metadata.scope?{...n.metadata,scope:(t.clientRegistrationDefaultScopes??t.scopes)?.join(` `)}:n.metadata,i=k2(r,n.registrationSource===`clientMetadataDocument`?null:n.registrationSource===`dynamic`?A2(t,r):`web`),a=i.token_endpoint_auth_method===`none`,o=i.token_endpoint_auth_method===`private_key_jwt`,s=U$(t,i.token_endpoint_auth_method);await N2(i,t,{registrationSource:n.registrationSource,ctx:e});let c=n.clientId??t.generateClientId?.()??KH(32,`a-z`,`A-Z`),l=a||o||s?void 0:t.generateClientSecret?.()||KH(32,`a-z`,`A-Z`),u=l?await i1(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:E2(t).join(` `)}:i,g=n.registrationSource===`clientMetadataDocument`?void 0:{userId:n.userId,referenceId:n.referenceId},_=H2({...h,redirect_uris:i.redirect_uris??[],disabled:void 0,client_secret_expires_at:u?n.registrationSource===`dynamic`&&t.clientRegistrationClientSecretExpiration?x$(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===`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`&&ave(t,v);let y=await ove(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 SH(e.context.adapter,async()=>{let t=await bH(e.context.adapter),r,i=!1;if(S){let{clientCredentialsScopes:e,disabled:n,skipConsent:i,enableEndSession:a,...o}=_,s=await t.update({model:b,where:[{field:`clientId`,value:c},{field:`clientDiscoveryId`,value:ee}],update:{...o,createdAt:S.createdAt,updatedAt:/* @__PURE__ */ new Date(p*1e3)}});if(!s)throw new E(`BAD_REQUEST`,{error:`invalid_client`,error_description:`client no longer exists`});r=s}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`&&B2(e)?{[P2]:!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`&&B2(t)?{[P2]:!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 L2(e,t){let n=U2({...e.client,clientSecret:e.clientSecret?(t.prefix?.clientSecret??``)+e.clientSecret:void 0});return e.resources.length>0&&(n.resources=e.resources),n}function lve(e,t){return{...L2(e,t),client_credentials_scopes:[...e.client.clientCredentialsScopes??[]]}}async function R2(e,t,n){return L2(await I2(e,t,n),t)}async function uve(e,t,n){return lve(await I2(e,t,n),t)}function dve(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 z2(e,t,n){if(dve(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 I2(e,t,r)}catch(i){if(!F2(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 I2(e,t,{...r,existingClient:s})}catch(e){throw F2(e)?e.cause:e}}}function B2(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 V2(e,t,n){let r=await LJ(e);if(await f2(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?i0(a??[]):[];a0(s,D2(o),o.token_endpoint_auth_method,t),s.length>0&&await f2(e,r,t,`configure-client-credentials-scopes`);let c=n?.admin?o.resources:void 0;for(let n of new Set(c??[]))await p2(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 uve(e,t,l):await R2(e,t,l);return e.setStatus(201),e.json(u)}function H2(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:w,skip_consent:ne,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=d2(se??{}),fe=de&&Object.keys(de).length?JSON.stringify(de):void 0;return{clientId:t,clientSecret:n,disabled:w,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:ne,enableEndSession:T,requirePKCE:re,dpopBoundAccessTokens:ie,subjectType:ae,referenceId:oe,metadata:fe}}function U2(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:w,jwksUri:ne,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{...d2(m1(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:w?JSON.parse(w):void 0,jwks_uri:ne??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 fve(e,t){let n=await LJ(e);if(await f2(e,n,t,`read`,e.query.client_id),!n)throw new E(`UNAUTHORIZED`);let r=await e1(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=U2(r);return i.client_secret=void 0,i}async function W2(e,t,n){let r=await e1(e,t,n);if(!r||r.disabled)throw new E(`NOT_FOUND`,{error_description:`client not found`,error:`not_found`});return U2({clientId:r.clientId,name:r.name,uri:r.uri,contacts:r.contacts,icon:r.icon,tos:r.tos,policy:r.policy})}async function pve(e,t){let n=await LJ(e);if(await f2(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=U2(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=U2(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 mve(e,t){let n=await LJ(e);if(await f2(e,n,t,`delete`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;$$(t,r);let i=await e1(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 G2(e,t,n){let r=await LJ(e);if(await f2(e,r,t,`update`,e.body.client_id),!r)throw new E(`UNAUTHORIZED`);let i=e.body.client_id;$$(t,i);let a=await e1(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 f2(e,r,t,`configure-client-credentials-scopes`,i),Object.keys(s).length===0&&o===void 0){let e=U2(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:i0(o);f!==void 0&&(a0(f,u,d,t),f.length>0&&!l&&await f2(e,r,t,`configure-client-credentials-scopes`,i)),await N2({...U2(a),...s},t,{ctx:e});let p={...H2(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 i1(e,t,t.generateClientSecret?.()||KH(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=U2(m);return h.client_secret=void 0,n?.admin?{...h,client_credentials_scopes:[...m.clientCredentialsScopes??[]]}:h}async function hve(e,t){let n=await LJ(e);if(await f2(e,n,t,`rotate`,e.body.client_id),!n)throw new E(`UNAUTHORIZED`);let r=e.body.client_id;$$(t,r);let i=await e1(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?.()||KH(32,`a-z`,`A-Z`),o=a?await i1(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 U2({...s,clientSecret:(t.prefix?.clientSecret??``)+a})}async function gve(e,t){if(!t.allowClientKeyRotation)throw new E(`FORBIDDEN`,{error:`access_denied`,error_description:`Client key rotation is disabled`});let{body:n}=e;l2(n.jwks);let{client:r}=await w2(e,t,n.client_assertion,n.client_assertion_type,void 0,n0({context:e.context,request:void 0},`/oauth2/client/rotate-keys`),{endpointAudienceOnly:!0,assertClient:e=>_ve(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 _ve(e,t){if($$(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 K2=k().trim().min(1),q2=Be(k().trim().min(1)).min(1),vve=e=>X(`/admin/oauth2/create-client`,{method:`POST`,body:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(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:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),token_endpoint_auth_method:K2.optional(),application_type:Ze([`web`,`native`]).optional(),jwks:V1.optional(),jwks_uri:k().optional(),grant_types:q2.optional(),client_credentials_scopes:Be(k().trim().min(1)).optional(),resources:Be(B1).optional(),response_types:Be(Ze([`code`])).optional(),client_secret_expires_at:Ae([k(),Le()]).optional().default(0),skip_consent:Je().optional(),enable_end_session:Je().optional(),require_pkce:Je().optional(),dpop_bound_access_tokens:Je().optional(),subject_type:Ze([`public`,`pairwise`]).optional(),metadata:ze(k(),rt()).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=>V2(t,e,{admin:!0})),yve=e=>X(`/oauth2/create-client`,{method:`POST`,use:[zJ],body:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(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:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),token_endpoint_auth_method:K2.optional(),application_type:Ze([`web`,`native`]).optional(),jwks:V1.optional(),jwks_uri:k().optional(),grant_types:q2.optional(),response_types:Be(Ze([`code`])).optional(),dpop_bound_access_tokens:Je().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=>V2(t,e)),bve=e=>X(`/oauth2/get-client`,{method:`GET`,use:[zJ],query:A({client_id:k()}),metadata:{openapi:{description:`Get OAuth2 formatted client details`}}},async t=>fve(t,e)),xve=e=>X(`/oauth2/public-client`,{method:`GET`,use:[zJ],query:A({client_id:k()}),metadata:{openapi:{description:`Gets publicly available client fields`}}},async t=>{let n=t.query.client_id;return W2(t,e,n)}),Sve=e=>X(`/oauth2/public-client-prelogin`,{method:`POST`,use:[L_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 W2(t,e,n)}),Cve=e=>X(`/oauth2/get-clients`,{method:`GET`,use:[zJ],metadata:{openapi:{description:`Get OAuth2 formatted client details for a user or organization`}}},async t=>pve(t,e)),wve=e=>X(`/admin/oauth2/update-client`,{method:`PATCH`,body:A({client_id:k(),update:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(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:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),application_type:Ze([`web`,`native`]).optional(),grant_types:q2.optional(),client_credentials_scopes:Be(k().trim().min(1)).optional(),response_types:Be(Ze([`code`])).optional(),client_secret_expires_at:Ae([k(),Le()]).optional(),skip_consent:Je().optional(),enable_end_session:Je().optional(),disabled:Je().optional(),dpop_bound_access_tokens:Je().optional(),metadata:ze(k(),rt()).optional()})}),metadata:{SERVER_ONLY:!0,openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>G2(t,e,{admin:!0})),Tve=e=>X(`/oauth2/update-client`,{method:`POST`,use:[zJ],body:A({client_id:k(),update:A({redirect_uris:Be(O1).min(1).optional(),scope:k().optional(),client_name:k().optional(),client_uri:k().optional(),logo_uri:k().optional(),contacts:Be(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:Be(O1).min(1).optional(),backchannel_logout_uri:O1.optional(),backchannel_logout_session_required:Je().optional(),application_type:Ze([`web`,`native`]).optional(),grant_types:q2.optional(),response_types:Be(Ze([`code`])).optional()})}),metadata:{openapi:{description:`Updates OAuth2 formatted client details.`}}},async t=>G2(t,e)),Eve=e=>X(`/oauth2/client/rotate-secret`,{method:`POST`,use:[zJ],body:A({client_id:k()}),metadata:{noStore:!0,openapi:{description:`Rotates a confidential client's secret`}}},async t=>hve(t,e)),Dve=e=>t2(`/oauth2/client/rotate-keys`,{method:`POST`,body:A({client_assertion:k(),client_assertion_type:k(),jwks:V1}),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=>gve(t,e)),Ove=e=>X(`/oauth2/delete-client`,{method:`POST`,use:[zJ],body:A({client_id:k()}),metadata:{openapi:{description:`Deletes an oauth client`}}},async t=>mve(t,e));async function J2(e,t,n){return await e.context.adapter.findOne({model:`oauthConsent`,where:[{field:`id`,value:n}]})}async function kve(e,t){let n=await LJ(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 J2(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 Ave(e,t){let n=await LJ(e);if(!n)throw new E(`UNAUTHORIZED`);return await e.context.adapter.findMany({model:`oauthConsent`,where:[{field:`userId`,value:n.user.id}]})}async function jve(e,t){let n=await LJ(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 J2(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 Mve(e,t){let n=await LJ(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 J2(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 e1(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 Nve=e=>X(`/oauth2/get-consent`,{method:`GET`,query:A({id:k()}),use:[zJ],metadata:{openapi:{description:`Gets details of a specific OAuth2 consent for a user`}}},async t=>kve(t,e)),Pve=e=>X(`/oauth2/get-consents`,{method:`GET`,use:[zJ],metadata:{openapi:{description:`Gets all available OAuth2 consents for a user`}}},async t=>Ave(t,e)),Fve=e=>X(`/oauth2/update-consent`,{method:`POST`,use:[zJ],body:A({id:k(),update:A({scopes:Be(k())})}),metadata:{openapi:{description:`Updates consent granted to a client.`}}},async t=>Mve(t,e)),Ive=e=>X(`/oauth2/delete-consent`,{method:`POST`,use:[zJ],body:A({id:k()}),metadata:{openapi:{description:`Deletes consent granted to a client`}}},async t=>jve(t,e)),Y2=e=>e.schema?.oauthResource?.modelName??`oauthResource`,X2=e=>e.schema?.oauthClientResource?.modelName??`oauthClientResource`,Lve=e=>e.schema?.oauthClient?.modelName??`oauthClient`;function Z2(e){try{return decodeURIComponent(e)}catch{return e}}function Rve(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 zve(e,t){await p2(e,await LJ(e),t,`create`);let n=e.body;if(!n?.identifier)throw new E(`BAD_REQUEST`,{error:`invalid_request`,error_description:`identifier is required`});await gge(t,n.identifier);let r=/* @__PURE__ */ new Date,i;try{i=await e.context.adapter.create({model:Y2(t),data:Rve(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 X1(i.identifier),e.json(i,{status:201})}async function Bve(e,t){await p2(e,await LJ(e),t,`list`);let n=await e.context.adapter.findMany({model:Y2(t)});return e.json(n??[])}async function Vve(e,t){let n=Z2(e.params.identifier);await p2(e,await LJ(e),t,`read`,n);let r=await e.context.adapter.findOne({model:Y2(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 Hve(e,t){let n=Z2(e.params.identifier);if(await p2(e,await LJ(e),t,`update`,n),!await e.context.adapter.findOne({model:Y2(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:Y2(t),where:[{field:`identifier`,value:n}],update:r}),X1(n);let i=await e.context.adapter.findOne({model:Y2(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 Uve(e,t){let n=Z2(e.params.identifier);if(await p2(e,await LJ(e),t,`delete`,n),!await e.context.adapter.findOne({model:Y2(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:Y2(t),where:[{field:`identifier`,value:n}]}),X1(n),e.json({deleted:!0})}async function Wve(e,t){let n=await LJ(e),r=Z2(e.params.identifier),i=Z2(e.params.client_id);if(await p2(e,n,t,`link`,r),!await e.context.adapter.findOne({model:Y2(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:Lve(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:X2(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 Gve(e,t){let n=await LJ(e),r=Z2(e.params.identifier),i=Z2(e.params.client_id);return await p2(e,n,t,`unlink`,r),await e.context.adapter.deleteMany({model:X2(t),where:[{field:`clientId`,value:i},{field:`resourceId`,value:r}]}),e.json({unlinked:!0})}const Q2=A({identifier:k().min(1).optional(),name:k().optional(),accessTokenTtl:Le().int().positive().nullable().optional(),refreshTokenTtl:Le().int().positive().nullable().optional(),signingAlgorithm:Ze(W1).nullable().optional(),signingKeyId:k().nullable().optional(),allowedScopes:Be(k()).nullable().optional(),customClaims:ze(k(),rt()).nullable().optional(),dpopBoundAccessTokensRequired:Je().optional(),disabled:Je().optional(),metadata:ze(k(),rt()).nullable().optional()}),Kve=e=>X(`/admin/oauth2/resources`,{method:`POST`,body:Q2.required({identifier:!0}),metadata:{SERVER_ONLY:!0}},async t=>zve(t,e)),qve=e=>X(`/admin/oauth2/resources`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Bve(t,e)),Jve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`GET`,metadata:{SERVER_ONLY:!0}},async t=>Vve(t,e)),Yve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`PATCH`,body:Q2,metadata:{SERVER_ONLY:!0}},async t=>Hve(t,e)),Xve=e=>X(`/admin/oauth2/resources/:identifier`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Uve(t,e)),Zve=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`POST`,metadata:{SERVER_ONLY:!0}},async t=>Wve(t,e)),Qve=e=>X(`/admin/oauth2/resources/:identifier/clients/:client_id`,{method:`DELETE`,metadata:{SERVER_ONLY:!0}},async t=>Gve(t,e));async function $ve(e,t,n){if(t.disableJwtPlugin)throw new O(`BAD_REQUEST`,{error_description:`JWT access tokens are disabled`,error:`invalid_request`});let r=K$(e.context),i=r.options,a;try{a=(await tI(n,uI(await AZ(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 nP||e instanceof cP)return null;throw e instanceof TypeError||q$(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 K1(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 eye(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 o1(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 tye(e,t,n,r){let i=await e.context.adapter.findOne({model:`oauthRefreshToken`,where:[{field:`token`,value:await o1(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 u0(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 u0(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 nye(e,t,n,r){try{return await $ve(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 eye(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 rye(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}=h1(await g1(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=tZ(n)),!n?.length)throw new O(`BAD_REQUEST`,{error_description:`missing a required token for introspection`,error:`invalid_request`});let c=await p1(e,t,i,a,void 0,o,void 0,s);try{if(r===void 0||r===`access_token`)try{return await nye(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 tye(e,t,(await l0(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?(C.error(`Introspection error:`,e.message,e.stack),new O(`INTERNAL_SERVER_ERROR`)):(C.error(`Introspection error:`,e),new O(`INTERNAL_SERVER_ERROR`))}}const iye={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}}}},$2=[`openid`,`profile`,`email`,`offline_access`],e4=A({id_token_hint:k().optional(),client_id:k().optional(),post_logout_redirect_uri:O1.optional(),state:k().optional()}),t4=_H(()=>null),n4=t4.get,r4=/* @__PURE__ */ new WeakMap,i4=`signedQueryIssuedAtMs`;function aye(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 a4=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??$2).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`,...L1.filter(e=>n.has(I1[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(L$(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:K$(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=e2(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($0(s,a))}:{response:f(Q0(s,a))};if(d)return{response:f($0(s,a))}},s=t2(`/oauth2/authorize`,{method:[`GET`,`POST`],body:A({}).passthrough(),redirectOnError:g4(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=>pye(e,a,e.authorizeSettings??{isAuthorize:!0})),c=(e,t)=>bQ(s,{...e,asResponse:!1,returnHeaders:!1,returnStatus:!1,authorizeSettings:t??{}});return{id:`oauth-provider`,version:`1.7.12`,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 e0(e,a).catch(t=>Dge(e,t)),Age(a),!a.disableJwtPlugin){let t=K$(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 b_e(t,a,{sessionId:e.id,userId:e.userId});if(!n)return;let r=r4.get(t)??/* @__PURE__ */ new Map;r.set(e.id,n),r4.set(t,r)},async after(e,t){if(!t)return;let n=r4.get(t);if(!n)return;let r=n.get(e.id);if(n.delete(e.id),n.size===0&&r4.delete(t),!r)return;let i=x_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:Lq(async e=>{let t=e.body.oauth_query;if(!await Q$(t,e.context.secret))throw new E(`BAD_REQUEST`,{error:`invalid_signature`});let n=yhe(t),r=new URLSearchParams(t),i=r.get(`ba_pl`)??void 0;r.delete(`sig`),r.delete(`exp`),r.delete(k$),r.delete(A$),await t4.set({query:r.toString(),signedQueryIssuedAt:n??void 0,postLoginClearedForSession:i}),e.path===`/sign-in/social`&&await Oq({query:r.toString(),...n?{[i4]:n.getTime()}:{}})})}],after:[{matcher(e){return yG(e.context.responseHeaders?.get(`set-cookie`)||``).has(e.context.authCookies.sessionToken.name)},handler:Lq(async e=>{let t=yG(e.context.responseHeaders?.get(`set-cookie`)||``).get(e.context.authCookies.sessionToken.name)?.value.split(`.`)[0];if(!t)return;let n=await t4.get(),r=(await Tq())?.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??aye(r?.[i4]),d=C1(a,`login`);return S1(o.session.createdAt,u)&&(d=w1(d)),e.query=x1(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`)?$0(e,a):Q0(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 $0(e,a)}),oauth2Authorize:s,oauth2Consent:X(`/oauth2/consent`,{method:`POST`,body:A({accept:Je().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:N1.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:[zJ],metadata:{openapi:{description:`Handle OAuth2 consent`,responses:{200:{description:`Consent processed successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect:{type:`boolean`,description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:`string`,format:`uri-reference`,description:`The absolute or relative URI to redirect to next.`}},required:[`redirect`,`url`]}}}}}}}},async e=>m_e(e,a,c)),oauth2Continue:X(`/oauth2/continue`,{method:`POST`,body:A({selected:Je().optional().meta({description:`Confirms an account has been selected and authorization can proceed.`}),created:Je().optional().meta({description:`Confirms an account was registered`}),postLogin:Je().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:[zJ],metadata:{openapi:{description:`Continues OAuth2 authorization flow`,responses:{200:{description:`Authorization flow continued successfully`,content:{"application/json":{schema:{type:`object`,properties:{redirect:{type:`boolean`,description:"Always true. Indicates the caller should redirect to `url`.",enum:[!0]},url:{type:`string`,format:`uri-reference`,description:`The absolute or relative URI to redirect to next.`}},required:[`redirect`,`url`]}}}}}}}},async e=>h_e(e,c)),oauth2Token:t2(`/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:O1.optional(),refresh_token:k().optional(),resource:Ae([B1,Be(B1).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 vge(e.request);t&&t.length>1&&(e.body.resource=t)}return Ige(e,a)}),oauth2Introspect:t2(`/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=>A0(e,a)),oauth2Revoke:t2(`/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=>rye(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=>Pge(e,a)),oauth2EndSession:t2(`/oauth2/end-session`,{method:[`GET`,`POST`],body:e4.optional(),query:e4.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=>M_e(e,a)),oauth2EndSessionConfirmation:t2(`/oauth2/end-session/confirm`,{method:`POST`,body:A({action:Ye(`confirm`)}),metadata:{noStore:!0,allowedMediaTypes:[`application/x-www-form-urlencoded`],scope:`http`}},async e=>N_e(e,a)),registerOAuthClient:t2(`/oauth2/register`,{method:`POST`,body:U1,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=>cve(e,a)),adminCreateOAuthClient:vve(a),createOAuthClient:yve(a),getOAuthClient:bve(a),getOAuthClientPublic:xve(a),getOAuthClientPublicPrelogin:Sve(a),getOAuthClients:Cve(a),adminUpdateOAuthClient:wve(a),updateOAuthClient:Tve(a),rotateClientSecret:Eve(a),rotateClientKeys:Dve(a),deleteOAuthClient:Ove(a),getOAuthConsent:Nve(a),getOAuthConsents:Pve(a),updateOAuthConsent:Fve(a),deleteOAuthConsent:Ive(a),adminCreateOAuthResource:Kve(a),adminListOAuthResources:qve(a),adminGetOAuthResource:Jve(a),adminUpdateOAuthResource:Yve(a),adminDeleteOAuthResource:Xve(a),adminLinkClientResource:Zve(a),adminUnlinkClientResource:Qve(a)},schema:sG(structuredClone(iye),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 oye(e,t,n){return t!==0&&n.getTime()-e.getTime()<=t*1e3}function sye(e){let{max_age:t,...n}=e;return n}function o4(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()}`:vq(e,o)}function cye(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 lye={response_type:{invalid:`unsupported_response_type`},resource:{invalid:`invalid_target`}};function uye(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function s4(e){return typeof e==`string`?e:void 0}function dye(e,t){let n=e.method===`POST`&&t?.isAuthorize===!0?e.body:e.query;return{...uye(n)?n:{}}}const c4=(e,t)=>{let n=j0(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 l4(e,t,n,r,i){return c4(e,o4(n.redirect_uri,r,i,n.state,d4(e,t)))}function u4(e){try{let t=new URL(e);return t.protocol!==`https:`&&!_Y(t.host)&&(t.protocol=`https:`),t.search=``,t.hash=``,t.toString().replace(/\/$/,``)}catch{return e}}function d4(e,t){let n;if(t.disableJwtPlugin)n=e.context.baseURL;else try{n=K$(e.context).options?.jwt?.issuer??e.context.baseURL}catch{n=e.context.baseURL}return u4(n)}function f4(e,t,n){return o4(e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,t,n)}function p4(e){let t;try{t=new URL(e)}catch{return}let n=gY(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 m4(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=p4(t);return e.find(e=>e===t?!0:a?p4(e)===a:!1)}function h4(e){if(!O1.safeParse(e).success)return!1;let t=new URL(e);return t.username.length===0&&t.password.length===0}async function fye(e,t,n,r){if(!n||!r)return null;let i;try{i=await e1(e,t,n)}catch{return null}if(!i||i.disabled)return null;let a=i.redirectUris??[],o=m4(a,r);if(t.validateRedirectUri){if(!h4(r))return null;try{return await t.validateRedirectUri(r,a,!!o)?r:null}catch{return null}}return o?r:null}function g4(e){return async({error:t,error_description:n,ctx:r})=>{let i=r.query??{},a=await fye(r,e,typeof i.client_id==`string`?i.client_id:void 0,typeof i.redirect_uri==`string`?i.redirect_uri:void 0);return a?c4(r,o4(a,t,n,typeof i.state==`string`?i.state:void 0,d4(r,e),cye(i))):c4(r,f4(r,t,n))}}async function pye(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=dye(e,n);e.query=i;let a=s4(i.request),o=s4(i.request_uri);if(a!==void 0&&o!==void 0)return g4(t)({error:`invalid_request`,error_description:`request and request_uri cannot be used together`,ctx:e});if(a!==void 0)return g4(t)({error:`request_not_supported`,error_description:`request object not supported`,ctx:e});if(o!==void 0){let n=s4(i.client_id);if(!n)return g4(t)({error:`invalid_request`,error_description:`client_id is required`,ctx:e});if(!t.requestUriResolver)return g4(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 g4(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=H1.safeParse(i);if(!s.success){let n=n2(s.error.issues,lye);return g4(t)({...n,ctx:e})}if(i=s.data,e.query=i,await t4.set({query:_4(i).toString()}),!i.response_type)return g4(t)({error:`invalid_request`,error_description:`response_type is required`,ctx:e});let c=e.query?.prompt?_1(e.query?.prompt):void 0,l=c?.has(`none`)??!1;if(c?.has(`select_account`)&&!t.selectAccount?.page)return c4(e,f4(e,`unsupported_prompt_select_account`,`unsupported prompt type`));if(i.response_type!==`code`)return c4(e,f4(e,`unsupported_response_type`,`unsupported response type`));let u=await e1(e,t,i.client_id);if(!u)return c4(e,f4(e,`invalid_client`,`client not found`));if(u.disabled)return c4(e,f4(e,`client_disabled`,`client is disabled`));if(!u1(u,`authorization_code`))return c4(e,f4(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=!!m4(d,i.redirect_uri);if(t.validateRedirectUri&&h4(i.redirect_uri))try{f=await t.validateRedirectUri(i.redirect_uri,d,e)}catch{f=!1}else t.validateRedirectUri||(f=e)}if(!f)return c4(e,f4(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 c4(e,o4(i.redirect_uri,`invalid_scope`,`The following scopes are invalid: ${r.join(`, `)}`,i.state,d4(e,t)))}p||(p=u.scopes??t.scopes??[],i.scope=p.join(` `));let m=p.includes(`openid`);if(i.claims!==void 0&&!m)return c4(e,o4(i.redirect_uri,`invalid_request`,`openid scope must be requested when using the claims parameter`,i.state,d4(e,t)));if(m&&!nge(i.claims))return c4(e,o4(i.redirect_uri,`invalid_request`,`claims must be a valid Claims request object`,i.state,d4(e,t)));if(m&&!rge(i.claims,`0`))return c4(e,o4(i.redirect_uri,`access_denied`,`essential acr requirement cannot be met`,i.state,d4(e,t)));let h=P1(i.claims,R1(t));if(i.resource!==void 0)try{await q1(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 c4(e,o4(i.redirect_uri,r,a,i.state,d4(e,t)))}throw n}let g=T1(u,{scopes:p,nonce:i.nonce});if(g&&(!i.code_challenge||!i.code_challenge_method))return c4(e,o4(i.redirect_uri,`invalid_request`,g.valueOf(),i.state,d4(e,t)));if(i.code_challenge||i.code_challenge_method){if(!i.code_challenge||!i.code_challenge_method)return c4(e,o4(i.redirect_uri,`invalid_request`,`code_challenge and code_challenge_method must both be provided`,i.state,d4(e,t)));if(![`S256`].includes(i.code_challenge_method))return c4(e,o4(i.redirect_uri,`invalid_request`,`invalid code_challenge method, only S256 is supported`,i.state,d4(e,t)))}let _=Y$(i.resource)??[],v=await LJ(e),y=i.max_age,b=v!=null&&y!==void 0&&oye(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?l4(e,t,i,`login_required`,`authentication required`):y4(e,t,c?.has(`create`)?`create`:`login`);if(b&&(i=sye(i),e.query=i),n?.isAuthorize&&c?.has(`select_account`))return y4(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?l4(e,t,i,`account_selection_required`,`End-User account selection is required`):y4(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?l4(e,t,i,`interaction_required`,`End-User interaction is required`):y4(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?l4(e,t,i,`interaction_required`,`End-User interaction is required`):y4(e,t,`post_login`);if(c?.has(`consent`))return y4(e,t,`consent`,{sessionId:v.session.id});let x=await y1(t,{user:v.user,session:v.session,scopes:p});if(u.skipConsent)return v4(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 b1(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?l4(e,t,i,`consent_required`,`End-User consent is required`):y4(e,t,`consent`,{sessionId:v.session.id});let ee=S?.resources??[];return _.some(e=>!ee.includes(e))?l?l4(e,t,i,`consent_required`,`End-User consent is required`):y4(e,t,`consent`,{sessionId:v.session.id}):v4(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 _4(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 v4(e,t,n){let r=KH(32,`a-z`,`A-Z`,`0-9`),i=Math.floor(Date.now()/1e3),a=i+(t.codeExpiresIn??600),o={identifier:await a1(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`,d4(e,t)),c4(e,s.toString())}async function y4(e,t,n,r){let i=await mye(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 c4(e,`${r?.page??a}?${i}`)}async function mye(e,t,n){let r=Date.now(),i=Math.floor(r/1e3)+(t.codeExpiresIn??600),a=_4(e.query);a.set(`exp`,String(i)),a.set(k$,String(r)),a.delete(`sig`),a.delete(A$),n?.postLoginClearedForSession&&a.set(A$,n.postLoginClearedForSession),vhe(a);let o=await zW(M$(a).toString(),e.context.secret);return a.set(`sig`,o),a.toString()}const hye=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,gye=/* @__PURE__ */ new Set([`client_secret_post`,`client_secret_basic`,`client_secret_jwt`]);function b4(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`}function _ye(e){if(hye.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`:vY(t.hostname)?null:`client_id URL must not target a private or reserved address`}function vye(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 yye(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||D1(t)}catch{return!1}}function bye(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(u2(e))return{valid:!1,error:`metadata document MUST NOT contain "${e}"`};let r=mge.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(gye.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&&!c2(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=>yye(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(!vY(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&&D1(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`||E1(n)))continue;let a=r&&(n.protocol===`http:`||n.protocol===`https:`)&&_Y(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(...vye(e)),{valid:!0,metadata:{...i,token_endpoint_auth_method:i.token_endpoint_auth_method??`none`},...a.length>0?{warnings:a}:{}}}const x4=5e3,S4=5120,xye=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,C4=`Failed to fetch metadata document (network error or redirect blocked)`,w4=`cimd`;function T4(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function E4(){return T4(`Metadata document exceeds ${S4/1024}KB size limit`)}async function Sye(e,t,n){let r=e.body?.getReader();if(!r){let n=await e.text();if(new TextEncoder().encode(n).byteLength>t)throw E4();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(),E4();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 Cye(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 wye(e,t,n,r){let i=_ye(t);if(i)throw T4(i);if(n.isMetadataDocumentUrlAllowed&&!await n.isMetadataDocumentUrlAllowed(t,e))throw T4(`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()},x4);try{try{o=await n.fetchClientMetadataResource(t,{headers:a,redirect:`error`,signal:s.signal})}catch{throw T4(c?`Metadata document fetch timed out after ${x4}ms`:C4)}if(o.redirected)throw T4(`Metadata document fetch must not follow redirects`);let i=Cye(o.headers);if(o.status===304){if(!r?.etag&&!r?.lastModified)throw T4(`Metadata document returned 304 without a conditional validator`);return{status:`not-modified`,cacheHeaders:i}}if(o.status!==200)throw T4(`Metadata document fetch returned HTTP ${o.status}`);let l=o.headers.get(`content-type`)??``;if(!xye.test(l))throw T4(`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>S4)throw await o.body?.cancel(),E4()}u=await Sye(o,S4,s.signal)}catch(e){throw c?T4(`Metadata document fetch timed out after ${x4}ms`):e instanceof O?e:T4(C4)}let d;try{d=JSON.parse(u)}catch{throw T4(`Metadata document is not valid JSON`)}let f=bye(t,d,{originBoundFields:n.originBoundFields,metadataProfile:n.metadataProfile});if(!f.valid)throw T4(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 D4(e,t,n,r,i,a){let o=a?{...a}:void 0,s=await z2(e,i,{clientId:t,clientDiscoveryId:w4,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 O4={minimumFetchInterval:1,maximumConcurrentFetches:16,maximumConcurrentFetchesPerOrigin:4,maximumFetchesPerMinute:120,maximumFetchesPerOriginPerMinute:30};function Tye(e){return new O(`BAD_REQUEST`,{error:`invalid_client`,error_description:e})}function k4(e){return new O(`TOO_MANY_REQUESTS`,{error:`temporarily_unavailable`,error_description:e})}function Eye(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=(x$(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 A4(e,t){if(!Number.isInteger(e)||e<1)throw new D(`cimd metadataFetchPolicy.${t} must be a positive integer`);return e}function Dye(e){let t=e.metadataFetchPolicy;return{minimumFetchIntervalMs:Eye(t?.minimumFetchInterval??O4.minimumFetchInterval,`minimumFetchInterval`),maximumConcurrentFetches:A4(t?.maximumConcurrentFetches??O4.maximumConcurrentFetches,`maximumConcurrentFetches`),maximumConcurrentFetchesPerOrigin:A4(t?.maximumConcurrentFetchesPerOrigin??O4.maximumConcurrentFetchesPerOrigin,`maximumConcurrentFetchesPerOrigin`),maximumFetchesPerMinute:A4(t?.maximumFetchesPerMinute??O4.maximumFetchesPerMinute,`maximumFetchesPerMinute`),maximumFetchesPerOriginPerMinute:A4(t?.maximumFetchesPerOriginPerMinute??O4.maximumFetchesPerOriginPerMinute,`maximumFetchesPerOriginPerMinute`)}}function j4(e,t){let n=t-6e4,r=0;for(;r<e.length&&e[r]<=n;)r+=1;r>0&&e.splice(0,r)}function Oye(e,t){if(typeof e==`number`)return Math.max(0,e*1e3);let n=Math.floor(t/1e3);return Math.max(0,(x$(e,n)-n)*1e3)}function kye(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 M4(e){if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function Aye(e,t,n){let{directives:r,duplicates:i}=kye(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=Oye(t,n);if(r.has(`no-cache`))return{cacheable:!0,expiresAt:n};let s=M4(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=M4(r.get(`s-maxage`)),m=r.has(`max-age`),h=M4(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 jye(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 Mye(e,t,n,r){let i=Aye(t,n,r);return i.cacheable?{metadata:e,expiresAt:i.expiresAt,etag:t.etag,lastModified:t.lastModified,responseCacheHeaders:t}:null}function Nye(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=Dye(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 k4(`metadata fetch client state is at capacity`)}},p=(e,t)=>{let r=s.get(e);if(r)return j4(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(j4(r.fetchStartTimesMs,t),!(r.activeFetchCount>0||r.fetchStartTimesMs.length>0)){s.delete(n),e=!0;break}if(!e)throw k4(`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 k4(`metadata document fetch is within the per-client minimum interval`);f(e,t);let i=new URL(e).origin,a=p(i,t);if(j4(c,t),l>=r.maximumConcurrentFetches)throw k4(`global metadata fetch concurrency limit exceeded`);if(a.activeFetchCount>=r.maximumConcurrentFetchesPerOrigin)throw k4(`metadata fetch concurrency limit exceeded for client origin`);if(c.length>=r.maximumFetchesPerMinute)throw k4(`global metadata fetch rate limit exceeded`);if(a.fetchStartTimesMs.length>=r.maximumFetchesPerOriginPerMinute)throw k4(`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(!b4(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||D4(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 wye(n,r,e,f?{etag:f.etag,lastModified:f.lastModified}:void 0);if(a.status===`not-modified`&&!f)throw Tye(`Metadata document returned 304 without a validated cached document`);let c=a.status===`modified`?a.metadata:f.metadata,u=await D4(n,r,c,e,l,s??void 0),p=Mye(c,a.status===`modified`?a.cacheHeaders:jye(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 Pye(e){return{id:w4,matches:b4,resolve:Nye(e),fetchClientMetadataResource:e.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}}}const Fye=e=>{let t=Pye(e);return{id:`cimd`,version:`1.7.12`,init(e){Dhe(e,{clientDiscovery:t})}}},Iye=/* @__PURE__ */ new Set([204,205,304]);function Lye(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 Rye=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(!vY(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=pee(r,{agent:!1,headers:o,method:n.method,servername:Tt(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`||Iye.has(r)?null:St.toWeb(t);e(new Response(i,{headers:Lye(t.headers),status:r,statusText:t.statusMessage}))});i.once(`error`,t),i.end()})};function zye(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 N4=class e extends P()(`clankerauth/CimdTransport`){static layer=uf(e,{fetch:zye(Rye)});static layerWith=t=>t===void 0?e.layer:uf(e,{fetch:t})};const P4=`x-clankerauth-peer`,Bye=e=>dee({requestTimeout:15e3,headersTimeout:1e4},e),Vye=(e,t)=>{t.writeHead(503).end()},Hye=dm(`NodeHttp.listen`)(function*(e,t){let n=Vye,r=Bye((e,t)=>n(e,t)),i=$f(e=>{r.close(()=>e(L)),r.closeAllConnections()});yield*Bp($f(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=>Vp(()=>i).pipe(cp(()=>I(()=>n=e)))}:yield*rp(/* @__PURE__ */ Error(`Expected a TCP listener`))}),Uye=lh(65536),Wye=/^\/forward-auth(?:\?|$)/,Gye=(e,t,n)=>{let r=(e[`x-forwarded-for`]?.split(`,`).map(e=>e.trim()).filter(Boolean))?.at(-1);return n&&r?r:Fi(t,()=>`unknown`)},Kye=({baseURL:e,trustProxy:t})=>n=>R(function*(){let r=yield*dM,i=r.source,a=i instanceof wt?i.url:r.url;if(!a?.startsWith(`/`)||a.startsWith(`//`))return sj({status:400});let o=zt(r.headers,Wye.test(a)?xg(`forwarded`):Sg([`forwarded`,`x-forwarded-host`,`x-forwarded-proto`]),vg(`host`,new URL(e).host),vg(P4,Gye(r.headers,r.remoteAddress,t)),xg(`x-forwarded-for`)),s=yield*n.pipe(Lp(dM,r.modify({headers:o})),Lp(kA,Uye));return i instanceof wt?AO(s.body).pipe(MO(`Stream`,e=>bj(s,oA(e.stream.pipe(zE(()=>I(()=>i.socket.destroy()))),e.contentType,e.contentLength))),RO(()=>s)):s}).pipe(Jp),F4=e=>`${I4}${e}`,I4=`resource:`,L4=(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})`,R4=dm(`Authorization.clear`)(function*(e,t){let n=t.clientId??null,r=t.resource===void 0?null:F4(t.resource);yield*e`DELETE FROM oauthConsent WHERE (${n} IS NULL OR clientId = ${n}) AND (${r} IS NULL OR referenceId = ${r})`,yield*L4(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})`}),qye=Ooe(W({message:Mx(U),error_description:Mx(U)})),Jye=e=>Fi(Hi(qye(e.body),e=>Li(e.message??e.error_description)),()=>`Request could not be completed`),z4=e=>new eV({message:e}),B4=e=>new JB({message:e}),V4=(e,t={})=>Xf({try:e,catch:e=>{if(!Nq(e))return qB.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(Jye(e)):qB.of(e)}}),H4=(e,t)=>new wI({message:t,issues:[{path:e,message:t}]}),Yye=Sx(K(UV)),Xye=ln(`RequestParseError`),Zye=e=>Yye(e)?e:gce(e)&&Xye(e.reason)?new tV({message:`Request body could not be read`}):qB.of(e),Qye=new Map(UV.map(e=>[e,ob(`httpApiStatus`)(e.ast)??500])),$ye=$se(K(UV)),U4=e=>{let t=Zye(e),n=UV.find(e=>Sx(e)(t));return $ye(t,{status:Qye.get(n)??500}).pipe(yp)},W4=(e,t)=>e===t||e.endsWith(`.${t}`),ebe=e=>{try{return new URL(`https://${e}`).hostname===e&&e.includes(`.`)&&!Tt(e)}catch{return!1}},G4=(e,t)=>e.protocol===`https:`||e.protocol===`http:`&&([`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||t),K4=`HTTPS origins (HTTP allowed on loopback, or anywhere with CLANKERAUTH_ALLOW_INSECURE_HTTP=true)`,q4=(e,t)=>URL.canParse(e)&&new URL(e).origin===e&&G4(new URL(e),t),J4=H(function*(e){let{allowInsecureHttp:t,baseURL:n,cookieDomain:r}=e;return q4(n,t)?lg(e.secret).length<32?yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BETTER_AUTH_SECRET must have at least 32 characters`)):e.mcpAllowedOrigins.every(e=>q4(e,t))?r!==void 0&&(!ebe(r)||!W4(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 ${K4}`)):yield*z(/* @__PURE__ */ Error(`CLANKERAUTH_BASE_URL must be one of: ${K4}`))}),tbe=R(function*(){let e={baseURL:yield*WD(`CLANKERAUTH_BASE_URL`),secret:yield*JD(`CLANKERAUTH_BETTER_AUTH_SECRET`),database:yield*WD(`CLANKERAUTH_DATABASE`).pipe(jD(`data/clankerauth.sqlite`)),host:yield*WD(`CLANKERAUTH_HOST`).pipe(jD(`127.0.0.1`)),port:yield*qD(`CLANKERAUTH_PORT`).pipe(jD(3e3)),mcpAllowedOrigins:yield*GD(TS,`CLANKERAUTH_MCP_ALLOWED_ORIGINS`).pipe(jD([])),trustProxy:yield*KD(`CLANKERAUTH_TRUST_PROXY`).pipe(jD(!1)),allowInsecureHttp:yield*KD(`CLANKERAUTH_ALLOW_INSECURE_HTTP`).pipe(jD(!1)),cookieDomain:yield*WD(`CLANKERAUTH_COOKIE_DOMAIN`).pipe(jD(void 0))};return yield*J4(e)});var Y4=class e extends P()(`clankerauth/Settings`){static layer=pf(e,tbe)};const X4=`Exactly one configured resource is required`,Z4=[`offline_access`],nbe=$V(SS(G(U))),rbe=$V(W({identifier:U,name:U,allowedScopes:U})),Q4=$V(G(EV)),$4=(e,t)=>[.../* @__PURE__ */ new Set([...Z4,...t.flatMap(t=>e.find(e=>e.identifier===t)?.scopes??[])])],e3=dm(`ResourceCatalog.validateSelection`)(function*(e,t){let n=t.findIndex(t=>!e.some(e=>e.identifier===t));if(n!==-1)return yield*H4([`resources`,n],`Unknown Resource`)}),t3=dm(`ResourceCatalog.accessForClient`)(function*(e,t){return yield*Q4(yield*t`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource WHERE clientId = ${e} ORDER BY resourceId`)});var n3=class e extends P()(`clankerauth/ResourceCatalog`){static layer=pf(e,R(function*(){let{sql:e}=yield*rH,t=sV((yield*Y4).baseURL),n=dm(`ResourceCatalog.decode`)(function*(e){let n=yield*rbe(e),r=yield*nbe(n.allowedScopes);return{identifier:n.identifier,name:n.name,scopes:r.filter(e=>!Z4.includes(e)),builtIn:n.identifier===t}}),r=dm(`ResourceCatalog.list`)(function*(){let t=yield*e`SELECT identifier, name, allowedScopes FROM oauthResource ORDER BY createdAt, identifier`;return yield*qf(t,n)}),i=dm(`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:dm(`ResourceCatalog.access`)(function*(){return yield*Q4(yield*e`SELECT clientId AS client_id, resourceId AS resource FROM oauthClientResource ORDER BY clientId, resourceId`)}),hasAccess:dm(`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:dm(`ResourceCatalog.scopesFor`)(function*(e){let t=yield*r();return yield*e3(t,e),$4(t,e)})}}))};const ibe=Doe(W({typ:U,payload:Gx(U,QS)})),abe=e=>({id:`signer`,endpoints:{signDocument:X.serverOnly({method:`POST`,body:ibe},async t=>t.json({token:await w$(t,{options:e,header:{typ:t.body.typ},payload:t.body.payload})}))}}),obe=e=>typeof e==`string`,sbe=(e,t,n,r,i,a)=>{let o={disableSettingJwtHeader:!0,jwt:{issuer:`${e.baseURL}/api/auth`},jwks:{keyPairConfig:{alg:`EdDSA`,crv:`Ed25519`}}},s=a4({loginPage:`/login`,consentPage:`/consent`,scopes:[...Z4],resources:[{identifier:sV(e.baseURL),name:`clankerauth administration`,allowedScopes:[...Z4,cV.read,cV.write]}],resourceSeedMode:`merge`,rateLimit:{register:{window:60,max:10}},postLogin:{page:`/consent`,shouldRedirect:()=>!1,consentReferenceId:async({scopes:e})=>{let t=await n4(),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:X4});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 F4(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:lg(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:Lq(async e=>{if(e.path===`/oauth2/register`){let t=e.body.redirect_uris;!e.body.application_type&&Array.isArray(t)&&t.some(e=>{if(!obe(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:[P4]}},rateLimit:{enabled:!0,storage:`database`,window:60,max:100,customRules:{"/sign-in/email":{window:60,max:5}}},plugins:[she({defaultPrefix:`clankerauth_`,maximumNameLength:100,enableSessionForAPIKeys:!1,keyExpiration:{defaultExpiresIn:null,minExpiresIn:0},rateLimit:{enabled:!1}}),_he(o),abe(o),s,Fye({fetchClientMetadataResource:r,metadataProfile:`mcp-2026-07-28`,metadataRevalidationInterval:300,maxCacheEntries:1e3,metadataFetchPolicy:{maximumConcurrentFetches:8,maximumConcurrentFetchesPerOrigin:2,maximumFetchesPerMinute:60,maximumFetchesPerOriginPerMinute:15}})]},oauthPlugin:s}};var r3=class e extends P()(`clankerauth/Issuer`){static layer=pf(e,R(function*(){let e=yield*Y4,{kysely:t}=yield*rH,n=yield*n3,{fetch:r}=yield*N4,i=cm(yield*Ap()),{options:a,oauthPlugin:o}=sbe(e,t,n,r,i,async()=>await(await bH((await s.$context).adapter)).count({model:`user`})>0),{auth:s,context:c}=yield*dm(`Auth.initialize`)(function*(){let e=yield*Xf(()=>DQ(a));if(e.schemaProblems.length)return yield*z(/* @__PURE__ */ Error(`Database schema requires manual repair`));yield*Xf(()=>e.runMigrations());let t=Eme(a),n=yield*Xf(()=>t.$context);return yield*Xf(()=>t.api.getJwks()),{auth:t,context:n}},Xp)();return{auth:s,context:c,publishScopes:e=>I(()=>{o.options.scopes=[...e]})}}))};const cbe=Cx(kV),lbe=Cx(W({id:U,key:U,referenceId:U,expiresAt:Zx(FS),permissions:Zx(SS(kV))})),i3=H(function*(e){return{keyId:e.id,name:e.name??``,enabled:e.enabled,permissions:yield*cbe(e.permissions??{}).pipe(pp(()=>dp(mm(`An API key's stored permissions do not decode; it is listed with none`,{keyId:e.id}),{}))),expiresAt:e.expiresAt?ph(e.expiresAt):null,createdAt:ph(e.createdAt)}});var a3=class e extends P()(`clankerauth/ApiKeys`){static layer=pf(e,R(function*(){let{auth:e}=yield*r3,{sql:t}=yield*rH,n=yield*n3,r=dm(`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*H4([`permissions`,t],`Administration requires OAuth access tokens, not API keys`);if(!e||r.some(t=>!e.scopes.includes(t)))return yield*H4([`permissions`,t],`Select explicitly granted, currently available Resource scopes`)}});return{list:dm(`ApiKeys.list`)(function*(){let{providerHeaders:t}=yield*rV,n=yield*t,r=yield*V4(()=>e.api.listApiKeys({headers:n,query:{sortBy:`createdAt`,sortDirection:`asc`}}));return{keys:yield*qf(r.apiKeys,i3)}}),create:dm(`ApiKeys.create`)(function*(t){let n=yield*rV;yield*r(t.permissions);let i=t.expiresAt===null?null:(_h(t.expiresAt)-(yield*Ef))/1e3;if(i!==null&&i<1)return yield*H4([`expiresAt`],`Expiry must be in the future`);let a=yield*V4(()=>e.api.createApiKey({body:{userId:n.userId,name:t.name.trim(),permissions:Ea(t.permissions,e=>[...e]),expiresIn:i}}),{refused:z4});return{...yield*i3(a),key:a.key}}),update:dm(`ApiKeys.update`)(function*(t){let n=yield*rV;return yield*r(t.permissions),yield*i3(yield*V4(()=>e.api.updateApiKey({body:{userId:n.userId,keyId:t.keyId,name:t.name?.trim(),enabled:t.enabled,permissions:t.permissions&&Ea(t.permissions,e=>[...e])}}),{refused:z4,missing:()=>ZB.of(t.keyId)}))}),delete:dm(`ApiKeys.delete`)(function*({keyId:t}){let{providerHeaders:n}=yield*rV,r=yield*n;return yield*V4(()=>e.api.deleteApiKey({headers:r,body:{keyId:t}}),{missing:()=>ZB.of(t)}),{deleted:!0}}),keyList:dm(`ApiKeys.keyList`)(function*(r){let i=yield*Ef,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*qf(o,e=>R(function*(){let t=yield*lbe(e),n=(t.permissions?.[r]??[]).filter(e=>a.includes(e));return n.length?[yield*Xf(()=>Gde(new Uint8Array(Buffer.from(t.key,`base64url`)),r,{keyId:t.id,ownerId:t.referenceId,scopes:n,expiresAt:t.expiresAt===null?null:_h(t.expiresAt)}))]:[]}).pipe(pp(()=>dp(mm(`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*V4(()=>e.api.signDocument({body:{typ:_I,payload:{aud:r,iat:c,exp:c+86400,keys:s.flat()}}}));return{list:l}})}}))};const o3=e=>e.userId===null,ube=$V(G(W({userId:Zx(U)}))),s3=dm(`Clients.requireManaged`)(function*(e,t){let[n]=yield*ube(yield*t`SELECT userId FROM oauthClient WHERE clientId = ${e}`);if(!n)return yield*z(YB.of(e));if(o3(n))return yield*z(QB.of(e))}),dbe=$V(G(W({clientId:U}))),c3=e=>({identifier:encodeURIComponent(e)}),fbe=e=>{try{return new URL(e).href===e&&!e.includes(`#`)}catch{return!1}},pbe=dm(`Resources.validateInput`)(function*(e){let t=e.identifier.trim(),n=e.name.trim(),r=[...new Set(e.scopes.map(e=>e.trim()))];if(!fbe(t))return yield*H4([`identifier`],`Resource identifiers must be absolute URIs in canonical form, without a fragment`);let i=e.scopes.findIndex(e=>Z4.includes(e.trim()));return i===-1?{identifier:t,name:n,scopes:r}:yield*H4([`scopes`,i],`offline_access is reserved`)});var l3=class e extends P()(`clankerauth/Resources`){static layer=pf(e,R(function*(){let{sql:e,transaction:t}=yield*rH,{auth:n,publishScopes:r}=yield*r3,i=yield*n3,a=yield*Pw(1),o=e=>a.withPermit(e),s=dm(`Resources.syncClient`)(function*(e,t,n){let r=yield*t3(n,e),i=JSON.stringify($4(t,r.map(e=>e.resource)));yield*e`UPDATE oauthClient SET scopes = ${i}, updatedAt = ${yield*Ef} WHERE clientId = ${n} AND scopes IS NOT ${i}`}),c=dm(`Resources.synchronize`)(function*(){let t=yield*i.list(),n=$4(t,t.map(e=>e.identifier));yield*r(n),yield*e`UPDATE oauthClient SET scopes = ${JSON.stringify(n)}, updatedAt = ${yield*Ef} WHERE userId IS NULL AND scopes IS NOT ${JSON.stringify(n)}`;for(let n of yield*dbe(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(H4([`identifier`],`The administration Resource is fixed`)):L,u=B(rV,e=>e.providerHeaders);yield*c();let d=dm(`Resources.link`)(function*(n,r){let a=yield*i.list();yield*e3(a,r);let o=yield*Ef;return yield*t(e=>R(function*(){let t=(yield*t3(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*R4(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*t3(n,e)},o);return{link:d,get:dm(`Resources.get`)(function*({identifier:e}){return(yield*i.get(e))??(yield*XB.of(e))}),put:dm(`Resources.put`)(function*(e){let r=yield*pbe(e),a=yield*i.get(r.identifier);yield*l(a);let o=yield*u,s=[...Z4,...r.scopes];return a===void 0?(yield*t(e=>R4(e,{resource:r.identifier})),yield*V4(()=>n.api.adminCreateOAuthResource({headers:o,body:{identifier:r.identifier,name:r.name,allowedScopes:s}}),{refused:z4})):yield*V4(()=>n.api.adminUpdateOAuthResource({headers:o,params:c3(r.identifier),body:{name:r.name,allowedScopes:s}}),{refused:z4}),yield*c(),{resource:r,created:a===void 0}},o),delete:dm(`Resources.delete`)(function*({identifier:e}){yield*l(yield*i.get(e));let r=yield*u;return yield*V4(()=>n.api.adminDeleteOAuthResource({headers:r,params:c3(e)}),{missing:()=>XB.of(e)}),yield*t(t=>R4(t,{resource:e})),yield*c(),{deleted:!0}},o),setAccess:dm(`Resources.setAccess`)(function*({client_id:t,resources:n}){return yield*s3(t,e),{clientAccess:yield*d(t,n)}})}}))};const mbe=$V(G(W({client_id:U,resource:U,scopes:SS(G(U)),approvedAt:Zx(FS),refreshedAt:Zx(FS)}))),hbe=$V(G(W({clientId:U,name:Zx(U),redirectUris:SS(G(U)),tokenEndpointAuthMethod:Zx(U),applicationType:Zx(U),scopes:Zx(SS(G(U))),grantTypes:Zx(SS(G(U))),disabled:Zx(Bx),clientDiscoveryId:Zx(U),userId:Zx(U)})));var u3=class e extends P()(`clankerauth/Clients`){static layer=pf(e,R(function*(){let{sql:e,transaction:t}=yield*rH,{auth:n}=yield*r3,{baseURL:r}=yield*Y4,i=yield*n3,a=yield*l3,o=dm(`Clients.exists`)(function*(e,t){if(!(yield*t`SELECT 1 FROM oauthClient WHERE clientId = ${e}`).length)return yield*z(YB.of(e))}),s=dm(`Clients.revoke`)(function*(e,t,n){return yield*o(e,n),yield*R4(n,{clientId:e,resource:t}),{revoked:!0}}),c=dm(`Clients.connections`)(function*(){let t=new Date(yield*Ef).toISOString();return(yield*mbe(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 = ${I4} || 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=>!Z4.includes(e))}))});return{connections:c,list:dm(`Clients.list`)(function*(){let{email:t}=yield*rV,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*hbe(n)).map(e=>({client_id:e.clientId,onboarding:e.clientDiscoveryId===null?o3(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*Kf({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:dm(`Clients.create`)(function*(e){let{providerHeaders:t}=yield*rV,r=yield*i.scopesFor(e.resources),o=yield*t,s=yield*V4(()=>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:z4});return yield*a.link(s.client_id,e.resources).pipe(bp(()=>V4(()=>n.api.deleteOAuthClient({headers:o,body:{client_id:s.client_id}})))),s}),update:dm(`Clients.update`)(function*(t){yield*s3(t.client_id,e);let{providerHeaders:r}=yield*rV,i=yield*r;return yield*V4(()=>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:z4,missing:()=>YB.of(t.client_id)})}),rotate:dm(`Clients.rotate`)(function*(t){yield*s3(t.client_id,e);let{providerHeaders:r}=yield*rV,i=yield*r;return yield*V4(()=>n.api.rotateClientSecret({headers:i,body:t}),{refused:z4,missing:()=>YB.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*L4(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*Ef} WHERE clientId = ${e}`,{blocked:n}}))}}))};const gbe=[`/`,`/resources`,`/keys`,`/login`,`/setup`,`/consent`],_be=({readOnly:e,mcp:t})=>({readOnlyHint:e,destructiveHint:t.destructiveHint??!e,idempotentHint:t.idempotentHint??!1,openWorldHint:t.openWorldHint??!0}),d3=`~effect/ai/AiError/Reason`;var vbe=class extends (/*#__PURE__*/ KS(`effect/ai/AiError/ToolParameterValidationError`)({_tag:/*#__PURE__*/ tS(`ToolParameterValidationError`),toolName:U,description:U})){[d3]=d3;get isRetryable(){return!0}get message(){return`Invalid parameters for tool '${this.toolName}': ${this.description}`}};const f3=`~effect/rpc/RpcMiddleware`,ybe=()=>(e,t)=>{let n=nr(),r;n!==0&&(rr(2),r=new globalThis.Error,rr(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[f3]=f3,a.error=t?.error??Lx,a.requiredForClient=t?.requiredForClient??!1,i},p3=(e,t)=>{let n=I(t);return Mx(e).pipe(Boe({decode:gie(n),encode:nv()}),eS(n))},Z=e=>Mx(e).pipe($x(Px(Nx(e)),{decode:nv(),encode:av(Hi(Ri))})),bbe=/*#__PURE__*/ K([U,cS]),m3=/*#__PURE__*/ K([U,cS]);var h3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(/*#__PURE__*/ Kx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ Z(m3)}),[q]))}))){},g3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){},_3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({_meta:/*#__PURE__*/ Z(q)}))){};const xbe=U;({...h3.fields});var v3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...g3.fields,nextCursor:/*#__PURE__*/ Z(xbe)}))){};const y3=/*#__PURE__*/ Xx([`user`,`assistant`]);var b3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({audience:/*#__PURE__*/ Z(/*#__PURE__*/ G(y3)),priority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),lastModified:/*#__PURE__*/ Z(U)}))){},x3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Icon`)({src:U,mimeType:/*#__PURE__*/ Z(U),sizes:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`light`,`dark`]))})){},S3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),version:U,icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),description:/*#__PURE__*/ Z(U),websiteUrl:/*#__PURE__*/ Z(U)}))){},C3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ClientCapabilities`)({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),QS)),roots:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Vx)})),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({}))}))})){},Sbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({experimental:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,/*#__PURE__*/ W({}))),extensions:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),QS)),logging:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),completions:/*#__PURE__*/ Z(/*#__PURE__*/ W({})),prompts:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Vx)})),resources:/*#__PURE__*/ Z(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ Z(Vx),listChanged:/*#__PURE__*/ Z(Vx)})),tools:/*#__PURE__*/ Z(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ Z(Vx)}))}))){},w3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/McpErrorBase`)({code:dS,message:U,data:/*#__PURE__*/ Z(Rx)})){};const T3=-32601,E3=-32602,D3=-32603,O3=-32020;var k3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/ParseError`)({...w3.fields,_tag:/*#__PURE__*/ tS(`ParseError`),code:/*#__PURE__*/ tS(-32700)})){},A3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/InvalidRequest`)({...w3.fields,_tag:/*#__PURE__*/ tS(`InvalidRequest`),code:/*#__PURE__*/ tS(-32600)})){},j3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/MethodNotFound`)({...w3.fields,_tag:/*#__PURE__*/ tS(`MethodNotFound`),code:/*#__PURE__*/ tS(T3)})){},M3=class extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/InvalidParams`)({...w3.fields,_tag:/*#__PURE__*/ tS(`InvalidParams`),code:/*#__PURE__*/ tS(E3)})){},N3=class e extends (/*#__PURE__*/ KS(`effect/ai/McpSchema/InternalError`)({...w3.fields,_tag:/*#__PURE__*/ tS(`InternalError`),code:/*#__PURE__*/ tS(D3)})){static notImplemented=/*#__PURE__*/ new e({message:`Not implemented`})};const P3=/*#__PURE__*/ K([k3,A3,j3,M3,N3,w3]);var Cbe=class extends (/*#__PURE__*/ J(`ping`,{success:/*#__PURE__*/ W({}),error:P3,payload:/*#__PURE__*/ Qx(h3)})){},wbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...g3.fields,protocolVersion:U,capabilities:Sbe,serverInfo:S3,instructions:/*#__PURE__*/ Z(U)}))){},Tbe=class extends (/*#__PURE__*/ J(`initialize`,{success:wbe,error:P3,payload:{...h3.fields,protocolVersion:U,capabilities:C3,clientInfo:S3}})){},F3=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{..._3.fields,requestId:bbe,reason:/*#__PURE__*/ Z(U)}})){},I3=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{..._3.fields,progressToken:m3,progress:cS,total:/*#__PURE__*/ Z(cS),message:/*#__PURE__*/ Z(U)}})){},Ebe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Resource`)({uri:U,name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),mimeType:/*#__PURE__*/ Z(U),annotations:/*#__PURE__*/ Z(b3),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),size:/*#__PURE__*/ Z(dS),_meta:/*#__PURE__*/ Z(q)})){},L3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)}))){},Dbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...L3.fields,text:U}))){},Obe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...L3.fields,blob:OS}))){};({...v3.fields}),{...v3.fields},{...g3.fields},{...h3.fields};var R3=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ Qx(_3)})){};({...h3.fields}),{...h3.fields};var z3=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{..._3.fields,uri:U}})){},kbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),required:/*#__PURE__*/ Z(Vx)}))){},Abe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Prompt`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),arguments:/*#__PURE__*/ Z(/*#__PURE__*/ G(kbe)),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),_meta:/*#__PURE__*/ Z(q)})){},B3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`text`),text:U,annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){},V3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`image`),data:OS,mimeType:U,annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){},H3=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`audio`),data:OS,mimeType:U,annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){};const U3=/*#__PURE__*/ K([B3,V3,H3,class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`resource`),resource:/*#__PURE__*/ K([Dbe,Obe]),annotations:/*#__PURE__*/ Z(b3),_meta:/*#__PURE__*/ Z(q)}))){},class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({...Ebe.fields,type:/*#__PURE__*/ tS(`resource_link`)}))){}]);({...v3.fields}),{...g3.fields},{...h3.fields};var W3=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ Qx(_3)})){},jbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({title:/*#__PURE__*/ Z(U),readOnlyHint:/*#__PURE__*/ p3(Vx,It),destructiveHint:/*#__PURE__*/ p3(Vx,Ft),idempotentHint:/*#__PURE__*/ p3(Vx,It),openWorldHint:/*#__PURE__*/ p3(Vx,Ft)}))){};const G3=/*#__PURE__*/ Kx(/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,q)),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),[q]),K3=q;var q3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Tool`)({name:U,title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),inputSchema:G3,outputSchema:/*#__PURE__*/ Z(K3),annotations:/*#__PURE__*/ Z(jbe),icons:/*#__PURE__*/ Z(/*#__PURE__*/ G(x3)),_meta:/*#__PURE__*/ Z(q)})){};({...v3.fields});var J3=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/CallToolResult`)({...g3.fields,content:/*#__PURE__*/ G(U3),structuredContent:/*#__PURE__*/ Z(QS),isError:/*#__PURE__*/ Z(Vx)})){};({...h3.fields});var Y3=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ Qx(_3)})){};const X3=/*#__PURE__*/ Xx([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]);({...h3.fields});var Z3=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:/*#__PURE__*/ W({..._3.fields,level:X3,logger:/*#__PURE__*/ Z(U),data:Rx})})){};const Q3=/*#__PURE__*/ K([B3,V3,H3,class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ToolUseContent`)({type:/*#__PURE__*/ tS(`tool_use`),id:U,name:U,input:/*#__PURE__*/ Gx(U,zx),_meta:/*#__PURE__*/ Z(q)})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ToolResultContent`)({type:/*#__PURE__*/ tS(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(U3),structuredContent:/*#__PURE__*/ Z(QS),isError:/*#__PURE__*/ Z(Vx),_meta:/*#__PURE__*/ Z(q)})){}]);var Mbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({role:y3,content:/*#__PURE__*/ K([Q3,/*#__PURE__*/ G(Q3)]),_meta:/*#__PURE__*/ Z(q)}))){},Nbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ToolChoice`)({mode:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`auto`,`required`,`none`]))})){},Pbe=class extends (/*#__PURE__*/ rS()(/*#__PURE__*/ W({name:/*#__PURE__*/ Z(U)}))){},Fbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ModelPreferences`)({hints:/*#__PURE__*/ Z(/*#__PURE__*/ G(Pbe)),costPriority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ Z(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))})){},Ibe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/CreateMessageResult`)({role:y3,content:/*#__PURE__*/ K([Q3,/*#__PURE__*/ G(Q3)]),_meta:/*#__PURE__*/ Z(q),model:U,stopReason:/*#__PURE__*/ Z(U)})){},$3=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:Ibe,error:P3,payload:{messages:/*#__PURE__*/ G(Mbe),modelPreferences:/*#__PURE__*/ Z(/*#__PURE__*/ W(Fbe.fields)),systemPrompt:/*#__PURE__*/ Z(U),includeContext:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ Z(cS),maxTokens:dS,stopSequences:/*#__PURE__*/ Z(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,zx)),tools:/*#__PURE__*/ Z(/*#__PURE__*/ G(/*#__PURE__*/ W(q3.fields))),toolChoice:/*#__PURE__*/ Z(/*#__PURE__*/ W(Nbe.fields))}})){};({...g3.fields});var Lbe=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/Root`)({uri:U,name:/*#__PURE__*/ Z(U),_meta:/*#__PURE__*/ Z(q)})){},e6=class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ListRootsResult`)({roots:/*#__PURE__*/ G(Lbe)})){},t6=class extends (/*#__PURE__*/ J(`roots/list`,{success:e6,error:P3,payload:/*#__PURE__*/ Qx(h3)})){};const Rbe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Z(U),type:/*#__PURE__*/ tS(`object`),properties:/*#__PURE__*/ Gx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/LegacyTitledEnum`)({type:/*#__PURE__*/ tS(`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__*/ GS(`@effect/ai/McpSchema/UntitledSingleSelectEnum`)({type:/*#__PURE__*/ tS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/TitledSingleSelectEnum`)({type:/*#__PURE__*/ tS(`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__*/ GS(`@effect/ai/McpSchema/UntitledMultiSelectEnum`)({type:/*#__PURE__*/ tS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(dS),maxItems:/*#__PURE__*/ Z(dS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ tS(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/TitledMultiSelectEnum`)({type:/*#__PURE__*/ tS(`array`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minItems:/*#__PURE__*/ Z(dS),maxItems:/*#__PURE__*/ Z(dS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(/*#__PURE__*/ W({const:U,title:U}))}),default:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))})){}])]),class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitationString`)({type:/*#__PURE__*/ tS(`string`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),minLength:/*#__PURE__*/ Z(dS),maxLength:/*#__PURE__*/ Z(dS),format:/*#__PURE__*/ Z(/*#__PURE__*/ Xx([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Z(U)})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitationNumber`)({type:/*#__PURE__*/ Xx([`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__*/ GS(`@effect/ai/McpSchema/ElicitationBoolean`)({type:/*#__PURE__*/ tS(`boolean`),title:/*#__PURE__*/ Z(U),description:/*#__PURE__*/ Z(U),default:/*#__PURE__*/ Z(Vx)})){}])),required:/*#__PURE__*/ Z(/*#__PURE__*/ G(U))}),zbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitRequestFormParams`)({...h3.fields,mode:/*#__PURE__*/ Z(/*#__PURE__*/ Fx(`form`)),message:U,requestedSchema:Rbe})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitRequestURLParams`)({...h3.fields,mode:/*#__PURE__*/ Fx(`url`),message:U,elicitationId:U,url:U})){}]),Bbe=/*#__PURE__*/ K([class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitAcceptResult`)({...g3.fields,action:/*#__PURE__*/ Fx(`accept`),content:/*#__PURE__*/ Z(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx,/*#__PURE__*/ G(U)])))})){},class extends (/*#__PURE__*/ GS(`@effect/ai/McpSchema/ElicitDeclineResult`)({...g3.fields,action:/*#__PURE__*/ Xx([`cancel`,`decline`])})){}]);var n6=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Bbe,error:P3,payload:zbe})){},Vbe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};n6.payloadSchema;var r6=class extends (/*#__PURE__*/ Bo(`McpReverseOperationUnsupported`)){},Hbe=class extends (/*#__PURE__*/ Bo(`McpReverseOperationError`)){},i6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpRequestContext`)){},a6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/McpServerClient`)){},o6=class extends (/*#__PURE__*/ ybe()(`effect/ai/McpSchema/McpServerClientMiddleware`)){},Ube=class extends (/*#__PURE__*/ hN(F3,I3,Z3,z3,R3,Y3,W3,Vbe)){},s6=class extends (/*#__PURE__*/ P()(`effect/ai/McpSchema/EnabledWhen`)){};const c6={Complete:e=>({_tag:`Complete`,value:e}),InputRequired:e=>({_tag:`InputRequired`,...e})};var Wbe=class extends (/*#__PURE__*/ Bo(`ResourceNotFound`)){},Gbe=class extends (/*#__PURE__*/ Bo(`ToolNotFound`)){},Kbe=class extends (/*#__PURE__*/ Bo(`InvalidToolInput`)){},qbe=class extends (/*#__PURE__*/ Bo(`InvalidToolContinuation`)){},Jbe=class extends (/*#__PURE__*/ Bo(`ToolExecutionError`)){},l6=class extends (/*#__PURE__*/ Bo(`UnsupportedByProtocol`)){},Ybe=class extends (/*#__PURE__*/ Bo(`PromptNotFound`)){};const u6=/*#__PURE__*/ Lo(),d6=/*#__PURE__*/ Lo(),Xbe=/*#__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)=>Qf(()=>{let r=e.get(t.name);return r===void 0||!r.isVisible(n.protocol)?new Gbe({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 Wbe({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 Ybe({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 M3({message:`Unknown completion reference or argument`});let a=yield*r(e,t),o=xte(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}))}}),Zbe=/*#__PURE__*/ new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}),f6={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}},p6=e=>{let t=e.startsWith(`=?base64?`),n=e.endsWith(`?=`);if(!t||!n)return/^[\t\x20-\x7e]*$/.test(e)?e:void 0;let r=bh(e.slice(9,-2));if(!Ca(r))try{return Zbe.decode(r.success)}catch{return}},m6=e=>({protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.initializePayload._meta}),h6=e=>({clientId:e.clientId,protocol:m6(e),requestContext:i6.of({clientId:e.clientId,protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata}),serverClient:e}),g6=e=>({clientId:e.clientId,protocol:{protocolVersion:e.protocolVersion,clientCapabilities:e.clientCapabilities,clientInfo:e.clientInfo,requestMetadata:e.requestMetadata},requestContext:e}),_6=(e,t)=>t._tag===`Complete`?F(t.value):z(new l6({protocolVersion:e,feature:`Client input`})),v6=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},y6=e=>sn(e)&&(e.type===`tool_use`||e.type===`tool_result`),b6=e=>sn(e)?e.tools!==void 0||e.toolChoice!==void 0?!0:Array.isArray(e.messages)?e.messages.some(e=>{if(!sn(e))return!1;let t=e.content;return Array.isArray(t)?t.some(y6):y6(t)}):!1:!1;var x6=class e extends (/*#__PURE__*/ Bo(`ProtocolError`)){static fromTool(t){let n=AO(t).pipe(MO(`ToolNotFound`,e=>`Tool '${e.name}' not found`),MO(`UnsupportedByProtocol`,e=>`${e.feature} is not supported by MCP ${e.protocolVersion}`),NO({InvalidToolInput:e=>e.message,InvalidToolContinuation:e=>e.message,ToolExecutionError:e=>e.message}),zO);return new e({code:t._tag===`ToolExecutionError`?D3:E3,message:n})}static fromFeature(t){if(N(t,`_tag`)){if(t._tag===`PromptNotFound`&&N(t,`name`)&&Jt(t.name))return new e({code:E3,message:`Prompt '${t.name}' not found`});if(t._tag===`ResourceNotFound`&&N(t,`uri`)&&Jt(t.uri))return new e({code:-32002,message:`Resource '${t.uri}' not found`})}let n=Qbe(t);return wa(n)?new e(n.success):new e({code:D3,message:`MCP feature handler failed`})}};const Qbe=/*#__PURE__*/ koe(/* @__PURE__ */ W({code:cS,message:U,data:/*#__PURE__*/ Mx(zx)})),$be=e=>ln(e,`McpReverseOperationUnsupported`),S6=e=>t=>$be(t)?t:new Hbe({operation:e,cause:t}),C6=(e,t,n)=>Dx(e)(n).pipe(B(Cx(t))),exe=(e,t,n)=>Dx(e)(n).pipe(B(Cx(t,{onExcessProperty:`error`}))),w6=/*#__PURE__*/ dm(function*(e,t){return d6.$match(t,{Cancelled:e=>({tag:F3._tag,payload:F3.payloadSchema.make({_meta:e.metadata,requestId:e.requestId,reason:e.reason})}),Progress:t=>({tag:I3._tag,payload:I3.payloadSchema.make({_meta:t.metadata,progressToken:t.progressToken,progress:t.progress,total:t.total,message:e.supportsProgressMessage?t.message:void 0})}),LoggingMessage:e=>({tag:Z3._tag,payload:Z3.payloadSchema.make({_meta:e.metadata,level:e.level,logger:e.logger,data:e.data})}),ResourceUpdated:e=>({tag:z3._tag,payload:z3.payloadSchema.make({_meta:e.metadata,uri:e.uri})}),ResourcesChanged:e=>({tag:R3._tag,payload:R3.payloadSchema.make({_meta:e.metadata})}),ToolsChanged:e=>({tag:Y3._tag,payload:Y3.payloadSchema.make({_meta:e.metadata})}),PromptsChanged:e=>({tag:W3._tag,payload:W3.payloadSchema.make({_meta:e.metadata})}),ElicitationComplete:()=>void 0})}),T6=e=>{switch(e._tag){case`ToolsChanged`:case`PromptsChanged`:case`ResourcesChanged`:case`ResourceUpdated`:return!0;default:return!1}},E6=e=>{let t=/* @__PURE__ */ new WeakMap,n=e=>{let n=t.get(e);if(n===void 0){let r=YS(e.payloadSchema);n={decode:Cx(r),encode:Ex(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`?rp(`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=>Fle(e.serverRequestRpcs,{spanPrefix:`McpServer/Client`}).pipe(V(n=>e.toReverseClient(t,n)));return{...e,payloadCodecs:n,installHandlers:r,makeReverseClient:i}},D6=e=>`@effect/mcp/${encodeURIComponent(e.protocolVersion)}/`,txe=/*#__PURE__*/ H(function*(e){if(e.length===0)return yield*new Cd(`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 Cd(`Duplicate MCP protocol version: ${e.protocolVersion}`);n.set(e.protocolVersion,e)}let r=t[0].clientRpcs.prefix(D6(t[0]));for(let e=1;e<t.length;e++)r=r.merge(t[e].clientRpcs.prefix(D6(t[e])));return{protocols:t,clientRpcs:r,select:e=>n.get(e)??t[0],protocolForInternalTag:e=>t.find(t=>e.startsWith(D6(t)))??t[0],routeClientRequest:(e,t)=>({...t,tag:`${D6(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(`${D6(t)}${i._tag}`),o=a.mapUnsafe.get(i.key);if(n===void 0||o===void 0)return yield*rp(`MCP handler registration invariant failed for ${t.protocolVersion}/${i._tag}`);e.set(n.key,o)}})})}}),O6=e=>({initializePayload:e.initializePayload,negotiatedProfile:e.negotiatedProfile,protocol:e.protocol,resourceSubscriptions:e.supportsResourceSubscriptions?/* @__PURE__ */ new Set:void 0,logLevel:{_tag:`Effect`,level:e.logLevel}}),nxe=()=>{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=O6(n);return e.set(t,r),r},registerConnection:(e,n)=>{let r=O6(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 x6({code:T3,message:`Resource subscriptions are not supported`})):I(()=>i.add(e)).pipe(fp)},unsubscribe:(e,t,n)=>{let i=r(t,n)?.resourceSubscriptions;return i===void 0?z(new x6({code:T3,message:`Resource subscriptions are not supported`})):I(()=>i.delete(e)).pipe(fp)},effectLogLevel:(e,t,n)=>{let i=r(e,t);return i?.logLevel._tag===`Mcp`?f6[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`?f6[n.level].order>=f6[e.level].order:TD(f6[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)}}},k6=`mcp-session-id`,A6=`mcp-protocol-version`,j6=`io.modelcontextprotocol/protocolVersion`,M6=`io.modelcontextprotocol/clientCapabilities`,N6=-32022,P6=e=>typeof e==`object`&&e?e:void 0,F6=e=>{let t=P6(e);return t!==void 0&&j6 in t?{present:!0,value:t[j6]}:{present:!1,value:void 0}},rxe=e=>F6(P6(P6(e)?.params)?._meta).present,ixe=e=>{switch(e){case`tools/call`:case`prompts/get`:return`name`;case`resources/read`:return`uri`;default:return}},I6=e=>({_tag:`Rejected`,status:400,error:{code:O3,message:e}}),L6=/*#__PURE__*/ hN(Cbe),R6=e=>({_tag:`Stateful`,transport:e});var z6=class extends (/*#__PURE__*/ P()(`effect/ai/McpRuntime/ServerRuntime`)){};const B6=(e,t)=>e.find(e=>e.runtime._tag===`Stateful`&&e.protocolVersion===t)??e.find(e=>e.runtime._tag===`Stateful`),axe=/*#__PURE__*/ H(function*(e){let t=e.find(e=>e.runtime._tag===`Stateful`)===void 0?void 0:nxe(),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 Cd(`MCP runtime supports at most one stateless protocol`);r=t.runtime,i=t}let a=yield*txe(e),o=/* @__PURE__ */ new Set,s=e=>({code:N6,message:`Unsupported protocol version '${e}'`,data:{supported:n,requested:e}}),c=(e,r)=>{let i=e[A6],a=e[k6],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 I6(`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[A6],a=P6(n),o=P6(P6(a?.params)?._meta),l=F6(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 I6(`MCP-Protocol-Version header is required`);if(!f&&(o===void 0||typeof l.value!=`string`))return{_tag:`Rejected`,status:400,error:{code:E3,message:`Required request metadata is missing`}};if((!f||l.present)&&l.value!==r)return I6(`MCP-Protocol-Version header does not match request metadata`);if(!f&&P6(o?.[M6])===void 0)return{_tag:`Rejected`,status:400,error:{code:E3,message:`${M6} 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 I6(`Mcp-Method header does not match request method`);let n=ixe(t);if(n!==void 0){let t=P6(a?.params)?.[n],r=e[`mcp-name`];if(typeof t!=`string`||r===void 0||p6(r)!==t)return I6(`Mcp-Name header does not match request parameters`)}return{_tag:`Accepted`,binding:void 0,protocol:i}}return c(e,d)};return z6.of({protocols:a.protocols,clientRpcs:a.clientRpcs,selectProtocol:a.select,protocolForInternalTag:a.protocolForInternalTag,routeClientRequest:a.routeClientRequest,prepareRequest:H(function*(e,n,o){let c=P6(o.payload)?._meta,l=F6(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=B6(a.protocols,e);if(t===void 0)return yield*new x6({code:N6,message:`initialize is not supported by the configured MCP protocols (requested '${e}')`});f=t}else f=o.tag===`ping`?B6(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*rp(`MCP stateless runtime invariant failed`);if(u!==void 0&&u!==f.protocolVersion)return yield*new x6(s(u));let p=yield*r.profileFromRequestMetadata(c),m={protocolVersion:p.protocolVersion,clientCapabilities:p.clientCapabilities,clientInfo:p.clientInfo,requestMetadata:p.requestMetadata},h=i6.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?sj({status:e}):fj({jsonrpc:`2.0`,id:n,error:t},{status:e})});if(Ca(r)){let t=e[A6];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 k3({message:`Parse error`}))}let a=r.success;if(Array.isArray(a)){if(a.length===0)return i(400,new A3({message:`Invalid Request`}));let t=l(e,a);return t._tag===`Rejected`||a.some(rxe)||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 A3({message:`Invalid Request`}),c);let v=N(a,`method`)&&a.method===`initialize`,y=e[k6]!==void 0;return v&&y?i(400,new A3({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 A3({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 j3({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=>Qf(()=>{let n=e[k6];if(n===void 0)return F(sj({status:400}));let r=c(e,!1);if(r._tag===`Rejected`)return F(sj({status:r.status}));let i=r.binding;return t.terminateSession(n),dp(qf(o,e=>e(i),{discard:!0}),sj({status:204}))}),onSessionTerminated:e=>Bp(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*rp(`MCP sessionful runtime invariant failed`);yield*o.install(n,L6,L6.of({ping:()=>F({})}));let r={initialize:H(function*(r,i,a){let o=yield*e.core.registrationPresence;return yield*ap(s=>{let c=ca(s.context,dM),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:Tbe.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),yM(c,(t,r)=>F(_j(r,{[k6]:e,[A6]:n.protocolVersion})))}else t.registerConnection(a,u);return F({capabilities:l,instructions:e.serverInfo.instructions,serverInfo:S3.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 ta(r)})})}),V6=e=>pf(z6)(axe(e)),H6=e=>Mx(e).pipe($x(Px(Nx(e)),{decode:nv(),encode:av(Hi(Ri))})),U6=q,oxe=/*#__PURE__*/ K([U,cS]),W6=/*#__PURE__*/ K([U,cS]),G6=/*#__PURE__*/ Xx([`user`,`assistant`]),K6=/*#__PURE__*/ Xx([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),q6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ H6(/*#__PURE__*/ Kx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ H6(W6)}),[q]))}),J6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ H6(U6)}),Y6=/*#__PURE__*/ W({_meta:/*#__PURE__*/ H6(U6)}),X6=/*#__PURE__*/ W({...q6.fields,cursor:/*#__PURE__*/ H6(U)}),Z6=/*#__PURE__*/ W({...Y6.fields,nextCursor:/*#__PURE__*/ H6(U)}),sxe=/*#__PURE__*/ W({extensions:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),QS)),experimental:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(U,U6)),roots:/*#__PURE__*/ H6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ H6(Vx)})),sampling:/*#__PURE__*/ H6(U6)}),cxe=/*#__PURE__*/ W({extensions:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(/*#__PURE__*/ Ix([U,`/`,U]),QS)),experimental:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(U,U6)),logging:/*#__PURE__*/ H6(U6),prompts:/*#__PURE__*/ H6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ H6(Vx)})),resources:/*#__PURE__*/ H6(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ H6(Vx),listChanged:/*#__PURE__*/ H6(Vx)})),tools:/*#__PURE__*/ H6(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ H6(Vx)}))}),Q6=/*#__PURE__*/ W({code:dS,message:U,data:/*#__PURE__*/ H6(Rx)}),$6=/*#__PURE__*/ W({audience:/*#__PURE__*/ H6(/*#__PURE__*/ G(G6)),priority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))}),lxe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ H6(U),text:U}),uxe=/*#__PURE__*/ W({uri:U,mimeType:/*#__PURE__*/ H6(U),blob:U}),dxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`text`),text:U,annotations:/*#__PURE__*/ H6($6)}),fxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`image`),data:U,mimeType:U,annotations:/*#__PURE__*/ H6($6)}),pxe=/*#__PURE__*/ W({uri:U,name:U,description:/*#__PURE__*/ H6(U),mimeType:/*#__PURE__*/ H6(U),size:/*#__PURE__*/ H6(cS),annotations:/*#__PURE__*/ H6($6)}),mxe=/*#__PURE__*/ W({uriTemplate:U,name:U,description:/*#__PURE__*/ H6(U),mimeType:/*#__PURE__*/ H6(U),annotations:/*#__PURE__*/ H6($6)}),e8=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ H6(U),required:/*#__PURE__*/ H6(Vx)}),hxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ H6(U),arguments:/*#__PURE__*/ H6(/*#__PURE__*/ G(e8))}),gxe=/*#__PURE__*/ W({name:U,description:/*#__PURE__*/ H6(U),inputSchema:/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ H6(/*#__PURE__*/ Gx(U,U6)),required:/*#__PURE__*/ H6(/*#__PURE__*/ G(U))})}),t8=/*#__PURE__*/ W({hints:/*#__PURE__*/ H6(/*#__PURE__*/ G(/* @__PURE__ */ W({name:/*#__PURE__*/ H6(U)}))),costPriority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),speedPriority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1}))),intelligencePriority:/*#__PURE__*/ H6(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))}),_xe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`ref/prompt`),name:U}),n8=/*#__PURE__*/ W({uri:U,name:/*#__PURE__*/ H6(U)});({...Y6.fields}),{...Z6.fields},{...Z6.fields},{...Y6.fields},{...Z6.fields},{...Y6.fields},{...Z6.fields},{...Y6.fields},{...Y6.fields};const vxe=/*#__PURE__*/ W({...Y6.fields,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U),total:/*#__PURE__*/ H6(cS),hasMore:/*#__PURE__*/ H6(Vx)})}),yxe=/*#__PURE__*/ W({...Y6.fields,roots:/*#__PURE__*/ G(n8)});var r8=class extends (/*#__PURE__*/ J(`ping`,{success:Y6,error:Q6,payload:/*#__PURE__*/ Qx(q6)})){};({...q6.fields}),{...q6.fields};var i8=class extends (/*#__PURE__*/ J(`logging/setLevel`,{success:Y6,error:Q6,payload:{...q6.fields,level:K6}})){};({...q6.fields}),{...q6.fields};var a8=class extends (/*#__PURE__*/ J(`resources/subscribe`,{success:Y6,error:Q6,payload:{...q6.fields,uri:U}})){},o8=class extends (/*#__PURE__*/ J(`resources/unsubscribe`,{success:Y6,error:Q6,payload:{...q6.fields,uri:U}})){};({...q6.fields}),{...q6.fields};var s8=class extends (/*#__PURE__*/ J(`roots/list`,{success:yxe,error:Q6,payload:/*#__PURE__*/ Qx(q6)})){},c8=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...J6.fields,requestId:oxe,reason:/*#__PURE__*/ H6(U)}})){};({...J6.fields});var l8=class extends (/*#__PURE__*/ J(`notifications/initialized`,{payload:/*#__PURE__*/ Qx(J6)})){},u8=class extends (/*#__PURE__*/ J(`notifications/roots/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){},d8=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...J6.fields,level:K6,logger:/*#__PURE__*/ H6(U),data:Rx}})){},f8=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...J6.fields,uri:U}})){},p8=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){},m8=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){},h8=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ Qx(J6)})){};const g8=H6,bxe=/*#__PURE__*/ W({...cxe.fields,completions:/*#__PURE__*/ g8(/*#__PURE__*/ W({}))}),xxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`audio`),data:U,mimeType:U,annotations:/*#__PURE__*/ g8($6)}),_8=/*#__PURE__*/ W({title:/*#__PURE__*/ g8(U),readOnlyHint:/*#__PURE__*/ g8(Vx),destructiveHint:/*#__PURE__*/ g8(Vx),idempotentHint:/*#__PURE__*/ g8(Vx),openWorldHint:/*#__PURE__*/ g8(Vx)});({...gxe.fields}),{...Y6.fields},{...Y6.fields},{...Z6.fields},{...Y6.fields},{...Y6.fields},{...q6.fields},{...q6.fields},{...q6.fields},{...q6.fields};var v8=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...J6.fields,progressToken:W6,progress:cS,total:/*#__PURE__*/ g8(cS),message:/*#__PURE__*/ g8(U)}})){};const y8=`2025-06-18`,b8=H6,x8=q,S8=/*#__PURE__*/ b8(x8),C8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ b8(U),version:U}),w8=/*#__PURE__*/ W({...sxe.fields,elicitation:/*#__PURE__*/ b8(/*#__PURE__*/ W({}))}),T8=/*#__PURE__*/ W({audience:/*#__PURE__*/ b8(/*#__PURE__*/ G(G6)),priority:/*#__PURE__*/ b8(/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})))}),E8=/*#__PURE__*/ W({...pxe.fields,title:/*#__PURE__*/ b8(U),annotations:/*#__PURE__*/ b8(T8),_meta:S8}),D8=/*#__PURE__*/ W({...mxe.fields,title:/*#__PURE__*/ b8(U),annotations:/*#__PURE__*/ b8(T8),_meta:S8}),O8=/*#__PURE__*/ K([/* @__PURE__ */ W({...lxe.fields,_meta:S8}),/* @__PURE__ */ W({...uxe.fields,_meta:S8})]),Sxe=/*#__PURE__*/ W({...e8.fields,title:/*#__PURE__*/ b8(U)}),k8=/*#__PURE__*/ W({...hxe.fields,title:/*#__PURE__*/ b8(U),arguments:/*#__PURE__*/ b8(/*#__PURE__*/ G(Sxe)),_meta:S8}),A8=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`resource`),resource:O8,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),Cxe=/*#__PURE__*/ W({...E8.fields,type:/*#__PURE__*/ Fx(`resource_link`)}),j8=/*#__PURE__*/ W({...dxe.fields,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),M8=/*#__PURE__*/ W({...fxe.fields,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),N8=/*#__PURE__*/ W({...xxe.fields,annotations:/*#__PURE__*/ b8(T8),_meta:S8}),P8=/*#__PURE__*/ K([j8,M8,N8,A8,Cxe]),F8=/*#__PURE__*/ K([j8,M8,N8]),wxe=/*#__PURE__*/ W({role:G6,content:P8}),Txe=/*#__PURE__*/ W({role:G6,content:F8}),Exe=/*#__PURE__*/ W({...bxe.fields}),I8=/*#__PURE__*/ W({...Y6.fields,protocolVersion:U,capabilities:Exe,serverInfo:C8,instructions:/*#__PURE__*/ b8(U)});var L8=class extends (/*#__PURE__*/ J(`initialize`,{success:I8,error:Q6,payload:{...q6.fields,protocolVersion:U,capabilities:w8,clientInfo:C8}})){};const R8=/*#__PURE__*/ Kx(/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,x8)),required:/*#__PURE__*/ b8(/*#__PURE__*/ G(U))}),[q]),z8=/*#__PURE__*/ W({name:U,title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),inputSchema:R8,outputSchema:/*#__PURE__*/ b8(R8),annotations:/*#__PURE__*/ b8(_8),_meta:S8}),B8=/*#__PURE__*/ W({...Y6.fields,content:/*#__PURE__*/ G(P8),structuredContent:/*#__PURE__*/ b8(x8),isError:/*#__PURE__*/ b8(Vx)}),Dxe=/*#__PURE__*/ W({...Y6.fields,role:G6,content:F8,model:U,stopReason:/*#__PURE__*/ b8(U)});var V8=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:Dxe,error:Q6,payload:{...q6.fields,messages:/*#__PURE__*/ G(Txe),modelPreferences:/*#__PURE__*/ b8(t8),systemPrompt:/*#__PURE__*/ b8(U),includeContext:/*#__PURE__*/ b8(/*#__PURE__*/ Xx([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ b8(cS),maxTokens:cS,stopSequences:/*#__PURE__*/ b8(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ b8(x8)}})){};const H8=/*#__PURE__*/ W({..._xe.fields,title:/*#__PURE__*/ b8(U)}),U8=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`ref/resource`),uri:U}),W8=vxe;var G8=class extends (/*#__PURE__*/ J(`completion/complete`,{success:W8,error:Q6,payload:{...q6.fields,ref:/*#__PURE__*/ K([H8,U8]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ b8(/*#__PURE__*/ W({arguments:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,U))}))}})){};const K8=/*#__PURE__*/ W({...Z6.fields,resources:/*#__PURE__*/ G(E8)}),q8=/*#__PURE__*/ W({...Z6.fields,resourceTemplates:/*#__PURE__*/ G(D8)}),J8=/*#__PURE__*/ W({...Y6.fields,contents:/*#__PURE__*/ G(O8)}),Y8=/*#__PURE__*/ W({...Z6.fields,prompts:/*#__PURE__*/ G(k8)}),X8=/*#__PURE__*/ W({...Y6.fields,description:/*#__PURE__*/ b8(U),messages:/*#__PURE__*/ G(wxe)}),Z8=/*#__PURE__*/ W({...Z6.fields,tools:/*#__PURE__*/ G(z8)});var Oxe=class extends (/*#__PURE__*/ J(`resources/list`,{success:K8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},kxe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:q8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},Q8=class extends (/*#__PURE__*/ J(`resources/read`,{success:J8,error:Q6,payload:{...q6.fields,uri:U}})){},Axe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:Y8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},jxe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:X8,error:Q6,payload:{...q6.fields,name:U,arguments:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,U))}})){},Mxe=class extends (/*#__PURE__*/ J(`tools/list`,{success:Z8,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},$8=class extends (/*#__PURE__*/ J(`tools/call`,{success:B8,error:Q6,payload:{...q6.fields,name:U,arguments:/*#__PURE__*/ b8(x8)}})){};const Nxe=/*#__PURE__*/ W({...Y6.fields,action:/*#__PURE__*/ Xx([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ b8(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx])))}),Pxe=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),minLength:/*#__PURE__*/ b8(dS),maxLength:/*#__PURE__*/ b8(dS),format:/*#__PURE__*/ b8(/*#__PURE__*/ Xx([`email`,`uri`,`date`,`date-time`]))}),/* @__PURE__ */ W({type:/*#__PURE__*/ Xx([`number`,`integer`]),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),minimum:/*#__PURE__*/ b8(cS),maximum:/*#__PURE__*/ b8(cS)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`boolean`),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),default:/*#__PURE__*/ b8(Vx)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ b8(U),description:/*#__PURE__*/ b8(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ b8(/*#__PURE__*/ G(U))})])),required:/*#__PURE__*/ b8(/*#__PURE__*/ G(U))});var e5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Nxe,error:Q6,payload:{...q6.fields,message:U,requestedSchema:Pxe}})){},Fxe=class extends (/*#__PURE__*/ hN(r8,L8,G8,i8,jxe,Axe,Oxe,kxe,Q8,a8,o8,$8,Mxe)){},t5=class extends (/*#__PURE__*/ hN(c8,v8,l8,u8)){},Ixe=class extends (/*#__PURE__*/ hN(r8,V8,s8,e5)){},Lxe=class extends (/*#__PURE__*/ hN(c8,v8,d8,f8,p8,m8,h8)){};const n5=/*#__PURE__*/ (/* @__PURE__ */ Fxe.omit(`ping`).middleware(o6).add(r8)).merge(t5),r5=/*#__PURE__*/ n5.omit(`ping`),Rxe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||sn(e.properties)&&Object.values(e.properties).every(sn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Jt);return t&&n},zxe=e=>({protocolVersion:y8,clientCapabilities:C3.make(e.capabilities),clientInfo:S3.make(e.clientInfo),requestMetadata:e._meta}),i5=(e,t)=>new r6({operation:e,protocolVersion:y8,reason:t}),a5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(i5(t,`Client did not advertise the ${n} capability`)),o5=/*#__PURE__*/ H(function*(e){return AO(e).pipe(jO({type:PO(`text`,`resource_link`)},e=>e),jO({type:PO(`image`,`audio`)},e=>({type:e.type,mimeType:e.mimeType,data:yh(e.data),annotations:e.annotations,_meta:e._meta})),jO({type:`resource`},e=>{let t=e.resource;return`text`in t?A8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):A8.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:yh(t.blob)},annotations:e.annotations,_meta:e._meta})}),zO)}),Bxe=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:yh(e.blob)},Vxe=e=>e===void 0||Hxe(e)?e:void 0,Hxe=e=>sn(e),Uxe=/*#__PURE__*/ E6({protocolVersion:y8,runtime:/*#__PURE__*/ R6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:n5,clientNotificationRpcs:t5,serverRequestRpcs:Ixe,serverNotificationRpcs:Lxe,handlerRpcs:r5,makeHandlers:(e,t)=>r5.of({initialize:(e,{client:n})=>t.initialize(y8,zxe(e),n.id).pipe(V(e=>I8.make({protocolVersion:y8,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(dp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(u6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(u6.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(u6.RootsChanged(),n.id,r),"resources/list":t=>a6.use(t=>e.resources.list(m6(t))).pipe(V(e=>K8.make({resources:e}))),"resources/templates/list":t=>a6.use(t=>e.resources.listTemplates(m6(t))).pipe(V(e=>q8.make({resourceTemplates:e}))),"resources/read":H(function*({uri:t}){let n=yield*a6,r=yield*e.resources.read(t,h6(n)).pipe(vp(x6.fromFeature));return J8.make({contents:r.contents.map(Bxe),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(dp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(dp({})),"prompts/list":t=>a6.use(t=>e.prompts.list(m6(t))).pipe(V(e=>Y8.make({prompts:e}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*a6,i=yield*e.prompts.get(n,t??{},h6(r)).pipe(vp(x6.fromFeature));if(i._tag===`InputRequired`)return yield*x6.fromFeature(new l6({protocolVersion:y8,feature:`prompt input requirements`}));let a=i.value,o=yield*qf(a.messages,e=>o5(e.content).pipe(V(t=>({role:e.role,content:t})),vp(x6.fromTool)));return X8.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*a6,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},h6(n)).pipe(vp(x6.fromFeature));return W8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*a6,n=yield*e.tools.list(m6(t));return Z8.make({tools:n.map(e=>z8.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:Rxe(e.outputSchema)?e.outputSchema:void 0,annotations:e.annotations===void 0?void 0:_8.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*a6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},h6(n)).pipe(B(e=>_6(y8,e)),vp(x6.fromTool)),i=yield*qf(v6(r),o5).pipe(vp(x6.fromTool)),a=Vxe(r.structuredContent);return B8.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*a5(e,`roots/list`,`roots`);let r=yield*C6(t6.payloadSchema,s8.payloadSchema,n).pipe(vp(()=>i5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(vp(S6(`roots/list`)));return new e6({roots:i})}),createMessage:H(function*(n){yield*a5(e,`sampling/createMessage`,`sampling`);let r=yield*exe($3.payloadSchema,V8.payloadSchema,n).pipe(vp(()=>i5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(vp(S6(`sampling/createMessage`)));return yield*C6(V8.successSchema,$3.successSchema,i).pipe(vp(()=>i5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*a5(e,`elicitation/create`,`elicitation`);let r=n.mode===`form`?boe(n,[`mode`]):n,i=yield*Cx(e5.payloadSchema,{onExcessProperty:`error`})(r).pipe(vp(()=>i5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(vp(S6(`elicitation/create`)));return yield*C6(e5.successSchema,n6.successSchema,a).pipe(vp(()=>i5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>w6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Cx(c8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),s5=`2025-11-25`,Q=H6,c5=q,l5=/*#__PURE__*/ Q(c5),u5=/*#__PURE__*/ W({src:U,mimeType:/*#__PURE__*/ Q(U),sizes:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),theme:/*#__PURE__*/ Q(/*#__PURE__*/ Xx([`light`,`dark`]))}),d5=/*#__PURE__*/ W({...C8.fields,description:/*#__PURE__*/ Q(U),websiteUrl:/*#__PURE__*/ Q(U),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),Wxe=/*#__PURE__*/ W({...w8.fields,sampling:/*#__PURE__*/ Q(/*#__PURE__*/ W({context:/*#__PURE__*/ Q(c5),tools:/*#__PURE__*/ Q(c5)})),elicitation:/*#__PURE__*/ Q(/*#__PURE__*/ W({form:/*#__PURE__*/ Q(c5),url:/*#__PURE__*/ Q(c5)}))}),f5=/*#__PURE__*/ W({...T8.fields,lastModified:/*#__PURE__*/ Q(U)}),p5=/*#__PURE__*/ W({...E8.fields,annotations:/*#__PURE__*/ Q(f5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),m5=/*#__PURE__*/ W({...D8.fields,annotations:/*#__PURE__*/ Q(f5),icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),h5=/*#__PURE__*/ W({...k8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),g5=/*#__PURE__*/ W({...j8.fields,annotations:/*#__PURE__*/ Q(f5)}),_5=/*#__PURE__*/ W({...M8.fields,annotations:/*#__PURE__*/ Q(f5)}),v5=/*#__PURE__*/ W({...N8.fields,annotations:/*#__PURE__*/ Q(f5)}),y5=/*#__PURE__*/ W({...A8.fields,annotations:/*#__PURE__*/ Q(f5)}),b5=/*#__PURE__*/ K([g5,_5,v5,/* @__PURE__ */ W({...p5.fields,type:/*#__PURE__*/ Fx(`resource_link`)}),y5]),Gxe=/*#__PURE__*/ W({role:G6,content:b5}),x5=/*#__PURE__*/ W({...z8.fields,icons:/*#__PURE__*/ Q(/*#__PURE__*/ G(u5))}),S5=/*#__PURE__*/ W({...B8.fields,content:/*#__PURE__*/ G(b5)});var Kxe=class extends (/*#__PURE__*/ J(`tools/call`,{success:S5,error:Q6,payload:$8.payloadSchema})){};const C5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`tool_use`),id:U,name:U,input:c5,_meta:l5}),w5=/*#__PURE__*/ K([g5,_5,v5,C5,/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(b5),structuredContent:/*#__PURE__*/ Q(c5),isError:/*#__PURE__*/ Q(Vx),_meta:l5})]),T5=/*#__PURE__*/ W({role:G6,content:/*#__PURE__*/ K([w5,/*#__PURE__*/ G(w5)]),_meta:l5}),E5=/*#__PURE__*/ W({mode:/*#__PURE__*/ Q(/*#__PURE__*/ Xx([`auto`,`required`,`none`]))}),qxe=/*#__PURE__*/ W({...Y6.fields,...T5.fields,model:U,stopReason:/*#__PURE__*/ Q(U)});var D5=class extends (/*#__PURE__*/ J(`sampling/createMessage`,{success:qxe,error:Q6,payload:{...V8.payloadSchema.fields,messages:/*#__PURE__*/ G(T5),maxTokens:dS,tools:/*#__PURE__*/ Q(/*#__PURE__*/ G(x5)),toolChoice:/*#__PURE__*/ Q(E5)}})){};const O5=/*#__PURE__*/ W({...n8.fields,_meta:l5}),Jxe=/*#__PURE__*/ W({...Y6.fields,roots:/*#__PURE__*/ G(O5)});var k5=class extends (/*#__PURE__*/ J(`roots/list`,{success:Jxe,error:Q6,payload:/*#__PURE__*/ Qx(q6)})){};const A5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minLength:/*#__PURE__*/ Q(dS),maxLength:/*#__PURE__*/ Q(dS),format:/*#__PURE__*/ Q(/*#__PURE__*/ Xx([`email`,`uri`,`date`,`date-time`])),default:/*#__PURE__*/ Q(U)}),j5=/*#__PURE__*/ W({type:/*#__PURE__*/ Xx([`number`,`integer`]),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minimum:/*#__PURE__*/ Q(cS),maximum:/*#__PURE__*/ Q(cS),default:/*#__PURE__*/ Q(cS)}),M5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`boolean`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),default:/*#__PURE__*/ Q(Vx)}),N5=/*#__PURE__*/ W({const:U,title:U}),P5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),default:/*#__PURE__*/ Q(U)}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),oneOf:/*#__PURE__*/ G(N5),default:/*#__PURE__*/ Q(U)})]),F5=/*#__PURE__*/ K([/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(dS),maxItems:/*#__PURE__*/ Q(dS),items:/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`string`),enum:/*#__PURE__*/ G(U)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`array`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),minItems:/*#__PURE__*/ Q(dS),maxItems:/*#__PURE__*/ Q(dS),items:/*#__PURE__*/ W({anyOf:/*#__PURE__*/ G(N5)}),default:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))})]),I5=/*#__PURE__*/ W({type:/*#__PURE__*/ Fx(`string`),title:/*#__PURE__*/ Q(U),description:/*#__PURE__*/ Q(U),enum:/*#__PURE__*/ G(U),enumNames:/*#__PURE__*/ Q(/*#__PURE__*/ G(U)),default:/*#__PURE__*/ Q(U)}),Yxe=/*#__PURE__*/ W({$schema:/*#__PURE__*/ Q(U),type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Gx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([I5,P5,F5]),A5,j5,M5])),required:/*#__PURE__*/ Q(/*#__PURE__*/ G(U))}),Xxe=/*#__PURE__*/ K([/* @__PURE__ */ W({...q6.fields,mode:/*#__PURE__*/ Q(/*#__PURE__*/ Fx(`form`)),message:U,requestedSchema:Yxe}),/* @__PURE__ */ W({...q6.fields,mode:/*#__PURE__*/ Fx(`url`),message:U,elicitationId:U,url:U})]),Zxe=/*#__PURE__*/ W({...Y6.fields,action:/*#__PURE__*/ Xx([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ Q(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx,/*#__PURE__*/ G(U)])))});var L5=class extends (/*#__PURE__*/ J(`elicitation/create`,{success:Zxe,error:Q6,payload:Xxe})){},Qxe=class extends (/*#__PURE__*/ J(`notifications/elicitation/complete`,{payload:{elicitationId:U}})){};const R5=/*#__PURE__*/ W({...I8.fields,serverInfo:d5});var $xe=class extends (/*#__PURE__*/ J(`initialize`,{success:R5,error:Q6,payload:{...L8.payloadSchema.fields,capabilities:Wxe,clientInfo:d5}})){};const z5=/*#__PURE__*/ W({...Z6.fields,resources:/*#__PURE__*/ G(p5)}),B5=/*#__PURE__*/ W({...Z6.fields,resourceTemplates:/*#__PURE__*/ G(m5)}),V5=/*#__PURE__*/ W({...Z6.fields,prompts:/*#__PURE__*/ G(h5)}),H5=/*#__PURE__*/ W({...X8.fields,messages:/*#__PURE__*/ G(Gxe)}),U5=/*#__PURE__*/ W({...Z6.fields,tools:/*#__PURE__*/ G(x5)});var eSe=class extends (/*#__PURE__*/ J(`resources/list`,{success:z5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},tSe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:B5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},nSe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:V5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},rSe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:H5,error:Q6,payload:{...q6.fields,name:U,arguments:/*#__PURE__*/ Q(/*#__PURE__*/ Gx(U,U))}})){},iSe=class extends (/*#__PURE__*/ J(`tools/list`,{success:U5,error:Q6,payload:/*#__PURE__*/ Qx(X6)})){},aSe=class extends (/*#__PURE__*/ hN(r8,$xe,G8,i8,rSe,nSe,eSe,tSe,Q8,a8,o8,Kxe,iSe)){},W5=class extends (/*#__PURE__*/ hN(c8,v8,l8,u8)){},oSe=class extends (/*#__PURE__*/ hN(r8,D5,k5,L5)){},sSe=class extends (/*#__PURE__*/ hN(c8,v8,d8,f8,p8,m8,h8,Qxe)){};const G5=/*#__PURE__*/ (/* @__PURE__ */ aSe.omit(`ping`).middleware(o6).add(r8)).merge(W5),K5=/*#__PURE__*/ G5.omit(`ping`),cSe=e=>{if(e?.type!==`object`)return!1;let t=e.properties===void 0||sn(e.properties)&&Object.values(e.properties).every(sn),n=e.required===void 0||Array.isArray(e.required)&&e.required.every(Jt);return t&&n},q5=(e,t)=>new r6({operation:e,protocolVersion:s5,reason:t}),J5=(e,t,n)=>Object.hasOwn(e.clientCapabilities,n)&&e.clientCapabilities[n]!==void 0?L:z(q5(t,`Client did not advertise the ${n} capability`)),lSe=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`)),uSe=(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},Y5=/*#__PURE__*/ H(function*(e){return AO(e).pipe(jO({type:PO(`text`,`resource_link`)},e=>e),jO({type:PO(`image`,`audio`)},e=>({type:e.type,mimeType:e.mimeType,data:yh(e.data),annotations:e.annotations,_meta:e._meta})),jO({type:`resource`},e=>{let t=e.resource;return`text`in t?y5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,text:t.text},annotations:e.annotations,_meta:e._meta}):y5.make({type:`resource`,resource:{uri:t.uri,mimeType:t.mimeType,_meta:t._meta,blob:yh(t.blob)},annotations:e.annotations,_meta:e._meta})}),zO)}),dSe=e=>e===void 0||fSe(e)?e:void 0,fSe=e=>sn(e),pSe=/*#__PURE__*/ E6({protocolVersion:s5,runtime:/*#__PURE__*/ R6({jsonRpc:{acceptsBatches:!1},http:{requiresVersionHeader:!0}}),clientRpcs:G5,clientNotificationRpcs:W5,serverRequestRpcs:oSe,serverNotificationRpcs:sSe,handlerRpcs:K5,makeHandlers:(e,t)=>K5.of({initialize:(e,{client:n})=>t.initialize(s5,{protocolVersion:s5,clientCapabilities:C3.make(e.capabilities),clientInfo:S3.make(e.clientInfo),requestMetadata:e._meta},n.id).pipe(V(e=>R5.make({protocolVersion:s5,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(dp({})),"notifications/cancelled":()=>L,"notifications/initialized":(e,{client:n,headers:r})=>t.clientNotification(u6.Initialized(),n.id,r),"notifications/progress":(e,{client:n,headers:r})=>t.clientNotification(u6.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(u6.RootsChanged(),n.id,r),"resources/list":()=>a6.use(t=>e.resources.list(m6(t))).pipe(V(e=>z5.make({resources:e.map(e=>p5.make(e))}))),"resources/templates/list":()=>a6.use(t=>e.resources.listTemplates(m6(t))).pipe(V(e=>B5.make({resourceTemplates:e.map(e=>m5.make(e))}))),"resources/read":H(function*({uri:t}){let n=yield*a6,r=yield*e.resources.read(t,h6(n)).pipe(vp(x6.fromFeature));return J8.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:yh(e.blob)}),_meta:r._meta})}),"resources/subscribe":({uri:e},{client:n,headers:r})=>t.subscribe(e,n.id,r).pipe(dp({})),"resources/unsubscribe":({uri:e},{client:n,headers:r})=>t.unsubscribe(e,n.id,r).pipe(dp({})),"prompts/list":()=>a6.use(t=>e.prompts.list(m6(t))).pipe(V(e=>V5.make({prompts:e.map(e=>h5.make(e))}))),"prompts/get":H(function*({arguments:t,name:n}){let r=yield*a6,i=yield*e.prompts.get(n,t??{},h6(r)).pipe(vp(x6.fromFeature));if(i._tag===`InputRequired`)return yield*x6.fromFeature(new l6({protocolVersion:s5,feature:`prompt input requirements`}));let a=i.value,o=yield*qf(a.messages,e=>Y5(e.content).pipe(V(t=>({role:e.role,content:t})),vp(x6.fromTool)));return H5.make({description:a.description,messages:o,_meta:a._meta})}),"completion/complete":H(function*(t){let n=yield*a6,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},h6(n)).pipe(vp(x6.fromFeature));return W8.make({completion:{values:Array.from(r.values),total:r.total,hasMore:r.hasMore},_meta:r.metadata})}),"tools/list":H(function*(){let t=yield*a6,n=yield*e.tools.list(m6(t));return U5.make({tools:n.map(e=>x5.make({name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:cSe(e.outputSchema)?e.outputSchema:void 0,icons:e.icons,annotations:e.annotations===void 0?void 0:_8.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*a6,r=yield*e.tools.call({...t,arguments:t.arguments??{}},h6(n)).pipe(B(e=>_6(s5,e)),mp([`InvalidToolInput`,`ToolExecutionError`],e=>F(J3.make({content:[B3.make({type:`text`,text:e.message})],isError:!0}))),vp(x6.fromTool)),i=yield*qf(v6(r),Y5).pipe(vp(x6.fromTool)),a=dSe(r.structuredContent);return S5.make({content:i,structuredContent:a,isError:r.isError,_meta:r._meta})})}),toReverseClient:(e,t)=>({listRoots:H(function*(n){yield*J5(e,`roots/list`,`roots`);let r=yield*C6(t6.payloadSchema,k5.payloadSchema,n).pipe(vp(()=>q5(`roots/list`,`Request is not representable by this protocol`))),{roots:i}=yield*t[`roots/list`](r).pipe(vp(S6(`roots/list`)));return new e6({roots:i})}),createMessage:H(function*(n){if(yield*J5(e,`sampling/createMessage`,`sampling`),b6(n)&&e.clientCapabilities.sampling?.tools==null)return yield*q5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`);if((n.includeContext===`thisServer`||n.includeContext===`allServers`)&&e.clientCapabilities.sampling?.context==null)return yield*q5(`sampling/createMessage`,`Client did not advertise the sampling.context capability`);let r=yield*C6($3.payloadSchema,D5.payloadSchema,n).pipe(vp(()=>q5(`sampling/createMessage`,`Request is not representable by this protocol`))),i=yield*t[`sampling/createMessage`](r).pipe(vp(S6(`sampling/createMessage`)));return lSe(i)&&e.clientCapabilities.sampling?.tools==null?yield*q5(`sampling/createMessage`,`Client did not advertise the sampling.tools capability`):yield*C6(D5.successSchema,$3.successSchema,i).pipe(vp(()=>q5(`sampling/createMessage`,`Response is not representable by the canonical model`)))}),elicit:H(function*(n){yield*J5(e,`elicitation/create`,`elicitation`);let r=n.mode===`url`?`url`:`form`;if(!uSe(e,r))return yield*q5(`elicitation/create`,`Client did not advertise the elicitation.${r} capability`);let i=yield*C6(n6.payloadSchema,L5.payloadSchema,n).pipe(vp(()=>q5(`elicitation/create`,`Request is not representable by this protocol`))),a=yield*t[`elicitation/create`](i).pipe(vp(S6(`elicitation/create`)));return yield*C6(L5.successSchema,n6.successSchema,a).pipe(vp(()=>q5(`elicitation/create`,`Response is not representable by the canonical model`)))})}),projectNotification:e=>e._tag===`ElicitationComplete`?F({tag:`notifications/elicitation/complete`,payload:{elicitationId:e.elicitationId}}):w6({supportsProgressMessage:!0},e),normalizeCancellation:e=>Cx(c8.payloadSchema)(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta})))}),X5=`2026-07-28`,$=H6,Z5=/*#__PURE__*/ $(q),Q5=/*#__PURE__*/ K([U,dS]),$5=Q5,e7=G6,t7=K6,n7=d5,mSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ Gx(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__*/ Gx(U,q))}),[q]),hSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({experimental:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,q)),logging:/*#__PURE__*/ $(q),completions:/*#__PURE__*/ $(q),prompts:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Vx)})),resources:/*#__PURE__*/ $(/*#__PURE__*/ W({subscribe:/*#__PURE__*/ $(Vx),listChanged:/*#__PURE__*/ $(Vx)})),tools:/*#__PURE__*/ $(/*#__PURE__*/ W({listChanged:/*#__PURE__*/ $(Vx)})),extensions:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,q))}),[q]),r7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({progressToken:/*#__PURE__*/ $($5),"io.modelcontextprotocol/protocolVersion":U,"io.modelcontextprotocol/clientInfo":/*#__PURE__*/ $(n7),"io.modelcontextprotocol/clientCapabilities":mSe,"io.modelcontextprotocol/logLevel":/*#__PURE__*/ $(t7)}),[q]),i7=/*#__PURE__*/ W({_meta:r7}),a7=/*#__PURE__*/ W({_meta:/*#__PURE__*/ $(/* @__PURE__ */ Kx(/*#__PURE__*/ W({"io.modelcontextprotocol/subscriptionId":/*#__PURE__*/ $(Q5)}),[q]))}),o7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":n7}),[q]),s7={_meta:o7,resultType:/*#__PURE__*/ Fx(`complete`)},c7=/*#__PURE__*/ W({code:dS,message:U,data:/*#__PURE__*/ $(QS)}),gSe=f5,l7=/*#__PURE__*/ W({...p5.fields,size:/*#__PURE__*/ $(dS),annotations:/*#__PURE__*/ $(gSe)}),u7=m5,_Se=O8,d7=g5,f7=_5,p7=v5,m7=/*#__PURE__*/ K([d7,f7,p7,/* @__PURE__ */ W({...l7.fields,type:/*#__PURE__*/ Fx(`resource_link`)}),y5]),h7=h5,vSe=/*#__PURE__*/ W({role:e7,content:m7}),ySe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ Fx(`object`)}),[q]),bSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({$schema:/*#__PURE__*/ $(U)}),[q]),xSe=_8,g7=/*#__PURE__*/ W({...x5.fields,inputSchema:ySe,outputSchema:/*#__PURE__*/ $(bSe),annotations:/*#__PURE__*/ $(xSe)}),_7=/*#__PURE__*/ K([d7,f7,p7,C5,/* @__PURE__ */ W({type:/*#__PURE__*/ Fx(`tool_result`),toolUseId:U,content:/*#__PURE__*/ G(m7),structuredContent:/*#__PURE__*/ $(QS),isError:/*#__PURE__*/ $(Vx),_meta:Z5})]),v7=/*#__PURE__*/ W({role:e7,content:/*#__PURE__*/ K([_7,/*#__PURE__*/ G(_7)]),_meta:Z5}),SSe=/*#__PURE__*/ Kx(/*#__PURE__*/ W({name:/*#__PURE__*/ $(U)}),[q]),y7=/*#__PURE__*/ cS.check(/*#__PURE__*/ uS({minimum:0,maximum:1})),CSe=/*#__PURE__*/ W({...t8.fields,hints:/*#__PURE__*/ $(/*#__PURE__*/ G(SSe)),costPriority:/*#__PURE__*/ $(y7),speedPriority:/*#__PURE__*/ $(y7),intelligencePriority:/*#__PURE__*/ $(y7)}),wSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Fx(`sampling/createMessage`),params:/*#__PURE__*/ W({messages:/*#__PURE__*/ G(v7),modelPreferences:/*#__PURE__*/ $(CSe),systemPrompt:/*#__PURE__*/ $(U),includeContext:/*#__PURE__*/ $(/*#__PURE__*/ Xx([`none`,`thisServer`,`allServers`])),temperature:/*#__PURE__*/ $(cS),maxTokens:dS,stopSequences:/*#__PURE__*/ $(/*#__PURE__*/ G(U)),metadata:/*#__PURE__*/ $(q),tools:/*#__PURE__*/ $(/*#__PURE__*/ G(g7)),toolChoice:/*#__PURE__*/ $(E5)})}),TSe=/*#__PURE__*/ W({...v7.fields,model:U,stopReason:/*#__PURE__*/ $(U)}),ESe=O5,DSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Fx(`roots/list`),params:/*#__PURE__*/ $(/*#__PURE__*/ W({_meta:Z5}))}),OSe=/*#__PURE__*/ W({roots:/*#__PURE__*/ G(ESe)}),kSe=/*#__PURE__*/ W({method:/*#__PURE__*/ Fx(`elicitation/create`),params:/* @__PURE__ */ K([/* @__PURE__ */ W({mode:/*#__PURE__*/ $(/*#__PURE__*/ Fx(`form`)),message:U,requestedSchema:/* @__PURE__ */ W({$schema:/*#__PURE__*/ $(U),type:/*#__PURE__*/ Fx(`object`),properties:/*#__PURE__*/ Gx(U,/* @__PURE__ */ K([/* @__PURE__ */ K([I5,P5,F5]),A5,j5,M5])),required:/*#__PURE__*/ $(/*#__PURE__*/ G(U))})}),/* @__PURE__ */ W({mode:/*#__PURE__*/ Fx(`url`),message:U,url:U})])}),ASe=/*#__PURE__*/ W({action:/*#__PURE__*/ Xx([`accept`,`decline`,`cancel`]),content:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,/*#__PURE__*/ K([U,cS,Vx,/*#__PURE__*/ G(U)])))}),jSe=/*#__PURE__*/ K([wSe,DSe,kSe]),MSe=/*#__PURE__*/ K([TSe,OSe,ASe]),b7=/*#__PURE__*/ Gx(U,jSe),NSe=/*#__PURE__*/ Gx(U,MSe),x7={_meta:o7,resultType:/*#__PURE__*/ Fx(`input_required`)},S7=/*#__PURE__*/ K([/*#__PURE__*/ Kx(/*#__PURE__*/ W({...x7,inputRequests:b7,requestState:/*#__PURE__*/ $(U)}),[q]),/*#__PURE__*/ Kx(/*#__PURE__*/ W({...x7,inputRequests:/*#__PURE__*/ $(b7),requestState:U}),[q])]),C7={...i7.fields,inputResponses:/*#__PURE__*/ $(NSe),requestState:/*#__PURE__*/ $(U)},w7={...s7,ttlMs:/*#__PURE__*/ dS.check(/*#__PURE__*/ Goe(0)),cacheScope:/*#__PURE__*/ Xx([`public`,`private`])},T7={...i7.fields,cursor:/*#__PURE__*/ $(U)},E7={...s7,nextCursor:/*#__PURE__*/ $(U)},D7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...w7,supportedVersions:/*#__PURE__*/ G(U),capabilities:hSe,instructions:/*#__PURE__*/ $(U)}),[q]);var PSe=class extends (/*#__PURE__*/ J(`server/discover`,{success:D7,error:c7,payload:i7})){};const O7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,resources:/*#__PURE__*/ G(l7)}),[q]);var FSe=class extends (/*#__PURE__*/ J(`resources/list`,{success:O7,error:c7,payload:T7})){};const k7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,resourceTemplates:/*#__PURE__*/ G(u7)}),[q]);var ISe=class extends (/*#__PURE__*/ J(`resources/templates/list`,{success:k7,error:c7,payload:T7})){};const A7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...w7,contents:/*#__PURE__*/ G(_Se)}),[q]);var LSe=class extends (/*#__PURE__*/ J(`resources/read`,{success:/*#__PURE__*/ K([A7,S7]),error:c7,payload:{...C7,uri:U}})){};const j7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,prompts:/*#__PURE__*/ G(h7)}),[q]);var RSe=class extends (/*#__PURE__*/ J(`prompts/list`,{success:j7,error:c7,payload:T7})){};const M7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...s7,description:/*#__PURE__*/ $(U),messages:/*#__PURE__*/ G(vSe)}),[q]);var zSe=class extends (/*#__PURE__*/ J(`prompts/get`,{success:/*#__PURE__*/ K([M7,S7]),error:c7,payload:{...C7,name:U,arguments:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,U))}})){};const N7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...E7,...w7,tools:/*#__PURE__*/ G(g7)}),[q]);var BSe=class extends (/*#__PURE__*/ J(`tools/list`,{success:N7,error:c7,payload:T7})){};const P7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...s7,content:/*#__PURE__*/ G(m7),structuredContent:/*#__PURE__*/ $(QS),isError:/*#__PURE__*/ $(Vx)}),[q]);var VSe=class extends (/*#__PURE__*/ J(`tools/call`,{success:/*#__PURE__*/ K([P7,S7]),error:c7,payload:{...C7,name:U,arguments:/*#__PURE__*/ $(q)}})){};const HSe=H8,USe=U8,F7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({...s7,completion:/*#__PURE__*/ W({values:/*#__PURE__*/ G(U).check(/*#__PURE__*/ mS(100)),total:/*#__PURE__*/ $(dS),hasMore:/*#__PURE__*/ $(Vx)})}),[q]);var WSe=class extends (/*#__PURE__*/ J(`completion/complete`,{success:F7,error:c7,payload:{...i7.fields,ref:/*#__PURE__*/ K([HSe,USe]),argument:/*#__PURE__*/ W({name:U,value:U}),context:/*#__PURE__*/ $(/*#__PURE__*/ W({arguments:/*#__PURE__*/ $(/*#__PURE__*/ Gx(U,U))}))}})){};const I7=/*#__PURE__*/ W({toolsListChanged:/*#__PURE__*/ $(Vx),promptsListChanged:/*#__PURE__*/ $(Vx),resourcesListChanged:/*#__PURE__*/ $(Vx),resourceSubscriptions:/*#__PURE__*/ $(/*#__PURE__*/ G(U))}),L7=/*#__PURE__*/ Kx(/*#__PURE__*/ W({_meta:/* @__PURE__ */ Kx(/*#__PURE__*/ W({"io.modelcontextprotocol/serverInfo":n7,"io.modelcontextprotocol/subscriptionId":Q5}),[q]),resultType:/*#__PURE__*/ Fx(`complete`)}),[q]);var GSe=class extends (/*#__PURE__*/ J(`subscriptions/listen`,{success:L7,error:c7,payload:{...i7.fields,notifications:I7}})){},R7=class extends (/*#__PURE__*/ J(`notifications/cancelled`,{payload:{...a7.fields,requestId:Q5,reason:/*#__PURE__*/ $(U)}})){},KSe=class extends (/*#__PURE__*/ J(`notifications/progress`,{payload:{...a7.fields,progressToken:$5,progress:cS,total:/*#__PURE__*/ $(cS),message:/*#__PURE__*/ $(U)}})){},qSe=class extends (/*#__PURE__*/ J(`notifications/message`,{payload:{...a7.fields,level:t7,logger:/*#__PURE__*/ $(U),data:QS}})){},z7=class extends (/*#__PURE__*/ J(`notifications/resources/updated`,{payload:{...a7.fields,uri:U}})){},B7=class extends (/*#__PURE__*/ J(`notifications/resources/list_changed`,{payload:/*#__PURE__*/ Qx(a7)})){},V7=class extends (/*#__PURE__*/ J(`notifications/tools/list_changed`,{payload:/*#__PURE__*/ Qx(a7)})){},H7=class extends (/*#__PURE__*/ J(`notifications/prompts/list_changed`,{payload:/*#__PURE__*/ Qx(a7)})){},U7=class extends (/*#__PURE__*/ J(`notifications/subscriptions/acknowledged`,{payload:{...a7.fields,notifications:I7}})){},W7=class extends (/*#__PURE__*/ hN(PSe,WSe,zSe,RSe,FSe,ISe,LSe,GSe,VSe,BSe)){},G7=class extends (/*#__PURE__*/ hN(R7)){},JSe=class extends (/*#__PURE__*/ W7.merge(G7)){},YSe=class extends (/*#__PURE__*/ hN()){},XSe=class extends (/*#__PURE__*/ hN(R7,KSe,qSe,z7,B7,V7,H7,U7)){};const ZSe=/*#__PURE__*/ Gx(U,q),QSe=/*#__PURE__*/ Cx(r7),$Se=/*#__PURE__*/ Cx(R7.payloadSchema),eCe=/*#__PURE__*/ Sx(QS),K7=/*#__PURE__*/ Dx(n7),q7=e=>{let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t},tCe=(e,t)=>{if(rn(t))return e===void 0;if(e===void 0)return!1;let n=p6(e);return n!==void 0&&AO(t).pipe(jO(FO,e=>n===e),jO(LO,e=>n===String(e)),jO(IO,e=>Number.isSafeInteger(e)&&n.trim().length>0&&Number(n)===e),RO(()=>!1))},nCe=/*#__PURE__*/ H(function*(e){let t=yield*QSe(e);return{protocolVersion:X5,clientCapabilities:t[`io.modelcontextprotocol/clientCapabilities`],clientInfo:t[`io.modelcontextprotocol/clientInfo`],requestMetadata:t}}),J7=(e,t)=>{let n=e._meta;return{...sn(n)?n:{},"io.modelcontextprotocol/serverInfo":t}},Y7=(e,t)=>q7({_meta:{"io.modelcontextprotocol/serverInfo":t},resultType:`input_required`,inputRequests:e.inputRequests,requestState:e.requestState}),X7=/*#__PURE__*/ Cx(/*#__PURE__*/ K([P7,S7])),Z7=/*#__PURE__*/ H(function*(e,t){let n=yield*K7(t);return e._tag===`Complete`?yield*X7({...q7(e.value),_meta:J7(e.value,n),resultType:`complete`}):yield*X7(Y7(e,n))}),rCe=(e,t)=>{let n={};for(let r of Object.values(e??{}))AO(r).pipe(jO({method:`roots/list`},()=>{t.roots===void 0&&(n.roots={})}),jO({method:`sampling/createMessage`},e=>{let r=n.sampling??{};b6(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)}),jO({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]={})}),zO);return n},Q7=e=>q7({uri:e.uri,mimeType:e.mimeType,_meta:e._meta,...`text`in e?{text:e.text}:{blob:yh(e.blob)}}),$7=/*#__PURE__*/ kO().pipe(/*#__PURE__*/ jO({type:/*#__PURE__*/ PO(`text`,`resource_link`)},e=>e),/*#__PURE__*/ jO({type:/*#__PURE__*/ PO(`image`,`audio`)},e=>q7({type:e.type,mimeType:e.mimeType,data:yh(e.data),annotations:e.annotations,_meta:e._meta})),/*#__PURE__*/ jO({type:`resource`},e=>q7({type:`resource`,resource:Q7(e.resource),annotations:e.annotations,_meta:e._meta})),zO),iCe=e=>l7.make(e),aCe=e=>u7.make(e),oCe=e=>C6(Abe,h7,e),sCe=e=>C6(q3,g7,e),e9={ttlMs:0,cacheScope:`private`},t9=/*#__PURE__*/ H(function*(e,t){let n=yield*K7(t);return{...q7(e),_meta:J7(e,n),resultType:`complete`}}),cCe=/*#__PURE__*/ kO().pipe(/*#__PURE__*/ MO(`ResourceNotFound`,e=>new x6({code:-32602,message:`Resource '${e.uri}' not found`,data:{uri:e.uri}})),/*#__PURE__*/ MO(`ToolNotFound`,`InvalidToolInput`,`InvalidToolContinuation`,`ToolExecutionError`,`UnsupportedByProtocol`,x6.fromTool),/*#__PURE__*/ RO(x6.fromFeature)),n9=e=>{let t=cCe(e);return c7.make({code:t.code,message:t.message,...eCe(t.data)?{data:t.data}:{}})},r9=/*#__PURE__*/ H(function*(e,t){let n=yield*Fp(dM);return Ni(n)&&yM(n.value,(t,n)=>F(tce(n,e))),yield*t}),lCe=e=>$Se(e).pipe(V(e=>({requestId:e.requestId,reason:e.reason,metadata:e._meta}))),i9=e=>new r6({operation:e,protocolVersion:X5,reason:`MCP 2026-07-28 carries server input requests in multi round-trip results`}),a9=/* @__PURE__ */ E6({protocolVersion:X5,runtime:{_tag:`Stateless`,transport:{jsonRpc:{acceptsBatches:!1},http:{}},profileFromRequestMetadata:nCe},clientRpcs:JSe,clientNotificationRpcs:G7,serverRequestRpcs:YSe,serverNotificationRpcs:XSe,handlerRpcs:/* @__PURE__ */ W7.merge(G7),makeHandlers:(e,t,n)=>{let r=Cx(ZSe),i=Cx(D7),a=Cx(O7),o=Cx(k7),s=Cx(A7),c=Cx(j7),l=Cx(M7),u=Cx(K([M7,S7])),d=Cx(F7),f=Cx(N7),p=n.sendNotification,m=p!==void 0,h=n.serverInfo.extensions===void 0?void 0:hte(n.serverInfo.extensions,e=>sn(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}}),_=i6.useSync(g6),v=H(function*(e){let t=yield*i6,n=e.inputResponses===void 0?void 0:yield*r(e.inputResponses).pipe(yp);return g6(i6.of({...t,inputResponses:n,requestState:e.requestState}))}),y=H(function*(e,t){let n=rCe(e.inputRequests,t);if(Object.keys(n).length!==0)return yield*r9(400,new x6({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 x6({code:-32601,message:`Method not found: subscriptions/listen`});let i=yield*n.registrationPresence,a=yield*Zd(yield*Rp),o=n.getListChangeRevision?.()??0,s=yield*Jd(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*Rd();yield*R(function*(){for(;;){let e=yield*AC(s);if(e.listChangeRevision!==void 0&&e.listChangeRevision<=o||e.targetClientId!==void 0&&e.targetClientId!==t.id)continue;let n=e.notification,r=AO(n).pipe(NO({ToolsChanged:()=>c.toolsListChanged===!0?V7:void 0,PromptsChanged:()=>c.promptsListChanged===!0?H7:void 0,ResourcesChanged:()=>c.resourcesListChanged===!0?B7:void 0,ResourceUpdated:e=>u.has(e.uri)?z7:void 0}),zO);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*QC(d,i)))break}}).pipe(wre(a),sp(Qf(()=>n.markSubscriptionCancelled?.(t.id,r)??L)),sp(Ud(f,void 0)),im),yield*p(X5,t.id,{tag:U7._tag,payload:U7.payloadSchema.make({_meta:l,notifications:c})});let m=Qp(dw(d).pipe(B(e=>p(X5,t.id,e))));yield*cie(m,zd(f)),yield*n.terminateSubscription?.(`2026-07-28`,t.id,r,`Pending notification limit exceeded`)??L;let h=yield*K7(n.serverInfo);return L7.make({_meta:{...l,"io.modelcontextprotocol/serverInfo":h},resultType:`complete`})},vp(n9)),"server/discover":H(function*(e){let t=yield*g,r=yield*t9({...e9,supportedVersions:Array.from(t.supportedVersions),capabilities:t.capabilities,instructions:n.serverInfo.instructions},n.serverInfo);return yield*i(r)},vp(n9)),"resources/list":H(function*(t){let r=yield*_,i=yield*e.resources.list(r.protocol),o=yield*t9({...e9,resources:i.map(iCe)},n.serverInfo);return yield*a(o)},vp(n9)),"resources/templates/list":H(function*(t){let r=yield*_,i=yield*e.resources.listTemplates(r.protocol),a=yield*t9({...e9,resourceTemplates:i.map(aCe)},n.serverInfo);return yield*o(a)},vp(n9)),"resources/read":H(function*(t){let r=yield*v(t),i=yield*e.resources.read(t.uri,r),a=i.contents.map(Q7),o=yield*t9({...e9,contents:a,_meta:i._meta},n.serverInfo);return yield*s(o)},vp(n9)),"prompts/list":H(function*(t){if(!(yield*n.registrationPresence).prompts)return yield*r9(404,new x6({code:T3,message:`Method not found`}));let r=yield*_,i=yield*e.prompts.list(r.protocol),a=yield*qf(i,oCe),o=yield*t9({...e9,prompts:a},n.serverInfo);return yield*c(o)},vp(n9)),"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*K7(n.serverInfo);return yield*u(Y7(i,e))}let a=i.value,o=a.messages.map(e=>({role:e.role,content:$7(e.content)})),s=yield*t9({description:a.description,messages:o,_meta:a._meta},n.serverInfo);return yield*l(s)},vp(n9)),"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*t9({completion:q7({values:Array.from(i.values),total:i.total,hasMore:i.hasMore}),_meta:i.metadata},n.serverInfo);return yield*d(a)},vp(n9)),"tools/list":H(function*(t){let r=yield*_,i=yield*e.tools.list(r.protocol),a=yield*qf(i,sCe),o=yield*t9({...e9,tools:a},n.serverInfo);return yield*f(o)},vp(n9)),"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*Fp(dM);if(i!==void 0&&Ni(a)){let e=[{schema:i.inputSchema,argument:t.arguments,path:``}];for(;e.length>0;){let{schema:t,argument:n,path:r}=e.pop();if(!sn(t))continue;let i=t[`x-mcp-header`];if(typeof i==`string`){let e=`mcp-param-${i.toLowerCase()}`;if(!tCe(a.value.headers[e],n))return yield*r9(400,new x6({code:O3,message:`${e} does not match argument '${r}'`}))}if(sn(t.properties))for(let[i,a]of Object.entries(t.properties))e.push({schema:a,argument:sn(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(mp([`ToolExecutionError`,`InvalidToolInput`],e=>F(c6.Complete(J3.make({content:[B3.make({type:`text`,text:e.message})],isError:!0})))));if(o._tag===`InputRequired`)return yield*y(o,r.protocol.clientCapabilities),yield*Z7(o,n.serverInfo);let s=o.value,c=s.content.map($7);return yield*Z7(c6.Complete({content:c,structuredContent:s.structuredContent,isError:s.isError,_meta:s._meta}),n.serverInfo)},vp(n9)),"notifications/cancelled":H(function*(e){return yield*L})}},toReverseClient:()=>({listRoots:()=>z(i9(`roots/list`)),createMessage:()=>z(i9(`sampling/createMessage`)),elicit:()=>z(i9(`elicitation/create`))}),projectNotification:e=>T6(e)?F(void 0):w6({supportsProgressMessage:!0},e),normalizeCancellation:lCe}),uCe=pSe,dCe=Uxe,o9=/*#__PURE__*/ new WeakMap,s9=/*#__PURE__*/ _a(`effect/ai/McpServer/RequestNotificationQueue`,{defaultValue:()=>void 0}),c9=e=>e._tag===`Progress`||e._tag===`LoggingMessage`,fCe=/*#__PURE__*/ Ube.omit(`notifications/elicitation/complete`),l9=/*#__PURE__*/ Sx(X3),pCe=e=>{switch(e.tag){case`notifications/cancelled`:return d6.Cancelled({requestId:e.payload.requestId,reason:e.payload.reason,metadata:e.payload._meta});case`notifications/progress`:return d6.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 d6.LoggingMessage({level:e.payload.level,logger:e.payload.logger,data:e.payload.data,metadata:e.payload._meta});case`notifications/resources/updated`:return d6.ResourceUpdated({uri:e.payload.uri,metadata:e.payload._meta});case`notifications/resources/list_changed`:return d6.ResourcesChanged({metadata:e.payload?._meta});case`notifications/tools/list_changed`:return d6.ToolsChanged({metadata:e.payload?._meta});case`notifications/prompts/list_changed`:return d6.PromptsChanged({metadata:e.payload?._meta});default:return}},u9=(e,t)=>{let n=Lp(e,i6,t.requestContext),r=t.requestContext.requestMetadata,i=N(r,`io.modelcontextprotocol/logLevel`)?r[`io.modelcontextprotocol/logLevel`]:void 0;return l9(i)&&(n=Lp(n,Gd,f6[i].effect)),t.serverClient===void 0?n:Lp(n,a6,t.serverClient)};var d9=class e extends (/*#__PURE__*/ P()(`effect/ai/McpServer`)){static make=/*#__PURE__*/ R(function*(){let t=yield*Xbe,n=Pa(),r=[],i=[],a=[],o=yield*YC(),s={consumers:0,listChangeRevision:0,requestEndpoints:0},c=()=>s.consumers===0&&s.requestEndpoints>0,l=/* @__PURE__ */ new Map,u=(yield*Eo).makeDispatcher(),d=yield*rN(fCe,{spanPrefix:`McpServer/Notifications`,onFromClient:e=>Rd().pipe(B(t=>ap(n=>{let r=e.message;if(r._tag!==`Request`)return L;let i=pCe(r);if(i===void 0)return L;let a={notification:i,delivered:t,requestContext:ca(n.context,i6),requestHeaders:ca(n.context,dM)?.headers},f=Qf(()=>d.write({clientId:0,requestId:r.id,_tag:`Exit`,exit:Md})),p=da(n.context,s9);if(p!==void 0&&a.requestContext!==void 0&&c9(i))return $C(p,a),sp(zd(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),$C(o,a)},0)):t.listChangeRevision=e}else m=!0,$C(o,a);return m&&a.requestContext!==void 0&&s.consumers>0?sp(zd(t),f):f})))}),f=e.of({notifications:d.client,notifyElicitationComplete:({clientId:e,elicitationId:t})=>c()?L:Rd().pipe(B(n=>QC(o,{notification:d6.ElicitationComplete({elicitationId:t}),targetClientId:e,delivered:n}).pipe(sp(Qf(()=>s.consumers>0?zd(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=ca(e.annotations,s6);yield*t.tools.register({descriptor:new q3({...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)=>u9(e.handle(t.arguments),n).pipe(rie({InternalError:t=>z(new Jbe({name:e.tool.name,message:t.message})),InvalidParams:t=>z(new(n.requestContext.requestState===void 0&&n.requestContext.inputResponses===void 0?Kbe:qbe)({name:e.tool.name,message:t.message}))}),V(e=>ln(e,`InputRequired`)?c6.InputRequired(e):c6.Complete(e)))}),yield*d.client[`notifications/tools/list_changed`]({})}),callTool:e=>R(function*(){let n=yield*a6,r=yield*t.tools.call(e,h6(n)).pipe(vp(e=>new M3({message:e._tag===`ToolNotFound`?`Tool '${e.name}' not found`:e.message})));return r._tag===`InputRequired`?yield*new M3({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=ca(e.annotations,s6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},read:t=>u9(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=xCe();c.add(a,!0),yield*t.resources.registerTemplate({descriptor:o,isVisible:t=>{let n=ca(e,s6);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)=>u9(r(e,Array.from(t)),n)});for(let[e,r]of Object.entries(n))yield*t.completions.register(`resource/${o.uriTemplate}/${e}`,(e,t)=>u9(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*a6;return yield*t.resources.read(e,h6(n)).pipe(mp(`ResourceNotFound`,e=>z(new M3({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=ca(e.annotations,s6);return n===void 0||n({protocolVersion:t.protocolVersion,capabilities:t.clientCapabilities,clientInfo:t.clientInfo})},get:(t,n)=>u9(e.handle(t),n).pipe(V(e=>ln(e,`InputRequired`)?c6.InputRequired(e):c6.Complete(e)))});for(let[n,r]of Object.entries(e.completions))yield*t.completions.register(`prompt/${e.prompt.name}/${n}`,(e,t)=>u9(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*a6,i=yield*t.prompts.get(n,e??{},h6(r)).pipe(mp(`PromptNotFound`,()=>new M3({message:`Prompt '${n}' not found`})));return i._tag===`Complete`?i.value:yield*new M3({message:`Client input is not supported by this MCP protocol`})}),completion:H(function*(e){let n=yield*a6,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},h6(n));return{_meta:i.metadata,completion:{values:i.values,total:i.total,hasMore:i.hasMore}}})});return o9.set(f,{core:t,notifications:o,notificationDelivery:s}),f});static layer=/*#__PURE__*/ pf(e)(e.make)};const f9=`mcp-session-id`,p9=/*#__PURE__*/ new WeakMap,m9=/*#__PURE__*/ new WeakMap,h9=e=>`${typeof e}:${e}`;var g9=class extends Fo{};const _9=/*#__PURE__*/ H(function*(e,t,n,r){let i=yield*fN,a=yield*d9,o=yield*Gd,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*TC(),h=(e,n,r)=>Qf(()=>{let a=t.selectProtocol(e),o=a.serverNotificationRpcs.requests.get(r.tag);return o===void 0?rp(`MCP protocol ${e} does not define server notification ${r.tag}`):a.payloadCodecs(o).encode(r.payload).pipe(yp,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=h9(t),i=n?.get(r);return i!==void 0&&(n.set(r,{...i,cancelled:!0}),!0)},_=(e,t,n,r)=>Qf(()=>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}=o9.get(a),S=r?.handlers??(yield*t.installHandlers({core:y,subscribeServerNotifications:OC(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*tE({lookup:H(function*(e){let n=t.selectProtocol(e.profile.protocolVersion),r,a=yield*aN.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=h9(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(Up(()=>I(()=>p(t,e))))}return r._tag===`Interrupt`?(p(h9(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(Lp(aN,a)),write:r}}),idleTimeToLive:1e4}),C=o6.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=nC(),t=ca(e.context,dM);return t&&yM(t,()=>F(sj({status:r[f9]===void 0?400:404}))),rp(/* @__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(!SCe(d.protocolVersion)||d.protocolVersion===`2026-07-28`)return rp(`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=i6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,requestMetadata:l._meta});return Lp(Lp(Lp(e,a6,a6.of({clientId:n.id,protocolVersion:f.protocolVersion,clientCapabilities:f.clientCapabilities,clientInfo:f.clientInfo,initializePayload:l,requestMetadata:sn(i)&&sn(i._meta)?i._meta:void 0,getClient:nE(ee,new g9({clientId:n.id,profile:f})).pipe(V(({client:e})=>e))})),i6,p),Gd,t.effectLogLevel(n.id,r,o))}),te=fN.of({...i,send:(e,t)=>{if(t._tag===`Exit`){let r=l.get(e),a=h9(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--,p9.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 N3({message:`Internal error`})}]}})}return i.send(e,t)},run:e=>(v=e,i.run((n,r)=>{let i=nC(),a=r,o=s?ca(i.context,dM):void 0;switch(o!==void 0&&a._tag!==`Eof`&&yM(o,(e,t)=>F(t.status===200&&t.body._tag===`Uint8Array`&&t.body.contentLength===0?sj({headers:xg(t.headers,`content-type`),status:202}):t)),a._tag){case`Request`:{if(o!==void 0&&a.isNotification!==!0){let e=m9.get(o)??{expected:0};e.expected++,m9.set(o,e)}let r=s?ua(nC().context,dM).headers:gg(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(h9(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*Xd(ua(i.context,Kd),I(()=>d(n))));let h=u.binding,_=u.protocol;if(c.set(n,{protocol:_,profile:u.profile??m?.profile,sessionHeaders:s&&r[f9]!==void 0?gg({[f9]:r[f9]}):m?.sessionHeaders}),a.tag===`invalid/json-rpc-batch`)return yield*f(n,a.id,new A3({message:`JSON-RPC batches are not supported`}));o!==void 0&&h!==void 0&&yM(o,(e,i)=>F(t.resolveRequest(n,r)===void 0?sj({status:404}):hj(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&&yM(o,()=>F(sj({status:r[f9]===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=h9(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:JM(a.id),client:new UM(n),headers:r}):L;return yield*u.requestContext===void 0?c:Lp(c,i6,u.requestContext)}).pipe(Cp)}if(!y||b)return a.isNotification?void 0:yield*f(n,a.id,new j3({message:`Method not found: ${a.tag}`}));let x=yield*lp(_.payloadCodecs(y).decode(a.payload));if(Ca(x))return yield*a.isNotification?L:f(n,a.id,new M3({message:`Invalid method parameters`}));if(a.isNotification!==!0){let e=l.get(n)??/* @__PURE__ */ new Map;e.set(h9(a.id),{requestId:JM(a.id),prepared:u,cancelled:!1,httpPost:o===void 0?void 0:m9.get(o)}),l.set(n,e)}let ee=e(n,v);return yield*u.requestContext===void 0?ee:Lp(ee,i6,u.requestContext)}).pipe(pp(e=>a.isNotification?L:f(n,a.id,ln(e,`ProtocolError`)?x6.fromFeature(e):new M3({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`?h9(a.requestId):void 0,r=s?t.resolveRequest(n,ua(nC().context,dM).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 nE(ee,new g9({clientId:o,profile:f})).pipe(B(({write:e})=>e(a)),zp)}}}))});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 Kf(t,{discard:!0})})),r===void 0&&(yield*Bp(I(()=>{b.consumers++}),()=>I(()=>{b.consumers--})));let w=/* @__PURE__ */ new Map;return yield*dw(r?.notifications??x).pipe(B(H(function*(e){let{delivered:n,listChangeRevision:r,notification:i,targetClientId:a,requestContext:l,requestHeaders:u}=e;T6(i)&&(yield*DC(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=c9(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=w.get(e),p=e===(a??l?.clientId);g||=p;let m=p?n:Ld();w.set(e,m);let _=R(function*(){s!==void 0&&(yield*zd(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||!l9(n)||X3.literals.indexOf(i.level)<X3.literals.indexOf(n))return}else if(!t.canDeliver(e,(l?.clientId===e?u:void 0)??c.get(e)?.sessionHeaders??hg,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(Cp,Hp(I(()=>{Wd(m,Md),w.get(e)===m&&w.delete(e)})));h.push(_)}g||(yield*Ud(n,void 0)),yield*Kf(h,{concurrency:`unbounded`,discard:!0}).pipe(im({startImmediately:!0}))})),Cp,Qp,im),yield*Vle(t.clientRpcs,{spanPrefix:`McpServer`,disableFatalDefects:!0}).pipe(Lp(fN,te),Lp(o6,C),Mp(S))},zp),mCe=(e,t)=>gf(R(function*(){let n=yield*z6;yield*im(_9(e,n,t))})).pipe(wf(d9.layer)),hCe=e=>{let t=V6(e.protocols);return mCe(e,`http`).pipe(Cf(_Ce(e)),Cf(t),Cf(Ale()))},gCe=e=>gf(R(function*(){let t=yield*z6,n=t.protocols.find(e=>e.runtime._tag===`Stateful`);if(n!==void 0)return yield*new Cd(`McpServer.layerHttpRequestScoped does not support the sessionful MCP protocol ${n.protocolVersion}`);let r=yield*d9,{core:i,notificationDelivery:a}=o9.get(r),o=yield*t.installHandlers({core:i,subscribeServerNotifications:rp(`Subscriptions are disabled for request-scoped MCP servers`),getListChangeRevision:()=>a.listChangeRevision,defaultLogLevel:yield*Gd,serverInfo:e});yield*Bp(I(()=>{a.requestEndpoints++}),()=>I(()=>{a.requestEndpoints--})),yield*v9(e,R(function*(){let{httpEffect:n,protocol:i}=yield*pN().pipe(Lp(QM,y9)),a=yield*YC();return yield*_9(e,t,`http`,{notifications:a,handlers:o}).pipe(Lp(fN,i),Lp(d9,r),im({startImmediately:!0})),yield*Lp(n,s9,a)}))})).pipe(wf(d9.layer),Cf(V6(e.protocols))),_Ce=e=>pf(fN)(R(function*(){let{httpEffect:t,protocol:n}=yield*pN().pipe(Lp(QM,y9));return yield*v9(e,t),n})),v9=/*#__PURE__*/ H(function*(e,t){let n=yield*z6,r=yield*xM,i=e.allowSessionTermination===!0&&n.protocols.some(e=>e.runtime._tag===`Stateful`),a=F(sj({status:403})),o=t=>n=>x9(n,e.allowedOrigins)?t(n):a,s=F(sj({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(!x9(r,e.allowedOrigins))return F(sj({status:403}));if(S9(r.headers[`content-type`])[0]!==`application/json`)return F(sj({status:415}));let i=S9(r.headers.accept);return!i.includes(`application/json`)||!i.includes(`text/event-stream`)?F(sj({status:406})):R(function*(){let e=yield*lp(B(r.text,wx(CS))),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?bCe(e,i.isSubscription):e};return i.acknowledge?yield*hp(V(t,a),()=>F(sj({status:202}))):yield*B(t,e=>e.body._tag!==`Uint8Array`||e.body.body.length>0?F(a(e)):m9.get(r)?.expected===0?F(mj(TE,{contentType:`text/event-stream`})):rp(/* @__PURE__ */ Error(`MCP request ended without writing its response`)))})})}),y9=/*#__PURE__*/ (()=>{let e=/*#__PURE__*/ yCe();return QM.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}}}})})(),vCe=/*#__PURE__*/ Sx(/*#__PURE__*/ nS(`Cause`,{data:/*#__PURE__*/ Foe([/*#__PURE__*/ nS(`Fail`,{error:/*#__PURE__*/ joe(P3)})])})),b9=e=>Array.isArray(e)?e.map(b9):!sn(e)||!N(e,`error`)?e:vCe(e.error)?{...e,error:e.error.data[0].error}:e;function yCe(e){let t=$M(e);return QM.of({...t,makeUnsafe:()=>{let e=t.makeUnsafe(),n=/* @__PURE__ */ new Set;return{decode:e.decode,encode:t=>{if(sn(t)){let e=p9.get(t);e!==void 0&&(p9.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=>!(sn(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(b9(i))}}}})}const bCe=(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:xg(e.headers,`content-type`),cookies:e.cookies,contentType:`text/event-stream`};if(e.body._tag===`Stream`){let r=e.body.stream.pipe(ME(i));if(!t)return mj(r,a);let o=bE(`15 seconds`).pipe(VE(1),ME(()=>n.encode(`: keepalive
|
|
536
|
+
|
|
537
|
+
`)));return mj(LE(r,o,{haltStrategy:`left`}),a)}return e.body._tag===`Uint8Array`?lj(i(e.body.body),a):hj(e,`content-type`,`text/event-stream`)},x9=(e,t)=>{let n=e.headers.origin;return n===void 0||(t??[]).includes(n)},S9=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()]}),xCe=()=>{let e=ej({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(t,n)=>{e.on(`GET`,`/${t}`,n)},find:t=>e.find(`GET`,`/${t}`)}},SCe=e=>e===`2024-11-05`||e===`2025-03-26`||e===`2025-06-18`||e===`2025-11-25`||e===`2026-07-28`,C9=a9,CCe=[a9,uCe,dCe],wCe=Sx(qI),TCe=Sx(G(qI)),w9=e=>YI(MI(e)),T9=e=>{let t=MI(e),n=YI(t);if(n!==void 0)return{kind:n,many:!1};if(!Cv(t)||t.encoding!==void 0)return;let[r,...i]=new Set([...t.elements,...t.rest].map(w9));return r===void 0||i.length>0?void 0:{kind:r,many:!0}},ECe=e=>{let t=e.context?.isOptional===!0,n=MI(e);if(t&&Tv(n)&&n.types.length===2){let[e,...t]=n.types.filter(e=>!Fie(e)),r=e===void 0||t.length>0?void 0:w9(e);return r===void 0?void 0:{kind:r,many:!1}}let r=T9(n);return r===void 0||t&&r.many?void 0:r},E9=e=>{let t=MI(e.ast),n=T9(t);if(n!==void 0)return{fields:[{name:void 0,...n}],rest:void 0};if(!wv(t)||t.encoding!==void 0)return{fields:[],rest:e};let r=t.propertySignatures.flatMap(({name:e,type:t})=>{let n=ECe(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:Ax(new $v(a,t.indexSignatures,s))}},DCe=e=>[...yv(e)?e.typeParameters:[],...Cv(e)?[...e.elements,...e.rest]:[],...wv(e)?[...e.propertySignatures,...e.indexSignatures].map(({type:e})=>e):[],...Tv(e)?e.types:[],...Ev(e)?[e.thunk()]:[],...(e.encoding??[]).map(({to:e})=>e)],OCe=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),JI(e))return!0;n.push(...DCe(e))}return!1},kCe=(e,{rest:t})=>[e.input,...e.error,...t===void 0?[]:[t]].some(({ast:e})=>OCe(e)),ACe=(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?TCe(i)?i:[]:wCe(i)?[i]:[]).map(t=>({kind:n,field:e,value:t}))}),jCe=Sx(G3),D9=(e,t)=>{let n=JS(e,{onExcessProperty:t?`error`:`ignore`}),[r,i]=Jt(n.schema.$ref)?Rb(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}},MCe=e=>{let t=e.map(([e])=>e).filter(e=>!jCe(D9(YS(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])=>kCe(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(`, `)}`)},NCe=e=>new J3({isError:!0,content:[{type:`text`,text:e}]}),O9=e=>e===void 0?[]:[{type:`text`,text:JSON.stringify(e)}],PCe=({kind:e,field:t,value:n})=>({type:e,data:n.data,mimeType:n.mimeType,...t===void 0?{}:{_meta:{"effect-actions/field":t}}}),FCe=(e,t)=>V(Cx(G3)(D9(YS(e.input),!0)),n=>new q3({name:e.name,description:e.description,inputSchema:n,outputSchema:t,annotations:{...e.mcp.title===void 0?{}:{title:e.mcp.title},..._be(e)},_meta:e.mcp._meta===void 0?void 0:{...e.mcp._meta}})),ICe=H(function*(e,t){let n=yield*d9,r=yield*WI(e),i=yield*Ap(),a=e=>hm(e).pipe(sp(cO(e)),dp(NCe(`Tool execution failed due to an internal server error.`))),o=e=>vd(e)?a(e):tp(e);for(let[e,a]of r){let r=E9(e.success),s=r.fields.length===0?void 0:r,c=s===void 0?YS(e.success):s.rest===void 0?void 0:YS(s.rest),l=c===void 0?void 0:yield*Cx(K3)(D9(c,!1)).pipe(yp),u=yield*FCe(e,l).pipe(yp),d=Cx(YS(e.input),GI),f=e=>{let t=Ex(YS(e));return e=>yp(t(e))},p=f(e.success),m=f(K(FI(e))),h=t===void 0||e.caller===xI?a:e=>DB(pfe(t,a(e))),g=new Set(s?.fields.map(({name:e})=>e)),_=(e,t)=>{if(s===void 0)return new J3({isError:!1,structuredContent:e,content:O9(e)});let n=ACe(s,t).map(PCe);if(c===void 0)return new J3({isError:!1,content:n});let r=on(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!g.has(e))):e;return new J3({isError:!1,structuredContent:r,content:[...O9(r),...n]})};yield*n.addTool({tool:u,annotations:ia(),handle:t=>mie({tool:e.name,parameters:t??{}}).pipe(sp(()=>d(t??{})),vp(({message:t})=>new M3({message:new vbe({toolName:e.name,description:t}).message})),B(e=>h(e).pipe(kp({onFailure:e=>V(m(e),e=>new J3({isError:!0,content:O9(e)})),onSuccess:e=>V(p(e),t=>_(t,e))}))),hp(o),Ip(e=>ha(i,e)))})}}),LCe=(e,t,n=ff,r)=>{jI(`MCP tool`,e.flatMap(e=>e.actions));let i=e.flatMap(e=>e.actions.map(e=>[e,E9(e.success)]));MCe(i);let a=new Set(i.map(([{name:e}])=>e)),o=R(function*(){let t=(yield*d9).tools.flatMap(({tool:e})=>a.has(e.name)?[e.name]:[]);if(t.length>0)return yield*rp(/* @__PURE__ */ Error(`Duplicate MCP tool: ${t.join(`, `)}, claimed by an action and a native feature`));yield*ICe(e,r)});return gf(o).pipe(Cf(n),Cf(t),Mre,UI(e))},RCe=/* @__PURE__ */ new Set([`server/discover`,`tools/list`,`notifications/cancelled`]),zCe=e=>{let t=new Set(e.filter(({caller:e})=>e===xI).flatMap(({name:e})=>[e,`=?base64?${yh(e)}?=`]));return e=>{if(t.size===0||e[`mcp-protocol-version`]!==C9.protocolVersion)return!0;let n=e[`mcp-method`];if(n===void 0)return!0;if(RCe.has(n))return!1;if(n!==`tools/call`)return!0;let r=e[`mcp-name`];return r===void 0||!t.has(r)}},BCe=e=>Dp(e.json,{onFailure:()=>!0,onSuccess:t=>!N(t,`method`)||t.method===e.headers[`mcp-method`]});function VCe(e,{actions:t,features:n,path:r=`/mcp`,authentication:i,requestScoped:a,allowSubscriptions:o=n!==void 0,...s}){let c=HI(BI(e),t),l=c.flatMap(e=>e.actions);SI(l,i);let u=LCe(c,a===!0?gCe({...s,path:r,protocols:[C9]}):hCe({...s,path:r,protocols:CCe,allowSessionTermination:!0,allowSubscriptions:o}),n,i);if(i===void 0)return u;let d=zCe(l),f=AM(V(eL(i),e=>t=>B(dM,n=>n.method!==`POST`||d(n.headers)?e.http(t,!1):B(BCe(n),n=>e.http(t,n)))));return u.pipe(Cf(f.layer))}var HCe=`0.26.3`;const UCe=(e,t)=>Xf(()=>IW({key:e,data:t})),WCe=(e,t)=>Xf(()=>LW({key:e,data:t})),GCe=async(e,t)=>(await Promise.all([WG(e.authCookies.sessionToken.name,t,e.secret),WG(e.authCookies.dontRememberToken.name,`true`,e.secret)])).map(e=>e.split(`;`)[0]).join(`; `),KCe=(e,t)=>dm(`OwnerAccount.providerSession`)(function*(n){let r=new Date((yield*Ef)+6e4),i=yield*Bp(V4(()=>e.internalAdapter.createSession(n,!0,{expiresAt:r},!0)),t=>Yf(()=>e.internalAdapter.deleteSession(t.token))),a=yield*V4(()=>GCe(e,i.token));return new Headers({origin:t,cookie:a})}),qCe=$V(W({id:U}));var k9=class e extends P()(`clankerauth/OwnerAccount`){static layer=pf(e,R(function*(){let{sql:e}=yield*rH,{auth:t,context:n}=yield*r3,{baseURL:r}=yield*Y4,i=yield*Pw(1),a=KCe(n,r),o=dm(`OwnerAccount.find`)(function*(){let t=yield*e`SELECT id FROM user LIMIT 1`;if(t.length)return(yield*qCe(t[0])).id});return{find:o,create:dm(`OwnerAccount.create`)(function*(e){if(yield*o())return yield*z($B.of());let{headers:n}=yield*V4(()=>t.api.signUpEmail({body:{name:`Owner`,email:e.email.trim(),password:e.password},returnHeaders:!0}),{refused:z4,conflict:$B.of});return n.getSetCookie()},e=>i.withPermit(e)),caller:(e,t,n)=>({userId:e,email:t,writable:n,providerHeaders:a(e)})}}))},A9=class extends P()(`clankerauth/ResponseCookies`){};const JCe=V(k9,e=>({setupStatus:()=>e.find().pipe(V(e=>({required:!e}))),setupOwner:dm(`Administration.setup`)(function*(t){let n=yield*e.create(t);return yield*(yield*A9).add(n),{created:!0}})}));var j9=class extends Bo(`Unauthorized`){constructor(e={}){super({message:e.message??`Authentication required`}),Object.defineProperty(this,"cause",{value:e.cause})}},M9=class extends qS()(`ProviderUnavailable`,{operation:U},{httpApiStatus:503}){constructor(e){super({operation:e.operation}),Object.defineProperty(this,"cause",{value:e.cause})}},N9=class extends Bo(`InsufficientScope`){},YCe=class extends qS()(`ConfigurationError`,{message:U}){};const P9=po(1),F9=(e,t)=>jp(n=>Ose(e).execute(t).pipe(Lp(MN,{...ca(n,MN),redirect:`manual`}),vp(e=>new M9({operation:`http.request`,cause:e})),lie(e=>e.status<300||e.status>=400,e=>new M9({operation:`http.redirect`,cause:{status:e.status}})))),XCe=W({keys:G(W({kty:U,crv:Mx(U),x:Mx(U),kid:Mx(U),alg:Mx(U),use:Mx(U),key_ops:Mx(G(U))}))}),ZCe=W({sub:_S,client_id:_S,scope:U,iat:cS,exp:cS}),QCe=W({list:U}),$Ce=Ude.pipe(Wx({exp:cS})),ewe=()=>({jwks:/* @__PURE__ */ new Map,keyLists:/* @__PURE__ */ new Map}),I9=e=>new j9({cause:e}),twe=po(1),L9=fo(5),R9=fo(3),z9=e=>t=>wp(t,{duration:R9,orElse:()=>z(new M9({operation:e}))}),B9=dm(`Verifier.make`)(function*(e){let t=yield*LA,n=JSON.stringify([e.issuer,e.resource]),r=yield*ip({try:()=>({jwks:new URL(`${e.issuer}/jwks`).href,keyList:new URL(`/api/keyList`,e.issuer).href}),catch:()=>new YCe({message:`Invalid issuer URL`})}),i=dm(`Verifier.jwks`)(function*(){let e=yield*F9(t,rse(r.jwks));return e.status===200?(yield*OA(XCe)(e).pipe(vp(e=>new M9({operation:`jwks.decode`,cause:e})))).keys.map(({key_ops:e,...t})=>e?{...t,key_ops:[...e]}:t):yield*new M9({operation:`jwks.fetch`,cause:{status:e.status}})},zp),a=R(function*(){let t=e.store.jwks.get(e.issuer),n=yield*Ef;if(t!==void 0){let e=`keys`in t?twe:L9;if(n-t.readAt<_o(e))return`keys`in t?t.keys:yield*new M9({operation:t.failure})}let r=yield*lp(i()),a=yield*Ef;return wa(r)?(e.store.jwks.set(e.issuer,{readAt:a,keys:r.success}),r.success):((e.store.jwks.get(e.issuer)?.readAt??-1/0)>=n||e.store.jwks.set(e.issuer,{readAt:a,failure:r.failure.operation}),yield*r.failure)}),o=dm(`Verifier.signingKey`)(function*(e,t){let n={keys:[...yield*t]};return yield*Xf({try:()=>uI(n)({alg:`EdDSA`,kid:e}),catch:I9})}),s=dm(`Verifier.signed`)(function*(t,n,r=a){let i=yield*ip({try:()=>hI(t),catch:I9});if(i.alg!==`EdDSA`||i.kid===void 0)return yield*I9();let s=yield*o(i.kid,r),c=yield*Ef,{payload:l}=yield*Xf({try:()=>tI(t,s,{issuer:e.issuer,audience:e.resource,algorithms:[`EdDSA`],typ:n,currentDate:new Date(c)}),catch:I9});return l}),c=dm(`Verifier.jwt`)(function*(e){let t=yield*s(e,`at+jwt`);if(t.cnf!==void 0)return yield*I9();let n=yield*Cx(ZCe)(t).pipe(vp(I9));return{subject:n.sub,scopes:n.scope.split(` `).filter(Boolean),actor:{kind:`client`,clientId:n.client_id},expiresAt:n.exp*1e3}}),l=dm(`Verifier.keyList`)(function*(){let n=SA(r.keyList).pipe(EA({resource:e.resource})),i=R(function*(){let e=yield*F9(t,n);return e.status===200?yield*OA(QCe)(e).pipe(vp(e=>new M9({operation:`key-list.decode`,cause:e}))):yield*new M9({operation:`key-list.fetch`,cause:{status:e.status}})}),o=yield*im(a.pipe(z9(`jwks.timeout`))),{list:c}=yield*i.pipe(z9(`key-list.timeout`)),l=e=>new M9({operation:`key-list.verify`,cause:e}),u=yield*s(c,_I,eC(o)).pipe(mp(`Unauthorized`,e=>z(l(e)))),d=yield*Cx($Ce)(u).pipe(vp(l));return{readAt:yield*Ef,expiresAt:d.exp*1e3,entries:new Map(d.keys.map(e=>[e.id,e.sealed]))}},zp),u=R(function*(){let t=e.store.keyLists.get(n),r=yield*Ef;if(t!==void 0&&r-t.readAt<_o(L9))return t.failure===void 0?void 0:yield*new M9({operation:t.failure});let i=yield*lp(l()),a=yield*Ef,o=e.store.keyLists.get(n),s=o?.failure!==void 0;if(wa(i)){e.store.keyLists.set(n,{readAt:a,failure:void 0,held:i.success}),s&&(yield*gm(`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*mm(`clankerauth key list reads are failing; a held list decides until it expires`,{operation:c})),yield*i.failure}),d=R(function*(){let t=yield*lp(u),r=e.store.keyLists.get(n)?.held;return r!==void 0&&r.expiresAt>(yield*Ef)?r:yield*Ca(t)?t.failure:new M9({operation:`key-list.expired`})}),f=dm(`Verifier.apiKey`)(function*(t){let r=n=>Xf({try:()=>Kde(t,e.resource,n.entries),catch:I9}),i=yield*Ef,a=e.store.keyLists.get(n)?.held,o=a!==void 0&&i-a.readAt<_o(P9)&&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*Ef)?yield*I9():{subject:s.ownerId,scopes:s.scopes,actor:{kind:`key`,keyId:s.keyId},expiresAt:s.expiresAt??void 0}});return{verifyToken:dm(`Verifier.verifyToken`)(function*(t){let n=yield*t.startsWith(`clankerauth_`)?e.apiKeys===!1?z(I9()):f(t):c(t),r=e.requiredScopes?.find(e=>!n.scopes.includes(e));return r===void 0?n:yield*new N9({scope:r,actor:n.actor})})}}),nwe=dm(`AdministrationResource.make`)(function*(){let{auth:e}=yield*r3,{baseURL:t}=yield*Y4,n=`${t}/api/auth`,r=sV(t);return{protectedResource:{resource:r,authorizationServers:[n],scopesSupported:[cV.read,cV.write,...Z4],scopesRequired:[cV.read,cV.write]},verifier:yield*B9({issuer:n,resource:r,store:ewe(),apiKeys:!1}).pipe(Mp(NN.pipe(Cf(uf(jN,(t,n)=>{let r=new Request(t,n);return r.headers.set(P4,`127.0.0.1`),e.handler(r)})))))}});ZI(`whoami`,{description:`The verified subject, issuer and scopes behind this request's credential.`,readOnly:!0,caller:class extends P()(`@clankerauth/CurrentPrincipal`){},success:W({subject:_S,issuer:_S,scopes:G(U)})});const V9=(e,t)=>{let n=`Requires ${e}.`;return t.kind===`client`?new DI({message:n,scopes:[e]}):new DI({message:n})},rwe=(e,t)=>t===void 0||e.scopes.includes(t)?void 0:V9(t,e.actor),H9=e=>e instanceof j9?new TI({message:e.message}):e instanceof N9?V9(e.scope,e.actor):e,U9=(e,t)=>vp(e.verifyToken(lg(t)),H9);dm(`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=>wp(e,{duration:`5 seconds`,orElse:()=>z(new M9({operation:`verify.timeout`}))}),l={verifyToken:e=>c(s.verifyToken(e))},u=dm(`Resource.principal`)(function*(e,t){let n=AB(e);if(Mi(n))return yield*new TI({message:`A bearer token is required.`});let r=yield*U9(l,n.value),i=rwe(r,t);return i===void 0?r:yield*i}),d=dm(`Resource.admit`)(function*(t,n){let r=yield*lp(u(t,n));if(wa(r))return{ok:!0,principal:r.success};let i=rce(LB(r.failure,{authentication:e,protectedResource:o,authorization:t}));return{ok:!1,refusal:{status:i.status,headers:Object.fromEntries(i.headers),body:yield*Yf(()=>i.text())}}});return{resource:i,issuer:r.issuer,protectedResource:o,verifier:l,admit:d,watch:(e,t)=>Qp(R(function*(){let n=yield*u(e,t),r=yield*Ef,i=Math.max(0,(n.expiresAt??1/0)-r);return n.actor.kind===`key`?yield*Tp(Math.min(i,_o(P9))):(yield*Tp(i),yield*H9(new j9))}))}});const iwe=e=>KB(e,V(r3,e=>()=>R(function*(){let t=yield*dM,n=new Headers(t.headers),r=yield*V4(()=>e.auth.api.getSession({headers:n}),{unavailable:B4});return r?{providerHeaders:F(n),userId:r.user.id,email:r.user.email,writable:!0}:yield*new TI({message:`Owner session required`})}))),awe=$V(W({id:U,email:U})),owe=e=>KB(oV,R(function*(){let{sql:t}=yield*rH,n=yield*k9,r=()=>new TI({message:`Owner authorization required`});return i=>R(function*(){let a=yield*U9(e.verifier,i).pipe(mp(`ProviderUnavailable`,()=>z(new JB({message:`Request could not be completed`}))));if(a.actor.kind!==`client`)return yield*r();let o=a.scopes.includes(cV.write);if(!o&&!a.scopes.includes(cV.read))return yield*new DI({message:`Insufficient scope`,scopes:[cV.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*awe(s[0]);return n.caller(c.id,c.email,o)})}),{protectedResource:e.protectedResource}),swe=e=>e.readOnly?L:B(rV,({writable:e})=>e?L:z(new DI({message:`This action requires the ${cV.write} scope`,scopes:[cV.write]}))),cwe=AM()(e=>R(function*(){let t=[],n=yield*Lp(e,A9,{add:e=>I(()=>t.push(...e))});return t.length?yj(n,Rh(t)):n}));function lwe(e){return vf(R(function*(){let{context:t}=yield*r3,n=yield*u3,r=yield*l3,i=yield*JCe,a=yield*a3,o=$I(HV,{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:swe}),s=$I(BV,{setupStatus:i.setupStatus,setupOwner:i.setupOwner,keyList:({resource:e})=>a.keyList(e)}),c=yield*nwe(),l=iV(t.authCookies.sessionToken.name),u=WV(l),d=bf(mB(u,o).pipe(Cf(iwe(l))),wM(`GET`,`/openapi.json`,fj(GR(u.api))),mB(u,s).pipe(Cf(cwe.layer))),f=bf(VCe(o,{name:`clankerauth-admin`,version:HCe,allowedOrigins:e,instructions:`Owner administration. Listing needs ${cV.read} or ${cV.write}; every other action changes authorization policy and needs ${cV.write}. Create and rotate actions return secrets once.`,authentication:oV}),mB(GV,o)).pipe(Cf(owe(c)));return bf(d,f)}))}const W9=`clankerauth_forward`,G9=(e,t)=>fj({error:t},{status:e}),uwe=e=>vf(R(function*(){let t=yield*Y4,{auth:n,context:r}=yield*r3,i=yield*n3,a=n=>{if(!URL.canParse(n))return;let r=new URL(n);return!r.username&&!r.password&&G4(r,t.allowInsecureHttp)&&W4(r.hostname,e)?r:void 0},o=lg(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=>V4(()=>n.api.getSession({headers:new Headers({cookie:e})}),{unavailable:B4}),f=R(function*(){let e=yield*dM,{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*nie(WCe(o,h)):Ai(),_=Ni(g)?yield*d(`${l}=${g.value}`):null;if(!_)return r[`sec-fetch-mode`]===`navigate`?cj(u(`/forward-auth/continue`,f)):G9(401,`unauthenticated`);let v=Math.floor((yield*Ef)/1e3),{token:y}=yield*V4(()=>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 sj({status:204,headers:{authorization:`Bearer ${y}`}})}),p=R(function*(){let e=yield*dM,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 cj(u(`/login`,u(`/forward-auth/continue`,r)));let s=yield*UCe(o,i);return yield*cj(r).pipe(vj(W9,s,c))}),m=R(function*(){let e=yield*dM,r=new URL(e.url,t.baseURL).searchParams.get(`rd`),i=r&&a(r)||s,{headers:o}=yield*V4(()=>n.api.signOut({headers:new Headers({cookie:e.headers.cookie??``}),returnHeaders:!0}),{refused:z4,unavailable:B4});return yield*yj(cj(i),Rh(o.getSetCookie())).pipe(vj(W9,``,{...c,maxAge:0}))});return bf(wM(`GET`,`/forward-auth`,pp(f,U4)),wM(`GET`,`/forward-auth/continue`,pp(p,U4)),wM(`GET`,`/forward-auth/logout`,pp(m,U4)))})),dwe=/* @__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`]),fwe=/* @__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`]),pwe=/* @__PURE__ */ new Set([`/jwks`,`/.well-known/oauth-protected-resource`,`/.well-known/oauth-authorization-server`,`/.well-known/oauth-authorization-server/api/auth`]),mwe=new Set(gbe),hwe=/^\/assets\/[a-zA-Z0-9_.-]+\.(js|css|woff2)$/,K9=(e,t=200)=>fj(e,{status:t}),q9=K9({error:`Not found`},404),J9=[`Authorization`,`Content-Type`,`Accept`,`Mcp-Protocol-Version`,`Mcp-Method`,`Mcp-Name`],gwe=new Set(J9.map(e=>e.toLowerCase())),_we=(e=gt(new URL(`dist/`,import.meta.resolve(`@clankerauth/web/package.json`))))=>vf(R(function*(){let t=yield*Y4,{auth:n}=yield*r3,{sql:r}=yield*rH,i=yield*n3,a=[.../* @__PURE__ */ new Set([t.baseURL,...t.mcpAllowedOrigins])],o=R(function*(){let e=yield*dM,r=new URL(e.url,t.baseURL),a=r.pathname.replace(/^\/api\/auth/,``);if(!dwe.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:X4},400)}let o=e.method===`GET`||e.method===`HEAD`?void 0:yield*e.arrayBuffer,s=yield*V4(()=>n.handler(new Request(r,{method:e.method,headers:e.headers,body:o})));return oce(s)}).pipe(pp(U4)),s=CM(n=>R(function*(){let r=yield*Ej;yield*n.add(`*`,`/*`,R(function*(){let n=yield*dM;if(n.method!==`GET`&&n.method!==`HEAD`)return q9;let i=new URL(n.url,t.baseURL).pathname,a=mwe.has(i)?`index.html`:hwe.test(i)?i.slice(1):void 0;return a?yield*r.fileResponse(mt(e,a),{contentType:a.endsWith(`.js`)?`text/javascript`:a.endsWith(`.css`)?`text/css`:a.endsWith(`.woff2`)?`font/woff2`:`text/html; charset=utf-8`}).pipe(pp(()=>F(q9))):q9}))})),c=AM(e=>Kye({baseURL:t.baseURL,trustProxy:t.trustProxy})(R(function*(){let n=yield*dM,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=fwe.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=>gwe.has(e))?sj({status:204}):K9({error:`MCP preflight rejected`},403)}else u=l&&n.method===`OPTIONS`?sj({status:204}):yield*e;l&&(u=u.pipe(_j({"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`}),gj(`access-control-allow-credentials`))),o&&(u=u.pipe(hj(`vary`,u.headers.vary?`${u.headers.vary}, Origin`:`Origin`),gj(`access-control-allow-credentials`)),c&&s!==void 0&&(u=u.pipe(_j({"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(_j({"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`:pwe.has(i)?`public, max-age=300`:`no-store`;return u=u.pipe(_j({"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(hj(`strict-transport-security`,`max-age=31536000`))),u})),{global:!0}),l=AM(e=>Xp(e));return bf(lwe(a),t.cookieDomain===void 0?ff:uwe(t.cookieDomain),wM(`GET`,`/healthz`,r`SELECT 1`.pipe(dp(K9({status:`ok`})),pp(U4))),wM(`*`,`/api/auth/*`,o),wM(`*`,`/.well-known/*`,o),s).pipe(Cf(l.layer),Cf(c),Cf(Bue))})),vwe=dm(`Http.nodeHandler`)(function*(e){let t=yield*hle(_we(e));return yield*Rue(t,{scope:yield*Rp})}),ywe=(e,t)=>{let n=vf(V(Y4,({database:e})=>rH.layer(e)));return bf(k9.layer,u3.layer,a3.layer).pipe(wf(l3.layer),wf(r3.layer),wf(n3.layer),wf(n),wf(xf(e,t)))},Y9=`credentials.json`,X9=W({email:U,password:U,secret:U,clientId:Nx(U),clientSecret:Nx(U)}),bwe=Cx(SS(X9)),xwe=kx(X9),Z9=(e,t)=>B(rD,n=>n.writeFileString(pt(e,Y9),`${JSON.stringify(xwe(t),null,2)}\n`,{mode:384})),Swe=dm(`Dev.identity`)(function*(e,t){let n={email:`owner@example.internal`,password:ct(24).toString(`base64url`),secret:ct(32).toString(`hex`)};if(!t)return n;let r=yield*rD,i=pt(e,Y9);return(yield*r.exists(i))?yield*bwe(yield*r.readFileString(i)):(yield*Z9(e,n),n)}),Q9=e=>Error(`Disposable issuer provisioning failed`,{cause:e}),$9=dm(`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*LA,a=yield*i.execute(SA(`${e}/api/auth/sign-in/email`,{headers:{origin:e}}).pipe(EA(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:Qh(a.cookies)}});yield*s.text;let c=Yh(a.cookies,s.cookies);return{cookie:Qh(c),cookies:Object.entries($h(c)).map(([e,t])=>({name:e,value:t}))}}),Cwe=bf(kN,NN,uf(MN,{redirect:`manual`})),wwe=H(function*(e){let t=yield*rD,n=gt(new URL(`./web/`,import.meta.url));if(!(yield*t.exists(pt(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*dp(t.makeDirectory(mt(r),{recursive:!0,mode:448}),mt(r)),a=yield*Hye(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*Swe(i,r!==void 0),l=yield*J4({baseURL:s,secret:sg(c.secret),database:pt(i,`issuer.sqlite`),host:`127.0.0.1`,port:o,mcpAllowedOrigins:[],trustProxy:!1,allowInsecureHttp:e.cookieDomain!==void 0,cookieDomain:e.cookieDomain}),u=yield*kre(ywe(uf(Y4,l),N4.layerWith(e.cimdTransport))),d=da(u,k9),f=yield*Zd(yield*Rp),p=yield*vwe(n).pipe(Mp(u),Lp(Kd,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=da(u,u3),g=da(u,l3),_=da(u,a3),v=e=>Xp(zp(R(function*(){let t=yield*d.find();return t===void 0?yield*rp(/* @__PURE__ */ Error(`Owner setup failed`)):yield*e(t).pipe(Lp(rV,d.caller(t,m.email,!0)))}))).pipe(vp(Q9));(yield*d.find())||(yield*d.create(m).pipe(vp(Q9))),yield*v(()=>qf(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:dm(`Dev.ownerToken`)(function*(e){let{cookie:t}=yield*$9(s,x,m,e.appOrigin),n=yield*LA,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 Twe(e){let t=qd(),n=e=>sm(e.pipe(Lp(Kd,t),Mp(Cwe)),{onFiberStart:rC(t)}),r=lm(Kp($d(t,Md)));try{let t=await n(wwe(e));return{...t.details,apiKey:e=>n(t.apiKey(e)),ownerSession:e=>n(t.ownerSession(e)),ownerToken:e=>n(t.ownerToken(e)),close:()=>sm(r)}}catch(e){throw await sm(r),e}}export{KV as n,Twe as t};
|